Introduced
In Laravel, the implementation of login and authorization based on traditional forms has been very simple, but how to meet the licensing requirements of the API scenario? In the API scenario, the user authorization is usually implemented through tokens, rather than the Session state between maintenance requests. The Laravel project now allows you to easily implement the API authorization process with Passport, which allows you to add a complete OAuth2 server-side implementation for your application in minutes.
Installation
To install a Passport using the Composer Dependency Package Manager:
Composer require Laravel/passport
Next, register the service provider for the Passport to the providers array in the configuration file config/app.php:
Laravel\passport\passportserviceprovider::class
Passport uses the service provider to register the internal Database Migration script directory, so after the previous step, you need to update your database structure. The Passport migration script automatically creates the client data tables and token data tables that the application requires:
PHP Artisan Migrate
Next, you need to run the Passport:install command to create the encryption key used to generate the secure access token, and this command will also create a private access client and a password authorization client:
PHP Artisan Passport:install
After the above command is executed, modify app\user.php to check the token and use scope of the authenticated user:
<? phpnamespace App; Use added use illuminate\notifications\notifiable; Use as authenticatable; class extends authenticatable{ use increase Hasapitokens
Next, you need to call the Passport::routes function in the boot method of Authserviceprovider. This function registers some necessary routes that will be used during the issuance and revocation of access tokens, clients, and private access tokens:
Modify app\providers\authserviceprovider.php:
<?phpnamespace app\providers; UseLaravel\passport\passport;//New Useilluminate\support\facades\gate; UseIlluminate\foundation\support\providers\authserviceprovider asserviceprovider; UseCarbon\carbon;//New ReferencesclassAuthserviceproviderextendsserviceprovider{/** * The policy mappings for the application. * * @var Array*/ protected $policies= [ ' App\model ' = ' app\policies\modelpolicy ', ]; /** * Register any authentication/authorization services. * * @return void*/ Public functionboot () {$this-registerpolicies (); Passport:: Routes ();//sign up for Passport routing//token expirationPassport::tokensexpirein (Carbon::now ()->adddays (15)); Passport:: Refreshtokensexpirein (Carbon::now ()->adddays (30)); }}
Finally, you need to change the authorization Protection entry (driver) in the API section of the configuration file config/auth.php to Passport. This adjustment will allow your application to use Passport Tokenguard when receiving authorization requests from the API:
' Guards ' = [ ' web ' + = ' driver ' and ' session ', ' provider ' and ' users ', ], ' API ' = [ // change to Passport ' provider ' + ' users ', ],],
Test
The route of the API is api.php. Open routes\api.php, add test route.
function () { Route::p ost ('/login ', ' [email protected] ');}); Routefunction() { route:: Get (' details ', ' [email protected] ');});
One is used to login, get token, and the other is to use the token obtained to complete the login verification, access to the current user profile.
Details routing, using the AUTH:API middleware, used to validate tokens.
Create the API folder in the App\http\ directory and add the usercontroller.php
<?phpnamespace App\http\controllers\api; Useilluminate\http\request; UseApp\http\controllers\controller; UseIlluminate\support\facades\auth; UseApp\user; UseResponse;classUsercontrollerextendscontroller{ Public function__construct () {$this->content =Array(); } Public functionLogin () {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; } returnResponse ()->json ($this->content,$status); } Public functiondetails () {returnResponse ()->json ([' user ' = = Auth::user ()]); }}
Test in Postman:
As shown, the login method to match the route, by post, to form the user's email and password to Api/login
If you pass the right words, you will get the token
Add the token from the previous step to the header and precede the token with ' Bearer '. Then we can get the current user's information. That is, user authentication is completed.
The above is not guaranteed to be completely correct. Welcome to my GitHub code.
Laravel 5.4 Construction Station 06--API certification system Passport