1. Introduction
The authentication in Lumen uses the same underlying library as Laravel, but is completely different from the complete Laravel framework. Because Lumen no longer supports Session status, if you want to authenticate input requests, you can only use API token.
2. Start
Certification service provider
Note: Before using the Lumen authentication feature, you need to cancel the comments before registering the service provider AuthServiceProvider in the bootstrap/app. Php file.
The AuthServiceProvider under the app/Providers Directory only contains the closure that is called when the Auth: viaRequest method is used to receive an input request to be authenticated. In this closure, you can parse the desired App \ User instance. If the corresponding authenticated User cannot be found through the request parameter, the closure will return null:
$ This-> app ['auth ']-> viaRequest ('api', function ($ request ){
// Return User or null...
});
Again, you can resolve any authenticated users you need. You can use the API token in the request header to obtain the request parameters.
Access authenticated user
Like the complete Laravel framework, you can use Auth: user () to obtain the current user. In addition, you can use the $ Request-> user () method on the Illuminate \ Http \ request instance:
Use Illuminate \ Http \ Request;
$ App-> get ('/post/{id}', ['middleware '=> 'auth', function (Request $ request, $ id ){
$ User = Auth: user ();
$ User = $ request-> user ();
//
}]);
Note: If you want to use Auth: user () to access the current authenticated user, you need to cancel the comments before $ app-> routeMiddleware () in bootstrap/app. php.
Of course, auth middleware must be allocated for the route to be authenticated. Therefore, you must cancel the comments before $ app-> routeMiddleware () in the bootstrap/app. Php file:
$ App-> routeMiddleware ([
'Auth' => App \ Http \ Middleware \ Authenticate: class,
]);