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

Using Passport to implement Auth authentication in Laravel5.5

Jun 13, 2018 am 11:29 AM
auth authentication laravel passport

This article mainly introduces the use of Passport to implement Auth authentication in Laravel5.5. It has certain reference value. Now I share it with you. Friends in need can refer to it

Laravel5.3 Get started Passport is used 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 sample code. Friends who need it can refer to it. Let’s take a look below.

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 felt a little cumbersome, so Laravel's Passport and the new Api Resource in 5.5 come to mind. 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 server

2.服务端带着从前端接收到账号与密码,并在其中添加 Client_id 与 Client_token,然后带着这些参数请求自身的 Passport 认证路由,然后返回认证后的 Access token 与 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,一切就大功告成啦~

以上就是本文的全部内容,希望对大家的学习有所帮助,更多相关内容请关注PHP中文网!

相关推荐:

Laravel5.2使用Captcha生成验证码实现登录的方法

关于Laravel中日期时间处理包Carbon的使用

关于laravel 5.1下php artisan migrate的使用

The above is the detailed content of Using Passport to implement Auth authentication 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)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1266
29
C# Tutorial
1239
24
Laravel Introduction Example Laravel Introduction Example Apr 18, 2025 pm 12:45 PM

Laravel is a PHP framework for easy building of web applications. It provides a range of powerful features including: Installation: Install the Laravel CLI globally with Composer and create applications in the project directory. Routing: Define the relationship between the URL and the handler in routes/web.php. View: Create a view in resources/views to render the application's interface. Database Integration: Provides out-of-the-box integration with databases such as MySQL and uses migration to create and modify tables. Model and Controller: The model represents the database entity and the controller processes HTTP requests.

Solve caching issues in Craft CMS: Using wiejeben/craft-laravel-mix plug-in Solve caching issues in Craft CMS: Using wiejeben/craft-laravel-mix plug-in Apr 18, 2025 am 09:24 AM

When developing websites using CraftCMS, you often encounter resource file caching problems, especially when you frequently update CSS and JavaScript files, old versions of files may still be cached by the browser, causing users to not see the latest changes in time. This problem not only affects the user experience, but also increases the difficulty of development and debugging. Recently, I encountered similar troubles in my project, and after some exploration, I found the plugin wiejeben/craft-laravel-mix, which perfectly solved my caching problem.

Laravel user login function Laravel user login function Apr 18, 2025 pm 12:48 PM

Laravel provides a comprehensive Auth framework for implementing user login functions, including: Defining user models (Eloquent model), creating login forms (Blade template engine), writing login controllers (inheriting Auth\LoginController), verifying login requests (Auth::attempt) Redirecting after login is successful (redirect) considering security factors: hash passwords, anti-CSRF protection, rate limiting and security headers. In addition, the Auth framework also provides functions such as resetting passwords, registering and verifying emails. For details, please refer to the Laravel documentation: https://laravel.com/doc

How to learn Laravel How to learn Laravel for free How to learn Laravel How to learn Laravel for free Apr 18, 2025 pm 12:51 PM

Want to learn the Laravel framework, but suffer from no resources or economic pressure? This article provides you with free learning of Laravel, teaching you how to use resources such as online platforms, documents and community forums to lay a solid foundation for your PHP development journey from getting started to master.

Laravel framework installation method Laravel framework installation method Apr 18, 2025 pm 12:54 PM

Article summary: This article provides detailed step-by-step instructions to guide readers on how to easily install the Laravel framework. Laravel is a powerful PHP framework that speeds up the development process of web applications. This tutorial covers the installation process from system requirements to configuring databases and setting up routing. By following these steps, readers can quickly and efficiently lay a solid foundation for their Laravel project.

What versions of laravel are there? How to choose the version of laravel for beginners What versions of laravel are there? How to choose the version of laravel for beginners Apr 18, 2025 pm 01:03 PM

In the Laravel framework version selection guide for beginners, this article dives into the version differences of Laravel, designed to assist beginners in making informed choices among many versions. We will focus on the key features of each release, compare their pros and cons, and provide useful advice to help beginners choose the most suitable version of Laravel based on their skill level and project requirements. For beginners, choosing a suitable version of Laravel is crucial because it can significantly impact their learning curve and overall development experience.

How to view the version number of laravel? How to view the version number of laravel How to view the version number of laravel? How to view the version number of laravel Apr 18, 2025 pm 01:00 PM

The Laravel framework has built-in methods to easily view its version number to meet the different needs of developers. This article will explore these methods, including using the Composer command line tool, accessing .env files, or obtaining version information through PHP code. These methods are essential for maintaining and managing versioning of Laravel applications.

The difference between laravel and thinkphp The difference between laravel and thinkphp Apr 18, 2025 pm 01:09 PM

Laravel and ThinkPHP are both popular PHP frameworks and have their own advantages and disadvantages in development. This article will compare the two in depth, highlighting their architecture, features, and performance differences to help developers make informed choices based on their specific project needs.

See all articles