Laravel 5.4 website construction 06--API Authentication System Passport, laravel06 -- api

Source: Internet
Author: User

Laravel 5.4 website construction 06--API Authentication System Passport, laravel06 -- api
Introduction

In Laravel, it is very easy to implement login and authorization based on traditional forms. But how can we meet the authorization requirements in API scenarios? In API scenarios, user authorization is usually implemented through tokens instead of maintaining the Session status between requests. Now the Laravel project can use Passport to easily implement the API authorization process. With Passport, you can add a complete oau2server implementation for your application within a few minutes.

Install

Use the Composer dependency Package Manager to install Passport:

 composer require laravel/passport

Next, register the Passport service provider to the providers array in the config/app. php configuration file:

Laravel\Passport\PassportServiceProvider::class

Passport uses the service provider to register the internal database migration Script directory. Therefore, after completing the previous step, you need to update your database structure. The Passport migration script automatically creates the client data table and token data table required by the application:

php artisan migrate

Next, you need to run the passport: install command to create the encryption key used to generate the security access token. At the same time, this command will also create the "Private access" client and "password authorization" client:

php artisan passport:install

After the preceding command is executed, modify App \ User. php to check the token and usage scope of authenticated users:

<? Phpnamespace App; use Laravel \ Passport \ HasApiTokens; // added use Illuminate \ Notifications \ Notifiable; use Illuminate \ Foundation \ Auth \ User as Authenticatable; class User extends Authenticatable {use extensions, notifiable; // Add HasApiTokens

Next, you need to call the Passport: routes function in the boot method of AuthServiceProvider. This function registers some required routes used in the process of issuing and revoking access tokens, clients, and private access tokens:

Modify App \ Providers \ AuthServiceProvider. php:

<? Phpnamespace App \ Providers; use Laravel \ Passport; // added use Illuminate \ Support \ Facades \ Gate; use Illuminate \ Foundation \ Support \ Providers \ AuthServiceProvider as ServiceProvider; use Carbon \ Carbon; // Add reference class AuthServiceProvider extends ServiceProvider {/*** The policy mappings for the application. ** @ var array */protected $ policies = ['app \ model' => 'app \ Policies \ modelpolicy',];/*** Register any authentication/authorization services. ** @ return void */public function boot () {$ this-> registerPolicies (); Passport: routes (); // register the validity period of the passport route // token Passport:: tokensExpireIn (Carbon: now ()-> addDays (15); Passport: refreshTokensExpireIn (Carbon: now ()-> addDays (30 ));}}

Finally, change the authorization protection item (driver) in the api section of config/auth. php to passport. This adjustment will allow your application to use the Passport TokenGuard to handle API authorization requests:

& Apos; guards & apos; = & apos; web & apos; = & apos; driver & apos; = & apos; session & apos;, & apos; provider & apos; = & apos; users & apos;,], 'API' => ['driver '=> 'passport', // change to passport 'provider' => 'users',],],
Test

The api route is api. php. Open routes \ api. php and add a test route.

Route::group(['namespace' => 'api'], function () {    Route::post('/login', 'UserController@login');});Route::group(['middleware' => 'auth:api', 'namespace' => 'api'], function() {    Route::get('details', 'UserController@details');});

One is used to log on and obtain the token, and the other is to use the obtained token for Logon verification and obtain the current user information.

The details routing uses auth: api middleware to verify the token.

Create an api folder in the App \ Http \ directory and add UserController. php

<? Phpnamespace App \ Http \ Controllers \ api; use Illuminate \ Http \ Request; use App \ Http \ Controllers \ Controller; use Illuminate \ Support \ Facades \ Auth; use App \ User; use Response; class UserController extends Controller {public function _ construct () {$ this-> content = array ();} public function login () {if (Auth :: attempt (['email '=> request ('email'), 'Password' => request ('Password')]) {$ user = Auth: user (); $ this-> content ['Token'] = $ user-> createToken ('Pizza app')-> accessToken; $ status = 200 ;} else {$ this-> content ['error'] = "unauthorized"; $ status = 401;} return response ()-> json ($ this-> content, $ status) ;}public function details () {return response ()-> json (['user' => Auth: user ()]) ;}}

Test in postman:

As shown in, the logon method must match the route. In post mode, the user's email and password are transmitted to api/login in form mode.

 

If it is passed correctly, the token will be obtained.

Add the token obtained in the previous step to the Header and add 'bearer' before the token '. Then you can get the information of the current user. That is, user authentication is completed.

 

The above is not guaranteed to be completely correct. Check out my GitHub code.

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.