Laravel API Authentication


Laravel API Authentication – The Laravel API Authentication typically uses tokens to authenticate user and do not maintain session state between requests.


Laravel API Authentication.

Let us understand how to use laravel API Authentication.

Function:-

There are followings functions available in laravel API Authentication.

  • 1. Introduction.
  • 2. Installation.
  • 3. Configuration.
  • 4. Issuing Access Tokens.
  • 5. Password Grant Tokens.
  • 6. Implicit Grant Tokens.
  • 7. Client Credentials Grant Tokens.
  • 8. Personal Access Tokens.
  • 9. Protecting Routes.
  • 10. Token Scopes.
  • 11. Consuming Your API With JavaScript.
  • 12. Events.
  • 13. Testing.

1. Introduction.

Laravel makes easy to perform authentication via login forms. Api authentication uses token to authenticate and do not maintain session state between request. It makes API authentication a breeze using passport which provides a full OAuth2 server implementation for your Laravel application in a matter of minutes.

2. Installation.

Lets start to install passport via composer.

composer require laravel/passport

Then, register the passport service provider in the providers array of your config/app.php file.

Laravel\Passport\PassportServiceProvider::class,

The Passport service provider registers its own database migration directory with the framework, so you should migrate your database after registering the provider.

php artisan migrate

Then, you should run the passport:install command. This command will create encryption key need to generate secure access token.

php artisan passport:install

After running this command add the Laravel/Passport/HasApiTokens trait to your App/User model.

Let’s look at a simple example.

<?php
namespace App;
use Laravel\Passport\HasApiTokens;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use HasApiTokens, Notifiable;
}

Then, you should call the Passport::routes method within the boot method of your AuthServiceProvider.

Let's look at a simple example.

<?php
namespace App\Providers;
use Laravel\Passport\Passport;
use Illuminate\Support\Facades\Gate;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;

class AuthServiceProvider extends ServiceProvider
{
   
    protected $policies = [
        'App\Model' => 'App\Policies\ModelPolicy',
    ];

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

        Passport::routes();
    }
}

Finally in your config/auth.php configure file, you should set the driver option of the api authentication guard to passport.

'guards' => [
    'web' => [
        'driver' => 'session',
        'provider' => 'users',
    ],

    'api' => [
        'driver' => 'passport',
        'provider' => 'users',
    ],
],

Frontend Quickstart

Passport ships with a JSON API that you may use to allow your users to create clients and personal access tokens.

To publish the passport Vue components, use the vendor:publish Artsian command.

php artisan vendor:publish --tag=passport-components

The published components will be placed in your resources/assets/js/components directory.

Vue.component(
    'passport-clients',
    require('./components/passport/Clients.vue')
);

Vue.component(
    'passport-authorized-clients',
    require('./components/passport/AuthorizedClients.vue')
);

Vue.component(
    'passport-personal-access-tokens',
    require('./components/passport/PersonalAccessTokens.vue')
);

After registering the components, make sure to run npm run dev to recompile your assets.

<passport-clients></passport-clients>
<passport-authorized-clients></passport-authorized-clients>
<passport-personal-access-tokens></passport-personal-access-tokens>

Deploying Passport

When deploying passport to your production server for the first time, you will likely need to run the passport:keys command.

php artisan passport:keys

3. Configuration.

Token Lifetimes

If you want to configure a shorter token lifetime, you can use the tokensExpireIn and refreshTokensExpireIn methods.

Let's look at a simple example.

use Carbon\Carbon;

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

    Passport::routes();

    Passport::tokensExpireIn(Carbon::now()->addDays(15));

    Passport::refreshTokensExpireIn(Carbon::now()->addDays(30));
}

4. Issuing Access Tokens.

When we are using authorization codes, a client application will redirect a user to your server where they will either approve or deny the request to issue an access token to the client.

Managing Clients

When developer building application that needs to interact with your application API will need to register their application with yours by creating a client. The consist of providing the name of their application and a URL that can redirect to after users approve their request for authorization.

The passport:client command

To create a client is using the passport:client Artsian command. This command may be used to create your own clients for testing your oAuth2 functionality. When you run the client command Passport will prompt you for more information about your client and will provide you with a client ID and secret.

php artisan passport:client

JSON API

Passport provides a JSON API that you can use to create clients.

GET /oauth/clients

This route return all of the clients for the authenticated user.

axios.get('/oauth/clients')
    .then(response => {
        console.log(response.data);
    });

POST /oauth/clients

This route is used to create new clients. It requires two pieces of data, the client name and redirect URL.

const data = {
    name: 'Client Name',
    redirect: 'http://example.com/callback'
};

axios.post('/oauth/clients', data)
    .then(response => {
        console.log(response.data);
    })
    .catch (response => {
        // List errors on response...
    });

PUT /oauth/clients/{client-id}

This route is used to update clients.

const data = {
    name: 'New Client Name',
    redirect: 'http://example.com/callback'
};

axios.put('/oauth/clients/' + clientId, data)
    .then(response => {
        console.log(response.data);
    })
    .catch (response => {
        // List errors on response...
    });

DELETE /oauth/clients/{client-id}

This route is used to delete clients.

axios.delete('/oauth/clients/' + clientId)
    .then(response => {
        //
    });

Requesting Tokens

Redirecting For Authorization

Once a client has been created, developers may use their client ID and secret to request an authorization code and access token from your application.

Route::get('/redirect', function () {
    $query = http_build_query([
        'client_id' => 'client-id',
        'redirect_uri' => 'http://example.com/callback',
        'response_type' => 'code',
        'scope' => '',
    ]);

    return redirect('http://your-app.com/oauth/authorize?'.$query);
});

Advertisements

Add Comment

📖 Read More