OAuth2.0 Introduction
About its introduction, give the following two articles, believe that after reading, it should have a certain degree of understanding:
[1] Understanding OAuth 2.0--Ruan Yi Feng
[2] help you understand the OAuth2.0 protocol in depth--seccloud
Here I mainly describe the use of OAuth2.0 in Laravel5. About this agreement itself, as well as the operation of the process I hope you read the above two articles, understanding, and then look at the back of my content!
installing OAuth2.0 in Laravel5
OAUTH2.0 has provided PHP libraries in the official, but we don't use the official Server Libraries Here, we use GitHub to oauth2-server-laravel this library, It is adapted to fit Laravel5
the (Laravel4 installation on the selected pair version).
Using Tutorials
In fact, about how to use this package, the oauth2-server-laravel
project has been made very clear, but the first document is English is not easy to understand, and then there are a few small pits, here in Chinese and fill in the words:
Installation
To use it first, you need to get it right first. As the current stable version of Laravel5 has not been released, only the development version (here according to the documentation installed on GitHub error is due to the version has not been released, need to use the development version), all installed as follows:
"lucadegasperi/oauth2-server-laravel""[email protected]","illuminate/html""~5.0"
PS: This installation illuminate/html
is because the package is removed from Laravel5, and then we need to use it in our project, but it is not necessary, you can choose not to install, do not install you will not be able to use this action on the page {!! Form::hidden(‘client_id‘, $params[‘client_id‘]) !!}
.
Configuration
The configuration can be fully followed by the documentation provided, as follows:
config/app.php
Adding a providers
service provider to an array
LucaDegasperi\OAuth2Server\Storage\FluentStorageServiceProvider::class,LucaDegasperi\OAuth2Server\OAuth2ServerServiceProvider::class,// view中Form表单使用,与OAuth无直接关系,只是为了布局方便Illuminate\Html\HtmlServiceProvider::class,
config/app.php
aliases
adds facades to the array
‘Authorizer‘=> LucaDegasperi\OAuth2Server\Facades\Authorizer::class,// 与OAuth2.0认证无直接关系,只是为了方便布局使用‘Form‘ => Illuminate\Html\FormFacade::class,‘HTML‘ => Illuminate\Html\HtmlFacade::class,
- Modify
app/Http/Kernel.php
, configure the relevant middleware
protected $middleware= [//Comment out //\app\http\middleware\verifycsrftoken::class,\lucadegasperi\oauth2server\middleware\oauthexceptionhandlermiddleware::class, ];protected$Routemiddleware= [//Add the following route, original reservation 'OAuth' = + \Lucadegasperi\Oauth2server\Middleware\Oauthmiddleware::class, ‘OAuth-owner' = + \Lucadegasperi\Oauth2server\Middleware\Oauthownermiddleware::class, ‘Check-Authorization-params' = + \Lucadegasperi\Oauth2server\Middleware\Checkauthcoderequestmiddleware::class, ‘CSRF' = + \App\Http\Middleware\Verifycsrftoken::class, ];
-
Execute PHP artisan vendor:publish
generate the relevant configuration file, you will see in config
generated a oauth2.php
file.
-
In the database to generate OAuth2.0 required database tables, just to execute PHP artisan migrate
, you will see the following table in the database generation:
- The
Selects the client's licensing mode, OAuth2.0 has four modes, namely: Authorisation Code Grant
, implicit Grant
, Resource Owner Credentials Grant
, Client credentials Grant
. Here I will introduce the mode of authorisation code grant
used by Weibo, I believe everyone follow.
After selecting, prefer to configure grant_types
option in config/oauth2.php
:
‘grant_types‘ => [ ‘authorization_code‘ => [ ‘class‘‘\League\OAuth2\Server\Grant\AuthCodeGrant‘, ‘access_token_ttl‘3600, ‘auth_token_ttl‘3660 ]]
Code and database processing database initialization data
Before writing the code, let's start by filling in the database with some initial data.
The first is to add a user, it is recommended that you use Laravel5
their own Seeder
to complete. I will not say the process, and directly tell you what data to initialize!
* users
add a user to table
* To oauth_clients
add a client to a table, note that its ID is a string type, which is equivalent to the Appkey allocated when applying for Weibo
* oauth_scopes
Add a two-day record to the table, such as:
* oauth_client_scopes
add a record to table as follows:
* oauth_client_endpoints
Add records to
PS: Here should be noted that redirect_uri
the value should be to fill in your own local can callback address, do not blindly imitate, please according to their own situation
As for the addition of these data is God horse meaning, I believe according to the name of the table can guess one or two, is not clear can leave a message to inquire ha.
Finally to the code stage.
For the sake of simplicity, I uninstalled the routing file in the documentation provided on GitHub, and recommended that when used in the project, porting the code in the closure to the controller, otherwise you would not be able to use the route caching feature provided by Laravel.
The entire routing code is as follows:
//This is a resource that needs to be OAuth2.0 authorized to access, do not believe you direct access will definitely errorRoute::get ('/', [' middleware '= [' OAuth '], function () { returnView' Welcome ');}]);//LoginRoute::get (' Auth/login ', function() { returnView' Auth.login ');}); Route::p OST (' Auth/login ', function(){ if(Auth::attempt (Input::only (' Email ',' Password '))){returnRedirect::intended (' OAuth '); }});//This will allow the page to jump to an authorization page and provide the user with the actionRoute::get (' Oauth/authorize ', [' as '=' Oauth.authorize.get ',' middleware '= [' Check-authorization-params ',' auth '], function(){ //Display a form where the user can authorize the client to access it ' s data $authParams= Authorizer::getauthcoderequestparams ();$formParams= Array_except ($authParams,' client ');$formParams[' client_id '] =$authParams[' client ']->getid ();returnView::make (' Oauth.authorization-form ', [' params '=$formParams,' client '=$authParams[' client ']]);}]);//The client requests an HTTP request for a token from the authentication server through authorizationRoute::p OST (' Oauth/authorize ', [' as '=' Oauth.authorize.post ',' middleware '= [' CSRF ',' Check-authorization-params ',' auth '], function() { $params= Authorizer::getauthcoderequestparams ();$params[' user_id '] = Auth::user ()->id;$redirectUri="';//If the user has allowed the client to access it data, redirect back to the client with an auth code if(Input::get (' Approve ') !==NULL) {$redirectUri= Authorizer::issueauthcode (' user ',$params[' user_id '],$params); }//If the user has denied the client to access it data, redirect back to the client with an error message if(Input::get (' Deny ') !==NULL) {$redirectUri= Authorizer::authcoderequestdeniedredirecturi (); }returnRedirect::to ($redirectUri);}]);//HTTP reply sent by authentication serverRoute::p OST (' Oauth/access_token ', [' as '=' Access_token ', function() {Header' Content-type:application/json; Charset=utf-8 ');returnResponse::json (Authorizer::issueaccesstoken ());}]);//page for HTTP requests used by clients to request tokens from the authentication server for sending post requestsRoute::get ('/callback ', function(){ if(Input::has (' Code ')){returnView' Callback '); }});
Refer to the LARAVLE-OAUTH2 project for the view file used above.
Effect Show
Here the page effect of the demonstration, I will follow the OAuth2.0 implementation process to explain, first the Authorization Code mode execution process is posted here:
The Chinese explanation is as follows:
(A) The user accesses the client, which directs the former to the authentication server.
(B) The user chooses whether to grant the client authorization.
(C) Assuming that the user grants authorization, the authentication server directs the user to the "redirect Uri" (redirection URI) specified by the client, with an authorization code attached.
(D) The client receives the authorization code and attaches an earlier "redirect Uri" to request a token from the authentication server. This step is done on the client's backend server and is not visible to the user.
(E) The authentication server checks the authorization code and the redirect Uri, sends an access token (access token) and updates the token (refresh token) to the client after confirmation is correct.
corresponding to step a:
In step A, the client requests the URI for authentication, which contains the following parameters:
Redirect_uri: Represents the redirect Uri, optional
State: Indicates the current status of the client, can specify any value, and the authentication server returns the value intact.
Response_type: Denotes authorization type, mandatory option, where the value is fixed to "code"
CLIENT_ID: Indicates the ID of the client, required option
Scope: Represents the permission range for the request, optional
corresponding to the B step:
After the A-step access, the displayed page is to show whether the authorization is given to the user, the user can choose, assuming the user chooses Approve
, then continue
corresponding to the C step:
At this time, the address bar is observed to find the address shown in the address bar is our callback address, as well as carrying the code and State parameters. The observation console will also find 302 status codes.
corresponding to the D step:
In itself this step is not visible, for the user, but in order to demonstrate, so provide a post form, the normal project can be in the client background to the as to send a certified POST request, at this time as will return a JSON data, from which to remove access_token
, After attaching to the associated resource URI, you can access the resource.
corresponding to the E-step:
Get Server return Data
{ "access_token":"Zv0anjwEjAm7SFZGjH1K3MRW6yNj56SuC5MGI9kB", "token_type":"Bearer", "expires_in":3600}
OK, you can now test access to resources that require authorization. For us here is:
http://localhost/llaravel/public/ , if you do not add parameters, direct Access will see the following error message:
{ "error":"invalid_request", "error_description":"The request is missing a required parameter, includes an invalid parameter value, includes a parameter more than once, or is otherwise malformed. Check the \"access token\" parameter."}
The correct access posture is:http://localhost/llaravel/public?access_token=Zv0anjwEjAm7SFZGjH1K3MRW6yNj56SuC5MGI9kB, accessed at this time, You will see Laravel5 's beautiful homepage interface.
OK, we're done here! Hope to be of help to you.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
8. Laravel5 study notes: Using OAuth authorization in Laravel5