zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    10 种保护 Spring Boot 应用的绝佳方法
    Redis 如何分析慢查询操作?
    Spring Boot 主类及目录结构介绍
    Redis 再牛逼,也得设置密码!!
    Spring Data Redis 详解及实战一文搞定
    Spring Boot Redis Cluster 实战干货
    超详细的 Redis Cluster 官方集群搭建指南
    Redis Linux 安装运行实战全记录
    hdu 4790 Just Random (思路+分类计算+数学)
    poj 1328 Radar Installation(贪心)
  • 原文地址:https://www.cnblogs.com/lalalagq/p/9971384.html
Copyright © 2011-2022 走看看