Taiwan before and after doing separate projects, certification is a must, because the http is stateless. After the user logs in successfully foreground, the background to the foreground returned token. After requesting the foreground to the background each time carrying token.
Principle is very simple:
Authorization request header is added in the foreground, the following
Background to take a value, then the user table to match api_token columns, if found described verification is successful, and returns the relevant information.
Laravel itself comes with several forms of authentication method implemented under the following authentication token described.
In the foreground to the background when initiating the request to carry a token
Background need to make a return to the current user's login information api, address /api/user
First add routes, when to route / api.php add
Route::middleware('auth:api')->get('/user', function (Request $request) { echo $request->user(); });
If the browser to directly access http://mydomain.com/api/user
will return 401 Unauthorized
because there are following in config / auth.php key configuration
'guards' => [ 'web' => [ 'driver' => 'session', 'provider' => 'users', ], 'Fire' => [ 'driver' => 'token', 'provider' => 'users', ], ],
Access can be seen walking through the api is token authentication, and provides no authentication token so they failed to return a 401.
'driver' => 'token'
The actual call is \vendor\laravel\framework\src\Illuminate\Auth\TokenGuard.php
above comes we need to provide api_token parameters in the request in order to distinguish which users need to add api_token field in the user table
Certification procedure call method is getTokenForRequest
public function getTokenForRequest() { $token = $this->request->query($this->inputKey); if (empty($token)) { $token = $this->request->input($this->inputKey); } if (empty($token)) { $token = $this->request->bearerToken(); } if (empty($token)) { $token = $this->request->getPassword(); } return $token; }
Whether there is a real find Authorization header in the bearerToken
public function bearerToken() { $header = $this->header('Authorization', ''); if (Str::startsWith($header, 'Bearer ')) { return Str::substr($header, 7); } }
Give the user table to add api_token field php artisan make:migration add_api_token_to_users --table=users
content
class AddApiTokenToUsers extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('users', function (Blueprint $table) { $table->string('api_token', 60)->unique(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('users', function (Blueprint $table) { $table->dropColumn('api_token'); }); } }
Open navicat into the user table, update users of api_token.
Open postman
Note that the header, key is the Authorization, the value is just Bearer + space + database set of api_token
This will return the contents of it, modify another user's token to return the appropriate user information, indicating that the authentication is successful, the function basically completed!
Here perfect details
Perfect logic
modification\app\Http\Controllers\Auth\RegisterController.php
protected function create(array $data) { return User::create([ 'name' => $data['name'], 'email' => $data['email'], 'password' => bcrypt($data['password']), // add this line 'api_token' => str_random(60), ]); }
User Model is also changed at $ fillable
protected $fillable = [ 'name', 'email', 'password', 'api_token', ];
If the front page, how to pass the time of initiating the request Authorization header to the background? Follows
Note that the following is a modification of the method Laravel5.4. The new version may be slightly different, just know that the principle will be able to do it ourselves.
Open \resources\assets\js\bootstrap.js
Referring to the csrf-token. Suitable place Add the following code
let token = document.head.querySelector('meta[name="csrf-token"]'); let api_token = document.head.querySelector('meta[name="api-token"]'); if (token) { // this document to refer to axios window.axios.defaults.headers.common['X-CSRF-TOKEN'] = Laravel.csrfToken =token.content; // If you are using jquery // Fix jquery ajax crossDomain without Token // jQuery.ajaxPrefilter(function (options, originalOptions, jqXHR) { // // if (options.crossDomain) { // jqXHR.setRequestHeader('Authorization', api_token.content); // jqXHR.setRequestHeader('X-CSRF-TOKEN', token.content); // //} // }); } else { console.error('CSRF token not found: https://laravel.com/docs/csrf#csrf-x-csrf-token'); } if (api_token) { window.axios.defaults.headers.common['Authorization'] = api_token.content; } else { console.error('Authorization token not found: https://laravel.com/docs/csrf#csrf-x-csrf-token'); }
Last Modified public view template \views\layouts\app.blade.php
<meta name="csrf-token" content="{{ csrf_token() }}"> <meta name="api-token" content="{{ Auth::check() ? 'Bearer '.Auth::user()->api_token : 'Bearer ' }}">
Summary:
to add user table api_token In essence, according to the background in this field to determine whether the user is valid, invalid return 401, the effective return query results.
The advantage is easy to understand, the disadvantage is too simple and safe enough.
For security, you can achieve the following functions:
After each successful login refresh api_token new value
is actually the official Laravel provides a Laravel Passport package. Laravel Passport is an OAuth2 server and API authentication package.
Reprinted from: https://www.jianshu.com/p/b89df38e886b