8. Laravel5 Study Notes: Use OAuth authorization in laravel5, laravel5oauth

Source: Internet
Author: User
Tags oauth

8. Laravel5 Study Notes: Use OAuth authorization in laravel5, laravel5oauth
Introduction to OAuth2.0

We will give you the following two articles about it. I believe you should have a certain understanding of it after reading it:
[1] understanding of OAuth 2.0 -- Ruan Yifeng
[2] helping you understand the OAuth2.0 protocol-secc.pdf

Here I will mainly explain how to use OAuth2.0 in laravel5. I hope you can read the above two articles and understand the agreement and the running process. Then, let's look at the content next to me!

Installing OAuth2.0 in Laravel5

OAuth2.0 provides the php library on the official website, but we do not directly use it here.Server Libraries, We use githubOauth2-server-laravelThis library is transformed and suitableLaravel5(Select the correct version for Laravel4 installation ).

Tutorial

In fact, for how to use this packageoauth2-server-laravelThe provided project has been clearly stated, but the document is not easy to understand in English, and there are several pitfalls. Here we will repeat and complete it in Chinese:

Install

First, you need to install it. The stable version of Laravel5 has not yet been released, but only the development version is provided. (an error occurs when installing it according to the document on github. This is because the provided version has not been released and you need to use the development version ), all installations are as follows:

"lucadegasperi/oauth2-server-laravel": "~4.1@dev","illuminate/html": "~5.0"

Ps: Installilluminate/htmlThis package was removed from Laravel5 and needs to be used in our project, but it is not necessary. You can choose not to install it, you will not be able to use{!! Form::hidden('client_id', $params['client_id']) !!}This operation.

Configuration

You can complete the configuration according to the provided documentation, as follows:

  • Directionconfig/app.phpOfprovidersAdd a service provider to the array
LucaDegasperi \ OAuth2Server \ Storage \ FluentStorageServiceProvider: class, LucaDegasperi \ OAuth2Server \ OAuth2ServerServiceProvider: class, // view Form usage, no direct relationship with OAuth, for ease of layout, Illuminate \ Html \ HtmlServiceProvider: class,
  • Directionconfig/app.phpOfaliasesAdd Facades to the array
'Authorizer' => LucaDegasperi \ OAuth2Server \ Facades \ Authorizer: class, // there is no direct relationship with OAuth2.0 authentication, to facilitate the layout, use 'form' => Illuminate \ Html \ FormFacade: class, 'html' => Illuminate \ HTML \ HtmlFacade: class,
  • Modifyapp/Http/Kernel.php, Configure related Middleware
Protected $ middleware = [// comment out // \ App \ Http \ Middleware \ VerifyCsrfToken: class, \ LucaDegasperi \ OAuth2Server \ Middleware \ role: class,]; protected $ routeMiddleware = [// Add the following route, and the original "oauth" => \ LucaDegasperi \ OAuth2Server \ Middleware \ OAuthMiddleware: class, 'oss-owner' => \ LucaDegasperi \ OAuth2Server \ Middleware \ role: class, 'check-authorization-params '=> \ LucaDegasperi \ OAuth2Server \ Middleware \ role: class, 'csrf' => \ App \ Http \ Middleware \ VerifyCsrfToken: class,];
  • Runphp artisan vendor:publishGenerate related configuration files.configAoauth2.phpFile.

  • To generate the database table required by OAuth2.0 in the database, you only need to executephp artisan migrateYou can see the following table generation in the database:

  • Select the authorization mode of the client. OAuth2.0 has four modes:Authorisation code grant,Implicit grant,Resource owner credentials grant,Client credentials grant. Here I will introduce the use of WeiboAuthorisation code grantIn this mode, we believe that everyone can communicate with each other.
    After selection, selectconfig/oauth2.phpConfiguringgrant_typesOption:

'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 code, we should first enter some initial data in the database.
First, add a user. We recommend that you useLaravel5Built-inSeeder. I will not talk about the process. I will tell you what data to initialize!
* ForwardusersAdd a user to table
* Forwardoauth_clientsTo add a client to table, you must note that its id is of the string type, which is equivalent to the AppKey allocated when applying for Weibo.
* Forwardoauth_scopesAdd two-day records to table, for example:

* Forwardoauth_client_scopesAdd the following record to table:

* Forwardoauth_client_endpointsAdd record

Ps: note that,redirect_uriThe value should be the address that you can call back locally. Do not imitate it. Please follow your own situation.

As for how to add the data, I believe you can guess one or two Based on the table name. If you are not clear, leave a message and ask.

Finally reached the code stage

For ease of use, I unmount all the code from the routing file according to the documentation provided on github. We recommend that you port the code in the closure to the controller when using the code in the project, otherwise, you will not be able to use the routing cache function provided by laravel.
The routing code is as follows:

// This is the resource that can be accessed only after OAuth2.0 authorization. If you do not believe that you directly access the resource, the error Route: get ('/', ['middleware ware '=> ['oauth'], function () {return view ('Welcome') ;}]); // log on to the Route :: get ('auth/login', function () {return view ('auth. login ');}); Route: post ('auth/login', function () {if (auth: attempt (Input: only ('email ', 'Password') {return Redirect: intended ('oauth ') ;}}); // This will Redirect the page to an authorization page and provide the Route :: get ('oss/authorize ', ['as' => 'oss. Authorize. get ', 'middleware ware' => ['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_assistt ($ authParams, 'client'); $ formParams ['client _ id'] = $ authParams ['client']-> getId (); return View: make ('oauth. authorization-form ', ['params' => $ formParams, 'clien T' => $ authParams ['client']);}]); // The HTTP request Route from the client requesting a token from the authentication server through authorization :: post ('oss/authorization', ['as' => 'oss. authorize. post', 'middleware ware '=> ['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 its data, redirect back to the client 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 its data, redirect back to the client with an error message if (Input: get ('deny ')! = Null) {$ redirectUri = Authorizer: authCodeRequestDeniedRedirectUri ();} return Redirect: to ($ redirectUri) ;}]); // The HTTP reply Route sent by the authentication server:: post ('oauth/access_token', ['as' => 'Access _ token', function () {header ('content-Type: application/json; charset = UTF-8 '); return Response: json (Authorizer: issueaccesen en () ;}]); // The HTTP request page used by the client to request a token from the authentication server, easy to send post request Route: get ('/callback', function () {if (Input: has ('code ')) {return view ('callback ');}});

For the view files used above, see the Laravle-OAuth2 project.

Effect display

Here is a demo of the page effect. I will explain it according to the execution process of OAuth2.0.Authorization code modeThe execution process of is posted here:

The explanation is as follows:

(A) when the user accesses the client, the latter directs the former to the authentication server.
(B) Select whether to authorize the client.
(C) assuming that the user is authorized, the authentication server directs the user to the "Redirect URI" (redirection URI) specified in advance by the client, and attaches an authorization code.
(D) The client receives the authorization code, attaches an earlier "Redirect URI" to apply for a token from the authentication server. This step is completed on the backend server of the client, which is invisible to users.
(E) The authentication server checks the authorization code and redirect URI. After confirming the correctness, it sends the access token and the update token to the client ).

Corresponding to step:

In step A, the URI requested by the client for authentication includes the following parameters:
Redirect_uri: indicates the redirection URI. Optional
State: indicates the current status of the client. You can specify any value. The authentication server returns this value intact.
Response_type: indicates the authorization type. required. The value here is fixed to "code"
Client_id: indicates the Client ID, required
Scope: indicates the permission range applied for. Optional

Corresponding to step B:
After access through step A, the displayed page shows whether the authorization is presented to the user. You can select it.Approve, Then proceed

Corresponding to Step C:

At this time, we can see that the address displayed in the address bar is our callback address and contains the code and state parameters. The status code 302 is also found on the console.

Step D:
This step is invisible to users. for demonstration purposes, a post form is provided. In normal projects, users can send authenticated post requests to the AS through the client background, at this time, AS will return a json data and retrieve itaccess_tokenAfter attaching the resource URI, you can access the resource.

Corresponding to Step E:
Get Server Response Data

{    "access_token":"Zv0anjwEjAm7SFZGjH1K3MRW6yNj56SuC5MGI9kB",    "token_type":"Bearer",    "expires_in":3600}

OK. Now you can test the access to the resources to be authorized. Here we are:

Http: // localhost/llaravel/public/If no parameter is added, the following error message is displayed during direct access:

{    "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 = Zv0anjwEjAm7SFZGjH1K3MRW6yNj56SuC5MGI9kBIn this case, you will see the beautiful homepage interface of laravel5.

OK. Now we're done! Hope to help you.

Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.

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.