Giter Site home page Giter Site logo

fusionauth / fusionauth-php-client Goto Github PK

View Code? Open in Web Editor NEW
20.0 14.0 11.0 524 KB

PHP client library for FusionAuth

Home Page: https://fusionauth.io

License: Apache License 2.0

PHP 99.94% Twig 0.06%
fusionauth php-client rest-client api-client php fusionauth-client

fusionauth-php-client's Introduction

FusionAuth PHP Client semver 2.0.0 compliant

Intro

If you're integrating FusionAuth with a PHP application, this library will speed up your development time. Please also make sure to check our SDK Usage Suggestions page.

For additional information and documentation on FusionAuth refer to https://fusionauth.io.

Install

The most preferred way to use the client library is to install the fusionauth/fusionauth-client package via Composer by running the command below at your project root folder.

composer require fusionauth/fusionauth-client

Then, include the composer autoloader in your PHP files.

require __DIR__ . '/vendor/autoload.php';

Examples

Set Up

First, you have to make sure you have a running FusionAuth instance. If you don't have one already, the easiest way to install FusionAuth is via Docker, but there are other ways. By default, it'll be running on localhost:9011.

Then, you have to create an API Key in the admin UI to allow calling API endpoints.

You are now ready to use this library!

Error Handling

After every request is made, you need to check for any errors and handle them. To avoid cluttering things up, we'll omit the error handling in the next examples, but you should do something like the following.

// $result is the response of one of the endpoint invocations from the examples below

if (!$result->wasSuccessful()) {
    echo "Error!" . PHP_EOL;
    echo "Got HTTP {$result->status}" . PHP_EOL;
    if (isset($result->errorResponse->fieldErrors)) {
        echo "There are some errors with the payload:" . PHP_EOL;
        var_dump($result->errorResponse->fieldErrors);
    }
    if (isset($result->errorResponse->generalErrors)) {
        echo "There are some general errors:" . PHP_EOL;
        var_dump($result->errorResponse->generalErrors);
    }
}

Create the Client

To make requests to the API, first you need to create a FusionAuthClient instance with the API Key created and the server address where FusionAuth is running.

$client = new FusionAuth\FusionAuthClient(
    apiKey: "<paste the API Key you generated here>",
    baseURL: "http://localhost:9011", // or change this to whatever address FusionAuth is running on
);

Create an Application

To create an Application, use the createApplication() method.

$result = $client->createApplication(
    applicationId: null, // Leave this empty to automatically generate the UUID
    request: [
        'application' => [
            'name' => 'ChangeBank',
        ],
    ],
);

// Handle errors as shown in the beginning of the Examples section

// Otherwise parse the successful response
var_dump($result->successResponse->application);

Check the API docs for this endpoint

Adding Roles to an Existing Application

To add roles to an Application, use createApplicationRole().

$result = $client->createApplicationRole(
    applicationId: 'd564255e-f767-466b-860d-6dcb63afe4cc', // Existing Application Id
    roleId: null, // Leave this empty to automatically generate the UUID
    request: [
        'role' => [
            'name' => 'customer',
            'description' => 'Default role for regular customers',
            'isDefault' => true,
        ],
    ],
);

// Handle errors as shown in the beginning of the Examples section

// Otherwise parse the successful response
var_dump($result->successResponse->role);

Check the API docs for this endpoint

Retrieve Application Details

To fetch details about an Application, use retrieveApplication().

$result = $client->retrieveApplication(
    applicationId: 'd564255e-f767-466b-860d-6dcb63afe4cc',
);

// Handle errors as shown in the beginning of the Examples section

// Otherwise parse the successful response
var_dump($result->successResponse->application);

Check the API docs for this endpoint

Delete an Application

To delete an Application, use deleteApplication().

$result = $client->deleteApplication(
    applicationId: 'd564255e-f767-466b-860d-6dcb63afe4cc',
);

// Handle errors as shown in the beginning of the Examples section

// Otherwise parse the successful response
// Note that $result->successResponse will be empty

Check the API docs for this endpoint

Lock a User

To prevent a User from logging in, use deactivateUser().

$result = $client->deactivateUser(
    'fa0bc822-793e-45ee-a7f4-04bfb6a28199',
);

// Handle errors as shown in the beginning of the Examples section

// Otherwise parse the successful response

Check the API docs for this endpoint

Registering a User

To register a User in an Application, use register().

The code below also adds a customer role and a custom appBackgroundColor property to the User Registration.

$result = $client->register(
    userId: 'fa0bc822-793e-45ee-a7f4-04bfb6a28199',
    request: [
        'registration' => [
            'applicationId' => 'd564255e-f767-466b-860d-6dcb63afe4cc',
            'roles' => [
                'customer',
            ],
            'data' => [
                'appBackgroundColor' => '#096324',
            ],
        ],    
    ],
);

// Handle errors as shown in the beginning of the Examples section

// Otherwise parse the successful response

Check the API docs for this endpoint

Questions and support

If you find any bugs in this library, please open an issue. Note that changes to the FusionAuthClient class have to be done on the FusionAuth Client Builder repository, which is responsible for generating that file.

But if you have a question or support issue, we'd love to hear from you.

If you have a paid plan with support included, please open a ticket in your account portal. Learn more about paid plan here.

Otherwise, please post your question in the community forum.

Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/FusionAuth/fusionauth-php-client.

Note: if you want to change the FusionAuthClient class, you have to do it on the FusionAuth Client Builder repository, which is responsible for generating all client libraries we support.

License

This code is available as open source under the terms of the Apache v2.0 License.

Upgrade Policy

This library is built automatically to keep track of the FusionAuth API, and may also receive updates with bug fixes, security patches, tests, code samples, or documentation changes.

These releases may also update dependencies, language engines, and operating systems, as we'll follow the deprecation and sunsetting policies of the underlying technologies that it uses.

This means that after a dependency (e.g. language, framework, or operating system) is deprecated by its maintainer, this library will also be deprecated by us, and will eventually be updated to use a newer version.

fusionauth-php-client's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

fusionauth-php-client's Issues

Getting error due to Silent Mode

I am having some issues with configuring. From my docker log I am getting:

2021-02-19 6:31:49.102 AM WARN com.inversoft.configuration.BasePropertiesFileInversoftConfiguration - Your FusionAuth configuration file [/usr/local/fusionauth/fusionauth-app/apache-tomcat/../../config/fusionauth.properties] needs attention. Here are the warnings:

  • You are using a deprecated configuration property name of [DATABASE_ROOT_USER]. The new allowed names for that property are [database.root.username]

This is followed by this Silent Mode Error:
---------------------------------- Entering Silent Configuration Mode -----------------------------------

2021-02-19 6:31:49.153 AM ERROR com.inversoft.maintenance.db.JDBCURL - Could not parse jdbcString [jdbc:mysql:database-2.cwymdn16cxes.us-east-1.rds.amazonaws.com]
2021-02-19 6:31:49.162 AM ERROR com.inversoft.maintenance.db.DatabaseSilentConfigurationWorkflowTask - Encountered an error while running silent mode
java.lang.IllegalStateException: Invalid database URL [jdbc:mysql:database-2.cwymdn16cxes.us-east-1.rds.amazonaws.com]

I don't know why it is going into silent mode? Where is the config file located? I can't seem to find fusionauth.properties.

getting invalid_redirect_uri

I am working on a passwordless login script. The email to the user works fine. But when the user clicks on the link in the email he gets invalid_redirect_uri (see image)
Screenshot from 2021-04-28 07-56-41

Here is the uri as it appears in the email:
<a href="http://fusionauth.ngrok.io/oauth2/passwordless/DM4l8LlDvIGzDOcixtjgCMMsFX8-4GqMbsCPGC7k0Cs?tenantId=4272f95b-0989-4892-badc-0ef6b934885f&amp;client_id=f603697d-41ea-4c53-ac2d-e935d5e34221&amp;redirect_uri=35.153.28.164%2Findex.php%2FConfigure%2Freport_generator_amazing&amp;response_type=code&amp;scope=openid&amp;state=bandfrombossanova%40gmail.com" target="_blank" data-saferedirecturl="https://www.google.com/url?q=http://fusionauth.ngrok.io/oauth2/passwordless/DM4l8LlDvIGzDOcixtjgCMMsFX8-4GqMbsCPGC7k0Cs?tenantId%3D4272f95b-0989-4892-badc-0ef6b934885f%26client_id%3Df603697d-41ea-4c53-ac2d-e935d5e34221%26redirect_uri%3D35.153.28.164%252Findex.php%252FConfigure%252Freport_generator_amazing%26response_type%3Dcode%26scope%3Dopenid%26state%3Dbandfrombossanova%2540gmail.com&amp;source=gmail&amp;ust=1619697345074000&amp;usg=AFQjCNFvFntwmztFJBGSbqjC1o8nwwfa9A"> <button style="border:none;color:white;padding:15px 32px;text-align:center;text-decoration:none;font-size:16px;margin:4px 2px;background-color:#008cba"> Click Here to Login! </button> </a>

I am using docker and fusionauth/fusionauth-app:1.19.7.
Is the error message correct? How can I fix this?

Missing PHP version constraint

The composer.json file is missing a php version constraint, so it's unclear which versions of PHP are supported by this library.

Please add this information.

Cut 'empty' params in request (JSONBody)

I'm trying to do something like this:
$request = [ 'loginId' => $hostData->getUser()->getUsername(), 'sendForgotPasswordEmail' => false ]; $response = $this->client->forgotPassword($request);
but library remove params sendForgotPasswordEmail. I found something like this in code (JSONBodyHandler:427)
$this->body = json_encode(array_filter($bodyObject));
function array_filter without callback remove all empty records from array. In my case remove sendForgotPasswordEmail but it is general problem with this function. It remove values with false and 0.

Delete Group Members does not have the expected API or its API is not documented

According to the FusionAuth documentation, there are two ways to remove a user from a group, and both use the URL to pass the request parameters to the FusionAuth API.

Either:
DELETE /api/group/member/{memberId}
or
DELETE /api/group/member?groupId={groupId}&userId={userId}

The method signature for deleteGroupMembers in this library seems designed to accept a JSON request body, but it is not clear how this body should be structured in order to remove a given user from a given group, since the documentation given above does not include removing users from a group using a request body.

Methods using the JWT authorization are failing

Expected behavior

Calling any method using the JWT authorization should work just fine.

Actual behavior

The JWT authorization header is added after the API key authorization header. Curl will only use the first header, thus ignoring the JWT authorization header.

Possible solution

Replace any existing Authorization header when adding a new one.

PHP Login User Example Does Not Work

The provided PHP login user example does not work for me.

Please assist me to solve it.

He's my code:

$apiKey = "[mykey]";

$client = new FusionAuth\FusionAuthClient($apiKey, "http://localhost:9011/api/login");

$applicationId = "[myid]";

$request = array();
$request["applicationId"] = $applicationId;
$request["email"] = "[email protected]";
$request["password"] = "12345";
$result = $client->login(json_encode($request));
if ($result->wasSuccessful()) {
$user = json_encode($result->successResponse->user);
echo $user;
}else{
$user = json_encode($result->errorResponse);
echo $user;
}

Here is the error I get:

{"fieldErrors":{"applicationId":[{"code":"[couldNotConvert]applicationId","message":"Invalid [applicationId]. This must be a valid UUID String (e.g. 25a872da-bb44-4af8-a43d-e7bcb5351ebc)."}],"loginId":[{"code":"[blank]loginId","message":"You must specify the [loginId] property."}],"password":[{"code":"[blank]password","message":"You must specify the [password] property."}],"userId":[{"code":"[couldNotConvert]userId","message":"Invalid userId on the URL [api]. This must be a valid UUID String (e.g. 25a872da-bb44-4af8-a43d-e7bcb5351ebc)."}]}}

Thanks.

Support php 8.1

Currently this library does not support PHP version 8.1.x
This has to do with breaking changes with some deprecations and backward incompatible changes

Versions 8.0.x and below do work without any problems.
For now I can't update my app to 8.1 since it is dependent on this library.

Timeouts and other cURL errors are not handled

When there's a read timeout, the response looks something like this:

FusionAuth\ClientResponse::__set_state(array(
   'errorResponse' => NULL,
   'exception' => NULL,
   'method' => 'PATCH',
   'request' => 
  array (
    'user' => 
    array (
        /* ... */
    ),
  ),
   'successResponse' => NULL,
   'status' => 0,
))

i.e. The errorResponse, exception, and successResponse are all NULL.

I think the code needs to use curl_errno to check for errors.

PSR autoload is failing because of case insensitive namespace

Expected behavior

FusionAuthClient class should autoload when used in code.

Actual behavior

Autoloading is failing on a case sensitive file system. The declared namespace is fusionauth, but the directory holding the class is FusionAuth. Composer will look for the case sensitive directory fusionauth and will not find it.

Possible solution

Rename the namespace in FusionAuthClient.php from fusionauth to FusionAuth.

forgotPassword method issue with TenantId

Hi

When sending a request using FA client v1.12 we're getting this message, despite the tenant id being passed and correct:

A Tenant Id is required to complete this request. To complete this request, you may assign a Tenant to your API key, or add the X-FusionAuth-TenantId HTTP request header with the Tenant Id.

The same problem doesn't happen on 1.11 or for any other API calls we use.

Is issue #833 back again?

I just added a third tenant and i am seeing this:
A 404 status code is returned from the Start Passwordless API when more than one tenant exists in FusionAuth.

This was solved in "Resolves GitHub Issue #833, thanks to @atrauzzi for reporting and helping us track this one down!"
This was reported solve din 1.19.0. I am using 1.19.7 and also experience this (it is repeatable). Can this be?

Please advise.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.