"tymon/jwt-auth": "^1.0@dev",
执行 composer update
'providers' => [ .... Tymon\JWTAuth\Providers\LaravelServiceProvider::class, // 上文已经提到过,这里的provider已经不是JWTauthServiceProvider ], 'aliases' => [ .... 'JWTAuth' => Tymon\JWTAuth\Facades\JWTAuth::class ],
发布配置文件#
php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\LaravelServiceProvider"
php artisan jwt:secret
/**
* Get the value of the model's primary key.
*
* @return mixed
*/
public function getKey()
{
return $this->getAttribute($this->getKeyName());
}
这个一般是得到id
调用Auth::guard('your jwt guard name')->attempt($credentials)
实际是调用了JWTGuard.php里面的attempt方法
oh yeah,终于生成了jwt token了
{"register_result1":"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOi8vbGFyYXZlbF9hcGkuYXBwL2FwaS9yZWdpc3RlciIsImlhdCI6MTUwMjM1NjE1MCwiZXhwIjoxNTAyMzU5NzUwLCJuYmYiOjE1MDIzNTYxNTAsImp0aSI6ImJSSHZsUXB5ZzN1WGtTR2MiLCJzdWIiOjksInBydiI6IjM3ODdmYmExNjE4YTkzMDUyNmFjYTZjOGJiOWI0NGI4M2YyOTc3MjYifQ.JpqCVjZggb2BHsCEXzITdnX70HbYIAfQY-iYSpkfHSw"}
$credentials我感觉不应该先用bcrypt,不然attempt会验证失败,只有插入数据库的时候才需要bcrypt
protected function getClaimsForSubject(JWTSubject $subject)
{
return [
'sub' => $subject->getJWTIdentifier(), //主键id
'prv' => $this->hashProvider($subject),
];
}
如何自定义customClaims
public function getJWTCustomClaims()
{
// TODO: Implement getJWTCustomClaims() method.
return ['key1' => 'elesos', 'key2' => 'test'];
}
上面是静态的,如何动态的加呢?
$client = DB::select('select * from clients where email = ?', [$email]);
//return $client;
//var_dump($client);return;//数组里面是对象元素
$customClaims = ['name' => $client[0]->name, 'vip_level' => '1'];
Auth::guard('client')->customClaims($customClaims);
接口如何访问
Route::get('/test1', function () {
return ['state' => 1, 'data' => 'sucess'];
})->middleware('auth:client');
或者
http://api.mysite.com/me?token={yourtokenhere}
验证token信息。
public function validate_test(){
//echo 'validate_test';
//$token = JWTAuth::getToken();
//return $token;
try {
if (! $user = JWTAuth::parseToken()->authenticate()) {
return response()->json(['user_not_found'], 404);
}
} catch (Tymon\JWTAuth\Exceptions\TokenExpiredException $e) {
return response()->json(['token_expired'], $e->getStatusCode());
} catch (Tymon\JWTAuth\Exceptions\TokenInvalidException $e) {
return response()->json(['token_invalid'], $e->getStatusCode());
} catch (Tymon\JWTAuth\Exceptions\JWTException $e) {
return response()->json(['token_absent'], $e->getStatusCode());
}
// the token is valid and we have found the user via the sub claim
return response()->json(compact('user'));
}
下一步要实现错误时返回json,而不是错误页面
Add the following code to the render method within app/Exceptions/Handler.php
public function render($request, Exception $e) { if ($e instanceof Tymon\JWTAuth\Exceptions\TokenExpiredException) { return response()->json(['token_expired'], $e->getStatusCode()); } else if ($e instanceof Tymon\JWTAuth\Exceptions\TokenInvalidException) { return response()->json(['token_invalid'], $e->getStatusCode()); } return parent::render($request, $e); }
或全部
// 这是我自己错定义的错误
return response()->json(array('error_code' => $e->getStatusCode()));
// 这是默认的错误返回,已注释了
//return parent::render($request, $e);
return response()->json(['errcode' => 4000, 'errmsg' => $exception->getMessage()], 200);
开发环境,当 APP_DEBUG = true 时,使用默认错误页面;
生产环境,当 APP_DEBUG = false 时,使用自定义错误页面,异步请求返回json异常信息
修改app/Exceptions/Handler.php
  1. public function render($request, Exception $exception)
  2. {
  3. $debug = config('app.debug', false);
  4. if($debug) {
  5. return parent::render($request, $exception);
  6. }
  7. if ($exception instanceof HttpException) {
  8. $code = $exception->getStatusCode();
  9. $message = $exception->getMessage();
  10. if ($request->expectsJson()) {
  11. return response()->json(['error' => $message], $code);
  12. }
  13. if (view()->exists('errors.custom' . $code)) {
  14. return response()->view('errors.custom' . $code, ['message'=>$message], $code);
  15. }
  16. }
  17. return parent::render($request, $exception);
  18. }
已知laravel5的默认Exceptions\Handler会优先匹配404异常,所以建议在Handler进行处理。
修改app/Exceptions/Handler.php的render方法如下
/** * Render an exception into an HTTP response. * * @param \Illuminate\Http\Request $request * @param \Exception $exception * @return \Illuminate\Http\Response */ public function render($request, Exception $exception) { if (is_a($exception, \Symfony\Component\HttpKernel\Exception\NotFoundHttpException::class) && $request->expectsJson()) { return response()->json(['msg'=>'NotFound']); } else { return parent::render($request, $exception); } }

laravel学习之路2: jwt集成的更多相关文章

  1. springboot 学习之路 3( 集成mybatis )

    目录:[持续更新.....] spring 部分常用注解 spring boot 学习之路1(简单入门) spring boot 学习之路2(注解介绍) spring boot 学习之路3( 集成my ...

  2. springboot 学习之路 6(集成durid连接池)

    目录:[持续更新.....] spring 部分常用注解 spring boot 学习之路1(简单入门) spring boot 学习之路2(注解介绍) spring boot 学习之路3( 集成my ...

  3. laravel学习之路4artisan

    php artisan list php artisan help migrate Tinker 让你可以在命令行中与 Laravel 应用进行交互php artisan tinker 在routes ...

  4. laravel学习之路1:认证相关

    Laravel中Auth::guard()表示什么意思? Auth::check() 是判断用户是否登录的方法,如果使用的默认用户系统,那这样使用没问题. 但是使用两组用户的话,如何使用各组用户的功能 ...

  5. springcloud学习之路: (五) springcloud集成SpringCloudConfig分布式配置中心

    SpringCloud全家桶中的分布式配置中心SpringCloudConfig, 它使用git来管理配置文件, 在修改配置文件后只需要调用一个接口就可以让新配置生效, 非常方便. SpringClo ...

  6. laravel学习之路5缓存

    redis需要先安装 需要通过 Composer 安装 predis/predis 扩展包 (~1.0) 或者使用 PECL 安装 PhpRedis PHP 拓展. composer require ...

  7. laravel学习之路3 数据库相关

    读写分离之多个读? 有 'host' => $readHosts[array_rand($readHosts)], 上面的好像有缓存问题php artisan config:cache ] ); ...

  8. springcloud学习之路: (四) springcloud集成Hystrix服务保护

    Hystrix是一套完善的服务保护组件, 可以实现服务降级, 服务熔断, 服务隔离等保护措施 使用它可以合理的应对高并发的情况 做到保护服务的效果 1. 导入依赖 <dependency> ...

  9. springcloud学习之路: (三) springcloud集成Zuul网关

    网关就是做一下过滤或拦截操作 让我们的服务更加安全 用户访问我们服务的时候就要先通过网关 然后再由网关转发到我们的微服务 1. 新建一个网关服务Module 2. 依然选择springboot工程 3 ...

随机推荐

  1. 大白话5分钟带你走进人工智能-第二十节逻辑回归和Softmax多分类问题(5)

                                                        大白话5分钟带你走进人工智能-第二十节逻辑回归和Softmax多分类问题(5) 上一节中,我们讲 ...

  2. openssl/ssl.h file not found

    sample/le-proxy.c:33:10: fatal error: 'openssl/ssl.h' file not found mac下,在安装某些软件的时候提示如上错误,但是mac已经安装 ...

  3. window linux 文件传输

    window 安装:pscp.exe (放在C:\Windows\System32 目录下) Linux 安装: 1: 先更新apt-getroot@ubuntu:/home/ubuntu# sudo ...

  4. EasyMvc入门教程

    EasyMvc 希望实现的目标:模块化,快速简单化,满足80%的常见需求.基于.Net Core 2.0.5开发.开发环境:VS2017,运行环境支持Window/Linux. 相关链接: 演示地址: ...

  5. S5PV210使用的启动方式

    2017年12月25日1. S5PV210存储配置: +内置64KB NorFlash(上电不需要初始化)(叫IROM 内部外存):用于存储预先设置的BL0; + SoC内置96KB SRAM(上电不 ...

  6. iptables 的学习资源

    慕课网:https://www.imooc.com/video/7617 马哥linux视频:http://edu.51cto.com//center/course/lesson/index?id=9 ...

  7. 转: 由socket的accept说开去

    from: http://ticktick.blog.51cto.com/823160/779866 今天与同学争执一个话题:由于socket的accept函数在有客户端连接的时候产生了新的socke ...

  8. 【LeetCode-面试算法经典-Java实现】【109-Convert Sorted List to Binary Search Tree(排序链表转换成二叉排序树)】

    [109-Convert Sorted List to Binary Search Tree(排序链表转换成二叉排序树)] [LeetCode-面试算法经典-Java实现][全部题目文件夹索引] 原题 ...

  9. Angular 学习笔记——shop

    <!DOCTYPE html> <html lang="en" ng-app> <head> <meta charset="UT ...

  10. iOS实录:GCD使用小结(一)

    导语:在iOS中,多线程方案有四种:pthread.NSThread.NSOperation & NSOperationQueue 和 GCD,但是开发中GCD使用得最多,本文主要总结一下我使 ...