mercredi 6 mars 2019

Use a REST api to login users

I have a REST API project that serve some protected resources. When an user want interact with de API, first must be authenticate in it.

To authenticate users, the API have a single endpoint /tokens that receive the credentials and send as response, if succeed, a Json Web Token.

Now, i need implement a login form in a Laravel 5.8 MVC project that allow the API users exchange the Json Web Token. To do that, i thought in extend the authentication module (creating a custom user provider) but, i don't have success.

In first place, i created and registered new user provider class:

app/Services/Auth/BeonweUserProvider.php

use Illuminate\Contracts\Auth\UserProvider;
use Illuminate\Contracts\Auth\Authenticatable;

class BeonweUserProvider implements UserProvider
{
    public function retrieveByCredentials(array $credentials)
    {
       // Makes an API call and retrive the JWT.
       // Return an Authenticatable
    }

    public function validateCredentials(Authenticatable $user, Array $credentials)
    {
       // The API did it ...
       return true;
    }
}

app/Providers/AuthServiceProvider.php

public function boot()
{
   $this->registerPolicies();

   Auth::provider('BeonweUser', function ($app, array $config) {
      $authenticable = 'App\Services\Auth\AuthenticatedUser';
      return new BeonweUserProvider($app->make($authenticable));
   });
}

config/auth.php

'defaults' => [
    'guard' => 'web',
    'passwords' => 'users',
],    
'guards' => [
    'web' => [
        'driver' => 'session',
        'provider' => 'beonwe',
    ],
 ],
'providers' => [
    'beonwe' => [
        'driver' => 'BeonweUser'
    ]
 ]

After that, i create a simple Authenticable User class:

class AuthenticatedUser extends User implements Authenticatable
{
    protected $access_token;

    public function getAuthIdentifierName()
    {
        return 'access_token';
    }


    public function getAuthIdentifier()
    {
        return $this->{$this->getAuthIdentifierName()};
    }
}

When an user submit the login form, the user provider fetchs sucessfully the access token, and return an instance of Authenticable. In the session value, i can see the correct JWT

login_web_59ba36addc2b2f9401580f014c7f58ea4e30989d => eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE1NTE4ODQ4NDIsImV4cCI6MTU1MTkxNzI0MiwidWlkIjoxLCJhaWQiOm51bGwsInR5cGUiOiJzdGFuZGFyZCJ9.G6lmrC-nEZWNWn6XIq9Du_GHtq5xJkNfWM5zpiDg31M

But Laravel, redirects to the login form again. Any ideas ?

Note: I am using the LoginController provided by Laravel fresh install.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire