API certification
- Token Generation
- Hash Token
- Pass the token in the request
Introduction
By default, Laravel provides a simple solution for API authentication via a random token assigned to each user of the application. In your
config/auth.php
configuration file, aapi
watcher using thetoken
driver has been defined. This driver is responsible for checking the API token on incoming requests and verifying that it matches the user-assigned token in the database.Note: While Laravel ships with a simple token-based authentication protection, we strongly recommend that you consider Laravel Passport for robust production implementations that provide API authentication. app.
Configuration
##Database Preparation Before using thetoken
migratedriver, you need to create a migration which will add a
api_token## to yourusers
table # Column:
After the migration is created, run theSchema::table('users', function ($table) { $table->string('api_token', 80)->after('password') ->unique() ->nullable() ->default(null); });
Artisan command.
Token generationAdd the
api_tokencolumn to your
users
After the table, you can assign random API tokens to each user in your application. These tokens should be assigned when theUser
model is created during registration. When using the authentication scaffolding provided by themake:auth
Artisan command, this can be done in thecreate
method ofRegisterController
:use Illuminate\Support\Str;use Illuminate\Support\Facades\Hash; /** * 在有效注册之后创建一个新用户实例: * * @param array $data * @return \App\User */ protected function create(array $data){ return User::create([ 'name' => $data['name'], 'email' => $data['email'], 'password' => Hash::make($data['password']), 'api_token' => Str::random(60), ]); }
Hash TokenIn the example above, the API token is stored in the database as plain text. If you wish to hash API tokens using the SHA-256 hash, you can set the
hashoption of the
api
watcher configuration totrue
.api
The watcher is defined in yourconfig/auth.php
configuration file:'api' => [ 'driver' => 'token', 'provider' => 'users', 'hash' => true, ],
Generate Hash Token
When using hash tokens, you should not generate API tokens during user registration. Instead, you need to implement your own API token management page in your application. This page should allow users to initialize and refresh their API tokens. When a user makes an initialization or refresh token request, you should store a hashed copy of the token in the data and return a plain text copy of the token to the view/front-end client for display once.
For example, a controller method that initializes/refreshes a token for a given user and returns the plain text token as a JSON response might look like this:
<?php namespace App\Http\Controllers; use Illuminate\Support\Str; use Illuminate\Http\Request; class ApiTokenController extends Controller{ /** * 更新已经验证过的用户的 API 令牌。 * * @param \Illuminate\Http\Request $request * @return array */ public function update(Request $request) { $token = Str::random(60); $request->user()->forceFill([ 'api_token' => hash('sha256', $token), ])->save(); return ['token' => $token]; } }
{tip} Because The API token in the above example has enough entropy that it is impractical to create a "rainbow tables" to find the original value of the hashed token. Therefore, there is no need to use slow hashing methods like
bcrypt
:Route Protection
Laravel includes an authentication watcher that can automatically validate API tokens for incoming requests. You just need to specify the
auth:api
middleware on any route that requires a valid access token:use Illuminate\Http\Request; Route::middleware('auth:api')->get('/user', function(Request $request) { return $request->user(); });
Passing the token in the request
There are several ways to pass the API token to your application. We will discuss these methods while demonstrating their usage using the Guzzle HTTP library. You can choose any of these methods based on the needs of your application.
Request Parameters
Your application’s API consumers can provide their token as the
api_token
query string value:$response = $client->request('GET', '/api/user?api_token='.$token);
Request Payload
API consumers of an application can include their API token in the form parameter of the request in the form of
api_token
:$response = $client->request('POST', '/api/user', [ 'headers' => [ 'Accept' => 'application/json', ], 'form_params' => [ 'api_token' => $token, ], ]);
Bearer Token
An application's API consumer can provide its API token as a
Bearer
in theAuthorization
header of the request Token:$response = $client->request('POST', '/api/user', [ 'headers' => [ 'Authorization' => 'Bearer '.$token, 'Accept' => 'application/json', ], ]);