API Authentication

Introduction

By default, Laravel ships with a simple solution to API authentication via a random token assigned to each user of your application. In your config/auth.php configuration file, an api guard is already defined and utilizes a token driver. This driver is responsible for inspecting the API token on the incoming request and verifying that it matches the user's assigned token in the database.

Note: While Laravel ships with a simple, token based authentication guard, we strongly recommend you consider using Laravel Passport for robust, production applications that offer API authentication.

Configuration

Database Preparation

Before using the token driver, you will need to create a migration which adds an api_token column to your users table:

  1. Schema::table('users', function ($table) {
  2. $table->string('api_token', 80)->after('password')
  3. ->unique()
  4. ->nullable()
  5. ->default(null);
  6. });

Once the migration has been created, run the migrate Artisan command.

{tip} If you choose to use a different column name, be sure to update your API's storage_key configuration option within the config/auth.php configuration file.

Generating Tokens

Once the api_token column has been added to your users table, you are ready to assign random API tokens to each user that registers with your application. You should assign these tokens when a User model is created for the user during registration. When using the authentication scaffolding provided by the make:auth Artisan command, this may be done in the create method of the RegisterController:

  1. use Illuminate\Support\Str;
  2. use Illuminate\Support\Facades\Hash;
  3. /**
  4. * Create a new user instance after a valid registration.
  5. *
  6. * @param array $data
  7. * @return \App\User
  8. */
  9. protected function create(array $data)
  10. {
  11. return User::create([
  12. 'name' => $data['name'],
  13. 'email' => $data['email'],
  14. 'password' => Hash::make($data['password']),
  15. 'api_token' => Str::random(60),
  16. ]);
  17. }

Hashing Tokens

In the examples above, API tokens are stored in your database as plain-text. If you would like to hash your API tokens using SHA-256 hashing, you may set the hash option of your api guard configuration to true. The api guard is defined in your config/auth.php configuration file:

  1. 'api' => [
  2. 'driver' => 'token',
  3. 'provider' => 'users',
  4. 'hash' => true,
  5. ],

Generating Hashed Tokens

When using hashed API tokens, you should not generate your API tokens during user registration. Instead, you will need to implement your own API token management page within your application. This page should allow users to initialize and refresh their API token. When a user makes a request to initialize or refresh their token, you should store a hashed copy of the token in the database, and return the plain-text copy of token to the view / frontend client for one-time display.

For example, a controller method that initializes / refreshes the token for a given user and returns the plain-text token as a JSON response might look like the following:

  1. <?php
  2. namespace App\Http\Controllers;
  3. use Illuminate\Support\Str;
  4. use Illuminate\Http\Request;
  5. class ApiTokenController extends Controller
  6. {
  7. /**
  8. * Update the authenticated user's API token.
  9. *
  10. * @param \Illuminate\Http\Request $request
  11. * @return array
  12. */
  13. public function update(Request $request)
  14. {
  15. $token = Str::random(60);
  16. $request->user()->forceFill([
  17. 'api_token' => hash('sha256', $token),
  18. ])->save();
  19. return ['token' => $token];
  20. }
  21. }

{tip} Since the API tokens in the example above have sufficient entropy, it is impractical to create "rainbow tables" to lookup the original value of the hashed token. Therefore, slow hashing methods such as bcrypt are unnecessary.

Protecting Routes

Laravel includes an authentication guard that will automatically validate API tokens on incoming requests. You only need to specify the auth:api middleware on any route that requires a valid access token:

  1. use Illuminate\Http\Request;
  2. Route::middleware('auth:api')->get('/user', function(Request $request) {
  3. return $request->user();
  4. });

Passing Tokens In Requests

There are several ways of passing the API token to your application. We'll discuss each of these approaches while using the Guzzle HTTP library to demonstrate their usage. You may choose any of these approaches based on the needs of your application.

Query String

Your application's API consumers may specify their token as an api_token query string value:

  1. $response = $client->request('GET', '/api/user?api_token='.$token);

Request Payload

Your application's API consumers may include their API token in the request's form parameters as an api_token:

  1. $response = $client->request('POST', '/api/user', [
  2. 'headers' => [
  3. 'Accept' => 'application/json',
  4. ],
  5. 'form_params' => [
  6. 'api_token' => $token,
  7. ],
  8. ]);

Bearer Token

Your application's API consumers may provide their API token as a Bearer token in the Authorization header of the request:

  1. $response = $client->request('POST', '/api/user', [
  2. 'headers' => [
  3. 'Authorization' => 'Bearer '.$token,
  4. 'Accept' => 'application/json',
  5. ],
  6. ]);