Laravel中使用JWT

Posted 酷极和

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Laravel中使用JWT相关的知识,希望对你有一定的参考价值。

Laravel 版本:

Laravel Framework 6.18.3

查看版本命令:

php artisan -V

1、安装JWT扩展包:

composer require tymon/jwt-auth:dev-develop --prefer-source

2、发布配置文件:

php artisan vendor:publish --provider="TymonJWTAuthProvidersLaravelServiceProvider"

3、生成JWT密钥:

php artisan jwt:secret

4、在 app/Http/Kernel.php 中注册 auth.jwt 中间件:

protected $routeMiddleware = [
    ....
    ‘auth.jwt‘ => TymonJWTAuthHttpMiddlewareAuthenticate::class,
];

5、设置路由:

Route::post(‘login‘, ‘ApiController@login‘);
Route::post(‘register‘, ‘ApiController@register‘);
Route::group([‘middleware‘ => ‘auth.jwt‘], function () {
    Route::get(‘logout‘, ‘ApiController@logout‘);
  Route::get(‘user‘, ‘ApiController@getAuthUser‘);
});

6、更新User模型:

JWT 需要在 User 模型中实现 TymonJWTAuthContractsJWTSubject 接口。 此接口需要实现两个方法  getJWTIdentifier 和 getJWTCustomClaims。使用以下内容更新 app/User.php 。

技术图片
<?php

namespace App;

use IlluminateFoundationAuthUser as Authenticatable;
use IlluminateNotificationsNotifiable;
use TymonJWTAuthContractsJWTSubject;

class User extends Authenticatable implements JWTSubject
{
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        ‘name‘, ‘email‘, ‘password‘,
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        ‘password‘, ‘remember_token‘,
    ];

    /**
     * Get the identifier that will be stored in the subject claim of the JWT.
     *
     * @return mixed
     */
    public function getJWTIdentifier()
    {
        return $this->getKey();
    }

    /**
     * Return a key value array, containing any custom claims to be added to the JWT.
     *
     * @return array
     */
    public function getJWTCustomClaims()
    {
        return [];
    }
}
View Code

7、修改config/auth.php文件:

‘guards‘ => [     
   ....
‘admin‘ => [ ‘driver‘ => ‘jwt‘, ‘provider‘ => ‘admins‘, ], ]
‘providers‘ => [
     ....
‘admins‘ => [ ‘driver‘ => ‘eloquent‘, ‘model‘ => AppUser::class, ], ]

8、控制器示例:

技术图片
<?php

namespace AppHttpControllers;

use AppUser;
use IlluminateHttpRequest;
use TymonJWTAuthJWTAuth;
use TymonJWTAuthExceptionsJWTException;

class ApiController extends Controller
{
    public $loginAfterSignUp = true;

    public function register(Request $request)
    {
        $user = new User();
        $user->name = $request->name;
        $user->email = $request->email;
        $user->password = bcrypt($request->password);
        $user->save();

        if ($this->loginAfterSignUp) {
            return $this->login($request);
        }

        return response()->json([
            ‘success‘ => true,
            ‘data‘ => $user
        ], 200);
    }

    public function login(Request $request)
    {
        $input = $request->only(‘email‘, ‘password‘);
        $jwt_token = null;
        $guard = auth(‘admin‘);
        if (!$jwt_token = $guard->attempt($input)) {
            return response()->json([
                ‘success‘ => false,
                ‘message‘ => ‘Invalid Email or Password‘,
            ], 401);
        }

        return response()->json([
            ‘success‘ => true,
            ‘token‘ => $jwt_token,
        ]);
    }

    public function logout(Request $request)
    {
        $this->validate($request, [
            ‘token‘ => ‘required‘
        ]);

        try {
            $guard = auth(‘admin‘);
            $guard->invalidate($request->token);

            return response()->json([
                ‘success‘ => true,
                ‘message‘ => ‘User logged out successfully‘
            ]);
        } catch (JWTException $exception) {
            return response()->json([
                ‘success‘ => false,
                ‘message‘ => ‘Sorry, the user cannot be logged out‘
            ], 500);
        }
    }

    public function getAuthUser(Request $request)
    {
        $this->validate($request, [
            ‘token‘ => ‘required‘
        ]);

        $user = JWTAuth::authenticate($request->token);

        return response()->json([‘user‘ => $user]);
    }
}    
View Code

Enjoy it !

....

以上是关于Laravel中使用JWT的主要内容,如果未能解决你的问题,请参考以下文章

在 laravel 中查找具有 JWT 令牌的用户 id

需要一种有效的方法来避免使用 Laravel 5 重复代码片段

Laravel - JWT Auth 无法从请求中解析令牌

如何在 Laravel 5.7 中生成 JWT 刷新令牌

Laravel 5.3 使用 JWT Auth 时限制登录

Laravel中使用JWT