Search code examples
phpapiauthenticationlaravel-5laravel-passport

Laravel - Creating API tokens to use internally for each user


Every user of my application may use the API only within the application with Vue. The old api_token solution works for me, but it seems to be insecure since the api_token is the only thing that separates the user from the data.

I've read about Passport that uses OAuth2 methodology which is far more secure than a simple api_token.

Is there a way to use Passport to achieve this? Note that every time a user is created, I must create a API token to him.

We have no plans to open this API for external applications.


Solution

  • you can create tokens for every user, have a look at below code.

    // find specific user
    $user = App\User::find(1);
    
    // Creating a token without scopes...
    $token = $user->createToken('Token Name')->accessToken;
    
    // Creating a token with scopes...
    $token = $user->createToken('My Token', ['place-orders'])->accessToken;
    

    you can create token after user creation too, just add logic of token after a user has been created.