Home  >  Article  >  Backend Development  >  How to implement Auth authentication using Passport in Laravel5.5

How to implement Auth authentication using Passport in Laravel5.5

小云云
小云云Original
2017-12-09 09:57:541899browse

Laravel5.3 Start using Passport as API authorization. Passport is based on OAuth2. The following article mainly introduces you to the method of using Passport to implement Auth authentication in Laravel5.5. The article introduces it in detail through the sample code. , friends in need can refer to it, I hope it can help everyone.

Preface

Recently I am writing a front-end and back-end separation project. I originally wanted to use Jwt-auth + Dingo to develop it, but it feels a little cumbersome. So I thought of Laravel's Passport and the new Api Resource in 5.5. Laravel Passport is a set of encapsulated OAuth2 server implementation

OAuth is an open network standard for authorization and is widely used around the world. The current version is version 2.0.

OAuth 2.0 is currently a popular approach, and it was first used by Google, Yahoo, Microsoft, Facebook, etc. The reason why it is marked as 2.0 is because there was originally a 1.0 protocol, but this 1.0 protocol was made too complicated and not easy to use, so it was not popularized. 2.0 is a new design with a simple and clear protocol, but it is not compatible with 1.0 and has nothing to do with 1.0.

So I won’t go into details here, let’s take a look at how to install it first.

Installation

Install Passport

1. Execute the following command in your Shell

composer require laravel/passport

If the Laravel version you are using is below 5.5, you need to manually add the following code to the providers array of the config/app.php file

Laravel\Passport\PassportServiceProvider::class,

2. Run the migration file

Execute the following command in your Shell

php artisan migrate

The Passport service provider uses the framework to register its own migration directory, so after registering the service, you can directly run php artisan migrate to generate the required data tables for Passport

3. Generate encryption key

Execute the following command in your Shell

php artisan passport:install

This command will create the encryption key required to generate a secure access token. At the same time, this command will also create the "Personal Access" client and "Password Authorization" used to generate the access token.

4. Add Trait

Add LaravelPassportHasApiTokens Trait to the AppUser model

<?php
namespace App;
use Laravel\Passport\HasApiTokens;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
 use HasApiTokens, Notifiable;
}

5. Register route

Call the Passport::routes function in the boot method of AuthServiceProvider.

class AuthServiceProvider extends ServiceProvider
{
 public function boot()
 {
  $this->registerPolicies();
  Passport::routes();
 }
}

If your program requires OAuth authentication in the form of front-end and back-end separation instead of multi-platform authentication, then you can pass it in the routers() method An anonymous function to customize the route that you need to register. Here is the authentication form that separates the front and back ends. Therefore, I only need to provide Auth authentication to one of my front-end clients, so I only registered the route to obtain the Token. At the same time, I also A prefix name is customized for it.

Passport::routes(function(RouteRegistrar $router) {
 $router->forAccessTokens();
},[&#39;prefix&#39; => &#39;api/oauth&#39;]);

6. Change the guard driver

Authorize the configuration file config/auth.php The driver option of the guards api is changed to passport. This adjustment will allow your application to use Passport's TokenGuard when verifying incoming API requests.

&#39;guards&#39; => [
 &#39;web&#39; => [
  &#39;driver&#39; => &#39;session&#39;,
  &#39;provider&#39; => &#39;users&#39;,
 ],
 &#39;api&#39; => [
  &#39;driver&#39; => &#39;passport&#39;,
  &#39;provider&#39; => &#39;users&#39;,
 ],
],

At this point, Passport has been installed, and the remaining As for the front-end part mentioned in the following document, since I only need to use it for Auth authentication and do not need to implement the complete OAuth function, we do not need to use the front-end page at all.

Use

For the convenience of Api returning data, I encapsulated several functions

function respond($status, $respond)
{
 return response()->json([&#39;status&#39; => $status, is_string($respond) ? &#39;message&#39; : &#39;data&#39; => $respond]);
}
function succeed($respond = &#39;Request success!&#39;)
{
 return respond(true, $respond);
}
function failed($respond = &#39;Request failed!&#39;)
{
 return respond(false, $respond);
}

The respond function can make basic returns. succeed and failed are re-encapsulated on the respond function to return request success and request failure data.

Then we need to use a layer of proxy.

Let’s first talk about the reason for using a proxy. The process of Passport authentication is that the slave application takes the Client Token generated by the main application

and the account password entered by the user to request the Passport of the main application. Token route to obtain access token (access token) and refresh token (refresh token), and then use the obtained access token to access the route under auth:api. But we do not have a subordinate application. The front end that separates the front and back ends requests this token. If you want to pull this access token from the front end, you need to write the Client token in the front end. This is very unreasonable, so we can Write a proxy internally, and the application itself takes the Client token to request itself to obtain the access token. This may be a bit confusing, but the request process is probably as follows

1. The front-end takes the account password entered by the user Request the server

2. The server receives the account number and password from the front end, adds Client_id and Client_token to it, then requests its own Passport authentication route with these parameters, and then returns after authentication Access token and refresh token

下面是代码实现,我在 AppHttpControllersTraits 下新建了一个 ProxyHelpers 的 Trait,当然,这个函数是我根据我的业务逻辑自己封装的,如果不适合你的业务逻辑你可以自行调整。

<?php

namespace App\Http\Controllers\Traits;

use GuzzleHttp\Client;
use App\Exceptions\UnauthorizedException;
use GuzzleHttp\Exception\RequestException;

trait ProxyHelpers
{
 public function authenticate()
 {
  $client = new Client();
  try {
   $url = request()->root() . &#39;/api/oauth/token&#39;;
   $params = array_merge(config(&#39;passport.proxy&#39;), [
    &#39;username&#39; => request(&#39;email&#39;),
    &#39;password&#39; => request(&#39;password&#39;),
   ]);
   $respond = $client->request(&#39;POST&#39;, $url, [&#39;form_params&#39; => $params]);
  } catch (RequestException $exception) {
   throw new UnauthorizedException(&#39;请求失败,服务器错误&#39;);
  }
  if ($respond->getStatusCode() !== 401) {
   return json_decode($respond->getBody()->getContents(), true);
  }
  throw new UnauthorizedException(&#39;账号或密码错误&#39;);
 }
}

config/passport.php 内容如下

<?php
return [
 &#39;proxy&#39; => [
  &#39;grant_type&#39; => env(&#39;OAUTH_GRANT_TYPE&#39;),
  &#39;client_id&#39;  => env(&#39;OAUTH_CLIENT_ID&#39;),
  &#39;client_secret&#39; => env(&#39;OAUTH_CLIENT_SECRET&#39;),
  &#39;scope&#39;   => env(&#39;OAUTH_SCOPE&#39;, &#39;*&#39;),
 ],
];

env 文件内容如下

OAUTH_GRANT_TYPE=password
OAUTH_CLIENT_ID=2
OAUTH_CLIENT_SECRET=2HaTQJF33Sx98HjcKDiSVWZjrhVYGgkHGP8XLG1O
OAUTH_SCOPE=*

我们需要用到的 client token 是 id 为 2 的 client token,不要搞错了哟~

然后我们只需要在控制器中 use 这个 Trait,然后调用 $this->authenticate() 就可以得到认证成功的 token,如果请求失败的话,你可以使用 catch 来捕捉错误抛出异常。

 public function login(Request $request)
{
  $needs = $this->validate($request, rules(&#39;login&#39;));
  $user = User::where(&#39;email&#39;, $needs[&#39;email&#39;])->first();

  if (!$user) {
   throw new UnauthorizedException(&#39;此用户不存在&#39;);
  }
  $tokens = $this->authenticate();
  return succeed([&#39;token&#39; => $tokens, &#39;user&#39; => new UserResource($user)]);
}

得到的 tokens 返回如以下格式

{
 "token_type": "Bearer",
 "expires_in": 31536000,
 "access_token": "token_str",
 "refresh_token": "token_str"
}

做完这一切后你就可以在前端向这样子请求服务端了

axios.post(&#39;yourdomain/login&#39;,login_form).then(resource => { 
})

如果请求成功,那么你将会得到 用户的信息和 access token,refresh token。

然后在你的前端 http 请求 header 里需要加入一个参数 Authorization

axios.defaults.headers.common[&#39;Authorization&#39;] = token.token_type + &#39; &#39; + token.access_token

然后在你需要使用到 auth 认证的路由里使用中间件 auth:api,一切就大功告成啦~

相关推荐:

Laravel5.5中的Package Auto Discovery详情介绍

有关Laravel5.5中友好报错展示与详解

Laravel5.5新特性之报错以及展示的图文介绍

The above is the detailed content of How to implement Auth authentication using Passport in Laravel5.5. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:php verify ID numberNext article:php verify ID number