Home  >  Article  >  PHP Framework  >  Laravel development: How to implement API authentication and authorization using Laravel Sanctum?

Laravel development: How to implement API authentication and authorization using Laravel Sanctum?

PHPz
PHPzOriginal
2023-06-13 19:07:182628browse

Laravel is a popular PHP web development framework that provides many powerful features and tools to simplify the development and maintenance of web applications. Laravel Sanctum is a plugin for the Laravel framework that provides API authentication and authorization capabilities to easily protect your API endpoints from unauthorized access.

In this article, we will learn how to implement API authentication and authorization using Laravel Sanctum.

1. What is Laravel Sanctum?

Laravel Sanctum is a lightweight authentication package that provides simple but powerful API authentication and authorization functionality. It is based on Laravel middleware and HTTP authentication, allowing us to securely attach authentication tokens to API requests.

Laravel Sanctum supports two authentication methods: Cookie-based authentication and Token-based authentication. Cookie-based authentication uses Laravel middleware to verify that a valid authentication cookie is present in the request. Another way to verify the Token in the Header class and check if it is valid.

2. Install Laravel Sanctum

Before we begin, we need to install Laravel Sanctum first. Laravel Sanctum can be easily installed using the composer package manager:

composer require laravel/sanctum

Of course, it can also be installed manually by adding the following requirements in the composer.json file:

{
  "require": {
    "laravel/sanctum": "^2.9"
  }
}

Once completed, run the following Command to publish Laravel Sanctum configuration files and database migration files:

php artisan vendor:publish --tag=sanctum-config
php artisan vendor:publish --tag=sanctum-migrations
php artisan migrate

3. Configure Laravel Sanctum

  1. First, you need to add laravel/sanctum middleware to your application’s HTTP core middle.

Modify the app/Http/kernel.php file and add the Sanctum middleware:

// app/Http/Kernel.php

protected $middleware = [
    // ...
    LaravelSanctumHttpMiddlewareEnsureFrontendRequestsAreStateful::class,
];

protected $middlewareGroups = [
    'web' => [
        // ...
    ],

    'api' => [
        LaravelSanctumHttpMiddlewareEnsureFrontendRequestsAreStateful::class,
        'throttle:api',
        IlluminateRoutingMiddlewareSubstituteBindings::class,
    ],
];

This will ensure that Sanctum's cookie-based authentication can be used during every request.

  1. Next, you need to configure the auth configuration file.

Open the config/auth.php file, find defaults and guards and configure them to use sanctum.

// config/auth.php

'defaults' => [
    'guard' => 'api',
    'passwords' => 'users',
],

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

    'api' => [
        'driver' => 'sanctum',
        'provider' => 'users',
        'hash' => false,
    ],
],

This will allow us to use Sanctum for token based authentication.

  1. Add Sanctum provider.

If you are using a new version of Laravel, you do not need to add a provider. If you are using an older version, please open the config/app.php file and add the following lines in the providers array:

LaravelSanctumSanctumServiceProvider::class,

IV. Create Authorization Token

Now, we have configured Laravel Sanctum, next we will learn how to use Sanctum to create authorization tokens.

  1. After the user logs in, create an API token for the user in the users table.
public function createToken(Request $request)
{
    $user = Auth::attempt(['email' => $request->input('email'), 'password' => $request->input('password')]);

    if($user) {
        $token = $user->createToken('API Token')->plainTextToken;
        
        return response()->json([
          'token' => $token,
        ]);
    } else {
        return response()->json([
          'message' => 'Invalid credentials',
        ], 401);
    }
}
  1. After you create the token, you can add it to the Authorization header of each request. It can be set as follows in the axios request:
axios.defaults.headers.common['Authorization'] = `Bearer ${token}`;

5. Implement API authentication and authorization

After creating the authorization token, we can use Sanctum to protect the API endpoint from Unauthorized access. We can use Laravel routing middleware to check the authentication token and deny unauthorized access.

  1. First, define the protected API route in the api.php file.
// routes/api.php

Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
    return $request->user();
});

This route will be protected using the Sanctum auth middleware.

  1. Next, access the protected route and view the results. This can be tested with the following command:
php artisan serve

Now, the /api/user route can be accessed to view the details of the logged in user. Now, without the Authorization header, you won't be able to access it and will return a 401 Unauthorized HTTP status code.

6. Ending

Laravel Sanctum is a powerful and easy-to-use authentication and authorization solution that can easily implement authentication and authorization in Laravel web applications and web APIs. It easily protects your API endpoints from unauthorized access and allows you to easily control which users can access which API endpoints. In this article, we learned how to install and configure Laravel Sanctum and saw how to use it to create authorization tokens and implement API authentication and authorization.

The above is the detailed content of Laravel development: How to implement API authentication and authorization using Laravel Sanctum?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn