How to use Passport to return JWT token for front-end Javascript application on registration and login?
I am trying to create REST API for my public javascript front-end application. I intend to have authorization to the API work with JWTs. I am using Passport to handle the JWTs.
I followed the steps on https://laravel.com/docs/6.x/passport to install Passport.
First of all, which grant is most suitable in my case? Is is Implicit Grant Tokens or Authorization Code Grant?
Secondly, what is the flow of authentication that should be followed? I was planning to use the same endpoints that were brought by Laravel Authentication by returning the JWT to the client after registration, and after login, and invalidating the JWT on logout. Is this plan against best practices?
An an example, in order to return user JWT on registration, I have overwritten the registered() function of the default RegisterController with the following function:
protected function registered(Request $request, $user)
{
if ($request->wantsJson()) {
return response()->json([
'id' => $user->id,
'token' => $user->createToken('Access token')->accessToken,
], 201);
}
return false;
}
And I am using the following code to test it:
public function testRegister()
{
// debug
$this->withoutExceptionHandling();
$payload = [
'email' => '[email protected]',
'password' => 'test2test2',
'password_confirmation' => 'test2test2',
'name' => 'asdaasda',
];
// login
$this->json('POST', '/register', $payload)
->assertStatus(201)
->assertJsonFragment([
'id' => 'placeholder',
]);
}
This throws error RuntimeException: Personal access client not found. Please create one.
I have tried troubleshooting it and created personal client using
php artisan passport:client --personal
But the same exception is still thrown.
I have also tried adding
Passport::enableImplicitGrant();
to AuthServiceProvider.php only to get the same error message:
If my approach is not completely flawed, how can I generate JWT tokens to the user upon registration using the most suitable grant?
Please or to participate in this conversation.