


How to implement Auth authentication using Passport in Laravel5.5
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(); },['prefix' => 'api/oauth']);
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.
'guards' => [ 'web' => [ 'driver' => 'session', 'provider' => 'users', ], 'api' => [ 'driver' => 'passport', 'provider' => 'users', ], ],
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(['status' => $status, is_string($respond) ? 'message' : 'data' => $respond]); } function succeed($respond = 'Request success!') { return respond(true, $respond); } function failed($respond = 'Request failed!') { 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() . '/api/oauth/token'; $params = array_merge(config('passport.proxy'), [ 'username' => request('email'), 'password' => request('password'), ]); $respond = $client->request('POST', $url, ['form_params' => $params]); } catch (RequestException $exception) { throw new UnauthorizedException('请求失败,服务器错误'); } if ($respond->getStatusCode() !== 401) { return json_decode($respond->getBody()->getContents(), true); } throw new UnauthorizedException('账号或密码错误'); } }
config/passport.php 内容如下
<?php return [ 'proxy' => [ 'grant_type' => env('OAUTH_GRANT_TYPE'), 'client_id' => env('OAUTH_CLIENT_ID'), 'client_secret' => env('OAUTH_CLIENT_SECRET'), 'scope' => env('OAUTH_SCOPE', '*'), ], ];
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('login')); $user = User::where('email', $needs['email'])->first(); if (!$user) { throw new UnauthorizedException('此用户不存在'); } $tokens = $this->authenticate(); return succeed(['token' => $tokens, 'user' => new UserResource($user)]); }
得到的 tokens 返回如以下格式
{ "token_type": "Bearer", "expires_in": 31536000, "access_token": "token_str", "refresh_token": "token_str" }
做完这一切后你就可以在前端向这样子请求服务端了
axios.post('yourdomain/login',login_form).then(resource => { })
如果请求成功,那么你将会得到 用户的信息和 access token,refresh token。
然后在你的前端 http 请求 header 里需要加入一个参数 Authorization
axios.defaults.headers.common['Authorization'] = token.token_type + ' ' + token.access_token
然后在你需要使用到 auth 认证的路由里使用中间件 auth:api,一切就大功告成啦~
相关推荐:
Laravel5.5中的Package Auto Discovery详情介绍
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

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

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 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

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 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

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

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 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
