Home>Article>PHP Framework> laravel installation jwt-auth and verification (example)

laravel installation jwt-auth and verification (example)

L
L forward
2020-05-28 10:37:32 5849browse

laravel installation jwt-auth and verification (example)


laravel Install jwt-auth and verify


##1. Use composer to install jwt, cmd to the project folder;

composer require tymon/jwt-auth 1.0.* (Write the version number here according to your own needs)

Install jwt, refer to the official documentation

https: //jwt-auth.readthedocs.io/en/docs/laravel-installation/

2. If the laravel version is lower than 5.4

Open config/app in the root directory. php

Add Tymon\JWTAuth\Providers\LaravelServiceProvider::class,

'providers' => [ ... Tymon\JWTAuth\Providers\LaravelServiceProvider:: class,]

3. Add a jwt.php configuration file under config

php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\LaravelServiceProvider"

4. Generate an encryption key under the .env file, such as: JWT_SECRET=foobar

php artisan jwt:secret

5. Write the following code in the user model

getKey(); } public function getJWTCustomClaims() { return []; } }

6. Register two Facade

config/app.php

'aliases' => [ ... // 添加以下两行 'JWTAuth' => 'Tymon\JWTAuth\Facades\JWTAuth', 'JWTFactory' => 'Tymon\JWTAuth\Facades\JWTFactory', ],

7. Modify auth.php

config/auth.php

'guards' => [ 'web' => [ 'driver' => 'session', 'provider' => 'users', ], 'api' => [ 'driver' => 'jwt', // 原来是 token 改成jwt 'provider' => 'users', ], ],

8. Register route

Route::group([ 'prefix' => 'auth' ], function ($router) { $router->post('login', 'AuthController@login'); $router->post('logout', 'AuthController@logout'); });

9. Create token controller

php artisan make:controller AuthController

The code is as follows:

middleware('auth:api', ['except' => ['login']]); } /** * Get a JWT via given credentials. * * @return \Illuminate\Http\JsonResponse */ public function login() { $credentials = request(['email', 'password']); if (! $token = auth('api')->attempt($credentials)) { return response()->json(['error' => 'Unauthorized'], 401); } return $this->respondWithToken($token); } /** * Get the authenticated User. * * @return \Illuminate\Http\JsonResponse */ public function me() { return response()->json(JWTAuth::parseToken()->touser()); } /** * Log the user out (Invalidate the token). * * @return \Illuminate\Http\JsonResponse */ public function logout() { JWTAuth::parseToken()->invalidate(); return response()->json(['message' => 'Successfully logged out']); } /** * Refresh a token. * * @return \Illuminate\Http\JsonResponse */ public function refresh() { return $this->respondWithToken(JWTAuth::parseToken()->refresh()); } /** * Get the token array structure. * * @param string $token * * @return \Illuminate\Http\JsonResponse */ protected function respondWithToken($token) { return response()->json([ 'access_token' => $token, 'token_type' => 'bearer', 'expires_in' => JWTAuth::factory()->getTTL() * 60 ]); } }

Note: attempt It keeps returning false because the password is encrypted. Just use bcrypt or password_hash to encrypt it.

10. Verify token to obtain user information.

There are two ways to use it:

Add to the url:?token=your token

Add to the header, it is recommended to use this, because it is more secure under https: Authorization:Bearer your token

11, First, use the artisan command to generate a middleware. I named it RefreshToken.php here. After the creation is successful, you need to inherit the JWT BaseMiddleware

The code is as follows:

checkForToken($request); // 使用 try 包裹,以捕捉 token 过期所抛出的 TokenExpiredException 异常 try { // 检测用户的登录状态,如果正常则通过 if ($this->auth->parseToken()->authenticate()) { return $next($request); } throw new UnauthorizedHttpException('jwt-auth', '未登录'); } catch (TokenExpiredException $exception) { // 此处捕获到了 token 过期所抛出的 TokenExpiredException 异常,我们在这里需要做的是刷新该用户的 token 并将它添加到响应头中 try { // 刷新用户的 token $token = $this->auth->refresh(); // 使用一次性登录以保证此次请求的成功 Auth::guard('api')->onceUsingId($this->auth->manager()->getPayloadFactory()->buildClaimsCollection()->toPlainArray()['sub']); } catch (JWTException $exception) { // 如果捕获到此异常,即代表 refresh 也过期了,用户无法刷新令牌,需要重新登录。 throw new UnauthorizedHttpException('jwt-auth', $exception->getMessage()); } } // 在响应头中返回新的 token return $this->setAuthenticationHeader($next($request), $token); } }

The main thing that needs to be said here is After the token is refreshed, not only does the token need to be placed in the return header, it is also best to replace the token in the request header, because after the refresh, the token in the request header has become invalid. If the business logic in the interface uses the request token in the header, then problems will arise.

Here we use

$request->headers->set('Authorization','Bearer '.$token);

to refresh the token in the request header.

After creating and writing the middleware, just register the middleware and add some exception handling in App\Exceptions\Handler.php.

12. Add middleware configuration in

$routeMiddleware in kernel.php file

'RefreshToken' => \App\Http\Middleware\RefreshToken::class,

13. Add routing

Route::group(['prefix' => 'user'],function($router) { $router->get('userInfo','UserController@userInfo')->middleware('RefreshToken'); });

Pass JWTAuth in the controller: :user(); can obtain user information

For more laravel framework technical articles, please visit

laraveltutorial!

The above is the detailed content of laravel installation jwt-auth and verification (example). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete