Home Backend Development PHP Tutorial How to implement Auth authentication using Passport in Laravel5.5

How to implement Auth authentication using Passport in Laravel5.5

Dec 09, 2017 am 09:57 AM
auth passport

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
Copy after login

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,
Copy after login

2. Run the migration file

Execute the following command in your Shell

php artisan migrate
Copy after login

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
Copy after login

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;
}
Copy after login

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();
 }
}
Copy after login

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;]);
Copy after login

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;,
 ],
],
Copy after login

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);
}
Copy after login

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;);
 }
}
Copy after login

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;),
 ],
];
Copy after login

env 文件内容如下

OAUTH_GRANT_TYPE=password
OAUTH_CLIENT_ID=2
OAUTH_CLIENT_SECRET=2HaTQJF33Sx98HjcKDiSVWZjrhVYGgkHGP8XLG1O
OAUTH_SCOPE=*
Copy after login

我们需要用到的 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)]);
}
Copy after login

得到的 tokens 返回如以下格式

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

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

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

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

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

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

然后在你需要使用到 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 of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Laravel development: How to implement API OAuth2 authentication using Laravel Passport? Laravel development: How to implement API OAuth2 authentication using Laravel Passport? Jun 13, 2023 pm 11:13 PM

As the use of APIs becomes more widespread, protecting the security and scalability of APIs becomes increasingly critical. OAuth2 has become a widely adopted API security protocol that allows applications to access protected resources through authorization. To implement OAuth2 authentication, LaravelPassport provides a simple and flexible way. In this article, we will learn how to implement APIOAuth2 authentication using LaravelPassport. Lar

Using Auth0 for authentication in Java API development Using Auth0 for authentication in Java API development Jun 18, 2023 pm 05:30 PM

In modern software development, identity authentication is a very important security measure. Auth0 is a company that provides identity authentication services. It can help developers quickly implement multiple identity authentication methods (including OAuth2, OpenIDConnect, etc.) and provide safe and reliable authentication services. In this article, we will introduce how to use Auth0 for authentication in JavaAPI development. Step 1: Create an Auth0 account and register the application. First, we need to

Laravel development: How to implement APIOAuth2 authentication using Laravel Passport? Laravel development: How to implement APIOAuth2 authentication using Laravel Passport? Jun 15, 2023 am 10:28 AM

Laravel is a very popular PHP framework that is easy to use, highly scalable, and highly readable. Laravel also provides many add-on packages (Package) to implement various functions, including LaravelPassport, which is an API package for implementing OAuth2 authentication. OAuth2 is a popular authorization framework that simplifies the authorization process and is widely used in web and mobile applications. In order to use OAuth

How to use Supabase Auth method in Vue3 How to use Supabase Auth method in Vue3 May 28, 2023 am 08:39 AM

Introduction Supabase is a self-proclaimed "open source Firebase alternative". I've been interested in working with Supbase for a while and thought I'd try using their authentication API to set up authentication for a Vue.js3 application. First of all, why should you use SupabaseAuth? The bottom line is that if you're using Supabase as your data store, (which has some pretty sweet benefits), SupabaseAuth is the only way you can manage access to that data. Secondly, although SupabaseAuth also has many different functions. User permissions without middleware (row-level security via Postgres)

Laravel development: How to implement OAuth2 authentication using Laravel Passport? Laravel development: How to implement OAuth2 authentication using Laravel Passport? Jun 15, 2023 pm 12:24 PM

Laravel development: How to implement OAuth2 authentication using LaravelPassport? Laravel is a popular PHP web development framework that makes it easy to build efficient, scalable, and easy-to-maintain web applications. Laravel has many features and components, including LaravelPassport. LaravelPassport is a complete OAuth2 server implementation that helps developers easily add security

Implementing PHP security authentication using Auth0 Implementing PHP security authentication using Auth0 Jul 25, 2023 pm 02:09 PM

Using Auth0 to implement PHP security verification Introduction: In modern web development, security verification is a crucial part. In order to protect users' privacy and data security, we need to take measures to ensure that only authorized users can access sensitive information or perform specific operations. Auth0 is a popular authentication and authorization platform that provides simple and powerful solutions to help us achieve secure verification. This article will introduce how to use Auth0 to implement PHP security verification and provide code

Using Passport to provide social authentication for Node.js applications Using Passport to provide social authentication for Node.js applications Sep 01, 2023 pm 08:41 PM

It is an accepted fact that passwords are inherently fragile. Therefore, requiring end users to create strong passwords for every application they use will only make matters worse. A simple workaround is to have users authenticate through existing social accounts (e.g. Facebook, Twitter, Google, etc.). In this article, we will do just that and add this social login feature to our account so that we can authenticate with Facebook and Twitter accounts using the Passport middleware. If you haven't read the previous article, I recommend you read it because we will be building on the foundation laid in this article to build a new strategy,

Laravel development: How to implement API authentication using Laravel Passport and JWT? Laravel development: How to implement API authentication using Laravel Passport and JWT? Jun 13, 2023 pm 11:41 PM

Laravel development: How to implement API authentication using LaravelPassport and JWT? API (Application Programming Interface) authentication is a common requirement in today's Internet applications. Laravel, as a popular PHP framework, provides two tools, LaravelPassport and JWT (JSONWebTokens), which can help us implement AP

See all articles