laravel使用JWT做API认证

最近项目做API认证,最终技术选型决定使用JWT,项目框架使用的是laravel,laravel使用JWT有比较方便使用的开源包:jwt-auth。php 后端实现JWT认证方法
使用composer安装jwt-auth,laravel使用的框架版本为5.0,jwt-auth最新稳定版本为0.5.12。(最新版为1.0.*,需laravel5.4以上)


composer require tymon/jwt-auth 0.5.*

安装完成后,需要在config/app.php中注册相应的服务提供者:

'providers' => [
    'TymonJWTAuthProvidersJWTAuthServiceProvider',
],

然后注册需要用到的对应门面:

'aliases' => [
    'JWTAuth'   => 'TymonJWTAuthFacadesJWTAuth',
    'JWTFactory' => 'TymonJWTAuthFacadesJWTFactory',
],

然后发布相应配置文件:此命令会在 config 目录下生成一个 jwt.php 配置文件,你可以在此进行自定义配置。

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

最后生成密钥:此命令会在你的 .env 文件中新增一行 JWT_SECRET=secret

php artisan jwt:generate

生成TOKEN,生成TOKEN有多种方式:下面介绍两种
一、根据模型为基础生成TOKEN:


根据模型生成TOKEN需在config/auth.php指定使用哪个模型。

    'model' => 'AppModelsMembers',

在模型文件Members.php中需添加

namespace AppModels;

use IlluminateDatabaseEloquentModel;
use IlluminateAuthAuthenticatable;
use IlluminateContractsAuthAuthenticatable as AuthenticatableContract;

class Members extends Model implements AuthenticatableContract
{
    use Authenticatable;
    ...
}


根据模型生成TOKEN

$member = AppModelsMembers::where('id',7)->select('id','username')->first();
$token = JWTAuth::fromUser($member);
echo $token;exit;

二、自定义生成TOKEN:


$customClaims = ['sub' => [
    'id' => '7',
    'name' => 'kocor',
]];
$payload = JWTFactory::make($customClaims);
$token = JWTAuth::encode($payload);
echo $token;exit;

解密提取TOKEN信息


提取TOKEN信息

$user_info = JWTAuth::parseToken()->authenticate()

刷新TOKEN

$newToken = JWTAuth::refresh($_REQUEST['token']);

使用实例

        
use TymonJWTAuthExceptionsJWTException;
use TymonJWTAuthExceptionsTokenExpiredException;
use TymonJWTAuthExceptionsTokenInvalidException;


//JWT提取会员信息
try {
    if (! $user_info = JWTAuth::parseToken()->authenticate()) {
        return Api::arr(config('statusCode.jwt_user_not_found'), trans('message.jwt_user_not_found').':404');
    }
    //在token有效期内允许刷新
    $newToken = JWTAuth::refresh($_REQUEST['token']);
    return Api::json(config('statusCode.success'), trans('message.success'),$newToken);
} catch (TokenExpiredException $e) {
    try {
        //在刷新有效期内
        $newToken = JWTAuth::refresh($_REQUEST['token']);
        return Api::json(config('statusCode.success'), trans('message.success'),$newToken);
    } catch (JWTException $e) {
        // 过期用户
        return Api::json(config('statusCode.jwt_token_expired'), trans('message.jwt_token_expired').$e->getStatusCode());
    }
//无效的token
} catch (TokenInvalidException $e) {
    return Api::json(config('statusCode.jwt_token_invalid'), trans('message.jwt_token_invalid').$e->getStatusCode());
//token不存在
} catch (JWTException $e) {
    return Api::json(config('statusCode.jwt_token_absent'), trans('message.jwt_token_absent').$e->getStatusCode());
}    

by kocor

原文地址:https://segmentfault.com/a/1190000016391157

原文地址:https://www.cnblogs.com/lalalagq/p/9971384.html