Laravel installation of JWT-Auth and validation

My official group click here.

1, Use Composer to install JWT, CMD into the project folder;

Composer require Tymon /jwt-auth 1.0.*

Install JWT, refer to the official documentation JWT – auth. Readthedocs. IO/en/docs/lar…

2. If laravel version is lower than 5.4

Open config/app.php in the root directory

In the array with Tymon \ JWTAuth \ ‘will’ will \ LaravelServiceProvider: : class,

‘providers’ => [ … Tymon\JWTAuth\Providers\LaravelServiceProvider::class,]

3, add a jwt.php config file under config

php artisan vendor:publish –provider=”Tymon\JWTAuth\Providers\LaravelServiceProvider”

Env file to generate an encryption key, such as JWT_SECRET=foobar

php artisan jwt:secret

5. Write the following code in the User model

<? php namespace App\Model; use Tymon\JWTAuth\Contracts\JWTSubject; use Illuminate\Notifications\Notifiable; use Illuminate\Foundation\Auth\User as Authenticatable; class User extends Authenticatable implements JWTSubject { // Rest omittedfor brevity
 protected $table="user";
 public $timestamps = false;
 public function getJWTIdentifier()
 {
 return $this->getKey();
 }
 public function getJWTCustomClaims()
 {
 return[]; }}Copy the code

Register two facades

config/app.php

'aliases'=> [... // Add the following two lines'JWTAuth'= >'Tymon\JWTAuth\Facades\JWTAuth'.'JWTFactory'= >'Tymon\JWTAuth\Facades\JWTFactory',].Copy the code

7, modify auth.php

config/auth.php

'guards'= > ['web'= > ['driver'= >'session'.'provider'= >'users',].'api'= > ['driver'= >'jwt'// Change the token to JWT'provider'= >'users',]],Copy the code

8. Register routes

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

Create the Token controller

php artisan make:controller AuthController

The code is as follows:

<? php namespace App\Http\Controllers; use App\Model\User; use Illuminate\Http\Request; use Tymon\JWTAuth\Facades\JWTAuth; class AuthController extends Controller { /** * Create a new AuthController instance. * * @return void
 */
 public function __construct()
 {
 $this->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 ]); }}Copy the code

Note: Attempt always returns false because the password is encrypted using bcrypt or password_hash

10. Verify token to obtain user information

There are two ways to use it:

Add to url:? Token = your token

Add to the header and recommend this as it is more secure when HTTPS is involved: Authorization:Bearer of your tokens

11, first use artisan command to generate a middleware, I named refreshtok.php, after the successful creation, need to inherit JWT BaseMiddleware

The code is as follows:

<? php namespace App\Http\Middleware; use Auth; use Closure; use Tymon\JWTAuth\Exceptions\JWTException; use Tymon\JWTAuth\Http\Middleware\BaseMiddleware; use Tymon\JWTAuth\Exceptions\TokenExpiredException; use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException; / / note that BaseMiddleware {/** * Handle an incoming request. ** @param \Illuminate\Http\Request$request
 * @ param  \Closure $next
 *
 * @ throws \Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException
 *
 * @ return mixed
 */
 public function handle($request, Closure $next) {// Check if there is a token in this request and throw an exception if there is no token.$this->checkForToken($request); // Use the try package to catch the TokenExpiredException thrown by token expiration try {// Check the user login status, if normal passif ($this->auth->parseToken()->authenticate()) {
 return $next($request);
 }
 throw new UnauthorizedHttpException('jwt-auth'.'Not logged in');
 } catch (TokenExpiredException $exception) {// Here we catch a TokenExpiredException thrown by the token expiration. What we need to do here is refresh the user's token and add it to the response header try {// Refresh the user's token$token = $this->auth->refresh(); Auth::guard('api')->onceUsingId($this->auth->manager()->getPayloadFactory()->buildClaimsCollection()->toPlainArray()['sub']);
 } catch (JWTException $exception) {// If this exception is caught, refresh is also expired and the user cannot refresh the token and needs to log in again. throw new UnauthorizedHttpException('jwt-auth'.$exception->getMessage()); }} // Return the new token in the response headerreturn $this->setAuthenticationHeader($next($request), $token); }}Copy the code

The main point here is that after the token is refreshed, it is not only necessary to put the token in the return header, but also better to replace the token in the request header, because after the refresh, the token in the request header is invalid. If the business logic in the interface uses the token in the request header, then there will be a problem.

Used here

$request->headers->set('Authorization'.'Bearer '.$token);Copy the code

Flushes the token in the request header.

Once the middleware is created and written, just register the middleware and add some exception handling to App\Exceptions\ handler.php.

12, kernel. PHP file

$routeMiddleware adds middleware configuration

'RefreshToken' => \App\Http\Middleware\RefreshToken::class,Copy the code

13. Add a route

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

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

For more PHP content visit:

Tencent T3-T4 standard boutique PHP architect tutorial directory directory, as long as you finish the guarantee salary rise a step (continue to update)


I hope the above content can help you. Many PHPer will encounter some problems and bottlenecks when they are advanced, and they have no sense of direction when writing too many business codes. I have sorted out some information, including but not limited to: Distributed architecture, high scalability, high performance, high concurrency, server performance tuning, TP6, Laravel, YII2, Redis, Swoole, Swoft, Kafka, Mysql optimization, shell scripting, Docker, microservices, Nginx, etc.