API Authentication

    By default, Laravel ships with a simple solution to API authentication via a random token assigned to each user of your application. In your 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.

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

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

    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 provided by the laravel/ui Composer package, this may be done in the create method of the RegisterController:

    1. use Illuminate\Support\Facades\Hash;
    2. use Illuminate\Support\Str;
    3. /**
    4. *
    5. * @param array $data
    6. * @return \App\User
    7. */
    8. protected function create(array $data)
    9. return User::forceCreate([
    10. 'name' => $data['name'],
    11. 'email' => $data['email'],
    12. 'password' => Hash::make($data['password']),
    13. 'api_token' => Str::random(80),
    14. ]);
    15. }

    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:

    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\Http\Request;
    4. use Illuminate\Support\Str;
    5. class ApiTokenController extends Controller
    6. {
    7. * Update the authenticated user's API token.
    8. *
    9. * @return array
    10. */
    11. public function update(Request $request)
    12. {
    13. $token = Str::random(80);
    14. $request->user()->forceFill([
    15. 'api_token' => hash('sha256', $token),
    16. ])->save();
    17. return ['token' => $token];
    18. }
    19. }

    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:

    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:

    Bearer Token

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