In this article, we will look at using JWT to secure our Laravel APIs.
JSON Web Token (JWT) is an open standard that allows two parties to securely send data and information as JSON objects. This information can be verified and trusted because it is digitally signed.
JWT authentication has aided the wider adoption of stateless API services. It makes it convenient to authorise and verify clients accessing API resources. It is a critical part of the authentication system in javascript powered applications.
<?php namespaceApp; useTymon\JWTAuth\Contracts\JWTSubject; useIlluminate\Notifications\Notifiable; useIlluminate\Foundation\Auth\UserasAuthenticatable; classUserextendsAuthenticatableimplementsJWTSubject # 这里别忘了加 { useNotifiable; public$table = 'user'; /** * The attributes that are mass assignable. * * @var array */ protected$fillable = [ 'name', 'password']; /** * The attributes that should be hidden for arrays. * * @var array */ protected$hidden = [ 'password', 'remember_token']; // Rest omitted for brevity /** * Get the identifier that will be stored in the subject claim of the JWT. * * @return mixed */ publicfunctiongetJWTIdentifier() { return$this->getKey(); } /** * Return a key value array, containing any custom claims to be added to the JWT. * * @return array */ publicfunctiongetJWTCustomClaims() { return []; } }
Before we define our API routes, we need to create a JwtM``iddleware which will protect our routes. Run this command via your terminal.
1
$ php artisan make:middleware JwtMiddleware
This will create a new middleware file inside our Middleware directory. This file can be located here app/Http/Middleware/JwtMiddleware. Open up the file and replace the content with the following:
This middleware extends Tymon\JWTAuth\Http\Middleware\BaseMiddleware, with this, we can catch token errors and return appropriate error codes to our users.
Next, we need to register our middleware. Open app/http/Kernel.php and add the following: