安装

运行以下命令把最新版本:

composer require tymon/jwt-auth
#这里可能有个坑 使用这个命令下载的版本并不是最新的??是' ^0.5.12'
#修改composer.json 版本为 '1.0.0-rc.1'
#执行 composer update

将以下代码片段添加到bootstrap/app.php文件中,是根据包提供商
在服务提供者注册区需改变如下:


// 取消这行注释
$app->register(App\Providers\AuthServiceProvider::class);// 添加jwt的服务
$app->register(Tymon\JWTAuth\Providers\LumenServiceProvider::class);

中间件区

//取消auth中间件注释
$app->routeMiddleware(['auth' => App\Http\Middleware\Authenticate::class,
]);

修改过后我的 app.php 文件是这样:(如果像我新下载框架,官方教只是局部文档)

<?phprequire_once __DIR__.'/../vendor/autoload.php';try {(new Dotenv\Dotenv(__DIR__.'/../'))->load();
} catch (Dotenv\Exception\InvalidPathException $e) {//
}/*
|--------------------------------------------------------------------------
| Create The Application
|--------------------------------------------------------------------------
|
| Here we will load the environment and create the application instance
| that serves as the central piece of this framework. We'll use this
| application as an "IoC" container and router for this framework.
|
*/$app = new Laravel\Lumen\Application(realpath(__DIR__.'/../')
);$app->withFacades();$app->withEloquent();//config
// jwt
$app->configure('auth');
/*
|--------------------------------------------------------------------------
| Register Container Bindings
|--------------------------------------------------------------------------
|
| Now we will register a few bindings in the service container. We will
| register the exception handler and the console kernel. You may add
| your own bindings here if you like or you can make another file.
|
*/$app->singleton(Illuminate\Contracts\Debug\ExceptionHandler::class,App\Exceptions\Handler::class
);$app->singleton(Illuminate\Contracts\Console\Kernel::class,App\Console\Kernel::class
);/*
|--------------------------------------------------------------------------
| Register Middleware
|--------------------------------------------------------------------------
|
| Next, we will register the middleware with the application. These can
| be global middleware that run before and after each request into a
| route or middleware that'll be assigned to some specific routes.
|
*/// $app->middleware([
//    App\Http\Middleware\ExampleMiddleware::class
// ]);$app->routeMiddleware(['auth' => App\Http\Middleware\Authenticate::class,]);/*
|--------------------------------------------------------------------------
| Register Service Providers
|--------------------------------------------------------------------------
|
| Here we will register all of the application's service providers which
| are used to bind services into the container. Service providers are
| totally optional, so you are not required to uncomment this line.
|
*/$app->register(App\Providers\AppServiceProvider::class);$app->register(App\Providers\AuthServiceProvider::class);
// $app->register(App\Providers\EventServiceProvider::class);// Add this line
$app->register(Tymon\JWTAuth\Providers\LumenServiceProvider::class);
/*
|--------------------------------------------------------------------------
| Load The Application Routes
|--------------------------------------------------------------------------
|
| Next we will include the routes file so that they can all be added to
| the application. This will provide all of the URLs the application
| can respond to, as well as the controllers that may handle them.
|
*/$app->router->group(['namespace' => 'App\Http\Controllers',
], function ($router) {require __DIR__.'/../routes/web.php';
});return $app;

使用artisan生成jwt secret key

php artisan jwt:secret

运行这行命令后会在.env文件中生成如 JWT_SECRET=foobar
这里需要额外提的是lumen默认是没有类似llaravel的config配置文件夹的,所有包的配置都是直接去读的.env中的配置。如果想要和laravel一样,自己按照laravel目录结构额外新建一个config文件夹
如生成auth.php,可以把服务提供商中的配置文件拷贝出来或者自己写配置也行。要使配置文件生效,应在bootstrap/app.php文件中添加

#官方好像没有这一步,但是使用lumen这步也是需要注意的,我是添加了这行,因为我沿用laravel的目录风格
$app->configure('auth');

使用

安装jwt

jwt-auth是专为laravel和lumen量身定制的包,因此必须安装使用这个两者之一

#安装lumen or laravel 使用composer 没有跟版本号,默认安装最新的composer create-project --prefer-dist laravel/lumen test
#or
composer create-project --prefer-dist laravel/laravel test
 composer require tymon/jwt-auth
更新User Model

建议不要框架自带的一个User.php ,在app目录下新建一个Models目录,新建User.php Model 必须满足Tymon\JWTAuth\Contracts\JWTSubject 契约,官方推荐更为为如下,可以根据需求再自定其他功能。
根据官方的 User.php我做了一下调整,为什么要调整,是为了代码能跑起来

<?php
/*** Created by PhpStorm.* User: hony* Date: 2018/1/19* Time: 11:57*/namespace App\Models;use Tymon\JWTAuth\Contracts\JWTSubject;
#use Illuminate\Notifications\Notifiable;
#use Illuminate\Foundation\Auth\User as Authenticatable;
use Laravel\Lumen\Auth\Authorizable;use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
class User extends Model implements AuthenticatableContract, JWTSubject
{#use Notifiable;use Authenticatable;// Rest omitted for brevity/*** 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 [];}
}
config配置

基于laravel的 config/auth.php 文件需要做一些修改才能使用JWT
的守护,官方提供需要修改如下:

我的 config/auth.php,如下

<?php
/*** Created by PhpStorm.* User: hony* Date: 2018/1/19* Time: 14:35*/
return [/*|--------------------------------------------------------------------------| Authentication Defaults|--------------------------------------------------------------------------|| This option controls the default authentication "guard" and password| reset options for your application. You may change these defaults| as required, but they're a perfect start for most applications.|*/'defaults' => ['guard' => 'api','passwords' => 'users',],/*|--------------------------------------------------------------------------| Authentication Guards|--------------------------------------------------------------------------|| Next, you may define every authentication guard for your application.| Of course, a great default configuration has been defined for you| here which uses session storage and the Eloquent user provider.|| All authentication drivers have a user provider. This defines how the| users are actually retrieved out of your database or other storage| mechanisms used by this application to persist your user's data.|| Supported: "session", "token"|*/'guards' => ['api' => ['driver' => 'jwt','provider' => 'users',]],'providers' => ['users' => ['driver' => 'eloquent',//这里是因为我用的mysql做的测试'model' => App\Models\User::class,],],
];

这里是告诉应用默认使用api守护,api守护是使用jwt驱动
在身份验证系统里lumen应该使用的是laravel的构建与jwt-auth做幕后的工作!

添加一些基本身份验证路由

routes/api.php添加,也可以做区分

Route::group([//'middleware' => 'auth',这里本来是api的被我改成auth,但是在登录的时候不需要auth中间件验证'prefix' => 'auth'], function ($router) {Route::post('login', 'AuthController@login');Route::post('logout', 'AuthController@logout');Route::post('refresh', 'AuthController@refresh');Route::post('me', 'AuthController@me');});#延伸扩展区分
Route::group(['middleware' => 'token'], function () {#这个文件中再去指定控制器等require(__DIR__ . '/api/cases.php');
});
创建AuthController
php artisan make:controller AuthController
#但是lumen本事是没有make:controller命令的,我是手动生成

然后添加内容

<?phpnamespace App\Http\Controllers;use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;class AuthController extends Controller
{/*** Create a new AuthController instance.** @return void*/public function __construct(){#这个句是官方提供的,还没有验证是否有效#$this->middleware('auth:api', ['except' => ['login']]);}/*** Get a JWT token via given credentials.** @param  \Illuminate\Http\Request  $request** @return \Illuminate\Http\JsonResponse*/public function login(Request $request){$credentials = $request->only('email', 'password');if ($token = $this->guard()->attempt($credentials)) {return $this->respondWithToken($token);}return response()->json(['error' => 'Unauthorized'], 401);}/*** Get the authenticated User** @return \Illuminate\Http\JsonResponse*/public function me(){return response()->json($this->guard()->user());}/*** Log the user out (Invalidate the token)** @return \Illuminate\Http\JsonResponse*/public function logout(){$this->guard()->logout();return response()->json(['message' => 'Successfully logged out']);}/*** Refresh a token.** @return \Illuminate\Http\JsonResponse*/public function refresh(){return $this->respondWithToken($this->guard()->refresh());}/*** Get the token array structure.** @param  string $token** @return \Illuminate\Http\JsonResponse*/protected function respondWithToken($token){return response()->json(['access_token' => $token,'token_type' => 'bearer','expires_in' => $this->guard()->factory()->getTTL() * 60]);}/*** Get the guard to be used during authentication.** @return \Illuminate\Contracts\Auth\Guard*/public function guard(){return Auth::guard();}
}

测试登录路由 http://example.dev/auth/login
身份验证响应

{"access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ","token_type": "bearer","expires_in": 3600
}

这个令牌可以用来制造经过身份验证的请求,您的应用程序。

验证请求方式 Authenticated requests

There are a number of ways to send the token via http:

Authorization header

Authorization: Bearer eyJhbGciOiJIUzI1NiI…

Query string parameter

http://example.dev/me?token=eyJhbGciOiJIUzI1NiI…

我的请求方式 我使用的是postman


最后,需要最值的注意的是,这个jwt的默认验证方式是hash。

lumen5.5 使用 jwt-auth1.0 笔记相关推荐

  1. actionscript 3.0 怎么写android 程序,(ActionScript3.0笔记)第一个程序HelloWorld!

    (ActionScript3.0笔记)第一个程序HelloWorld! 创建我的第一个ActionScript3.0程序--HelloWord! 首先下载ActionScript3.0的集成开发环境, ...

  2. C#3.0笔记(一)预备知识之Delegate

    在学习C#3.0之前还是先来回顾下委托.事件,因为这样能更加有助于理解C#3.0里面的一些新的特性,如Lambada表达式等. 背景 在C语言中我们可以用函数指针来创建回调函数,但是在C里面回调函数存 ...

  3. 人工智能实践:Tensorflow2.0笔记 北京大学MOOC(1-1)

    人工智能实践:Tensorflow2.0笔记 北京大学MOOC(1-1) 说明 一.神经网络计算过程 1. 人工智能三学派 2. 神经网络设计过程 2.1 人脑中的神经网络形成过程 2.2 计算机模仿 ...

  4. 乐鑫esp8266学习rtos3.0笔记第3篇: 一篇文章带你搞掂存储技术 NVS 的认识和使用,如何利用NVS保存整型、字符串、数组以及结构体。(附带demo)

    本系列博客学习由非官方人员 半颗心脏 潜心所力所写,不做开发板.仅仅做个人技术交流分享,不做任何商业用途.如有不对之处,请留言,本人及时更改. 1. Esp8266之 搭建开发环境,开始一个" ...

  5. 乐鑫esp8266学习rtos3.0笔记第9篇:整理分享那些我在项目中常用的esp8266 rtos3.0版本的常见驱动,Button按键长短按、PWM平滑调光等。(附带demo)

    本系列博客学习由非官方人员 半颗心脏 潜心所力所写,仅仅做个人技术交流分享,不做任何商业用途.如有不对之处,请留言,本人及时更改. 1. Esp8266之 搭建开发环境,开始一个"hello ...

  6. 乐鑫esp8266学习rtos3.0笔记:仅1M flash 的安信可 ESP-01S 模块,如何二次开发?如何对其 OTA 远程升级固件!

    本系列博客学习由非官方人员 半颗心脏 潜心所力所写,不做开发板.仅仅做个人技术交流分享,不做任何商业用途.如有不对之处,请留言,本人及时更改. 1. Esp8266之 搭建开发环境,开始一个" ...

  7. 乐鑫esp8266学习rtos3.0笔记第4篇:带你捋一捋微信公众号 airkiss 配网 esp8266 并绑定设备的过程,移植并成功实现在 esp8266 rtos3.1 sdk。(附带demo)

    本系列博客学习由非官方人员 半颗心脏 潜心所力所写,仅仅做个人技术交流分享,不做任何商业用途.如有不对之处,请留言,本人及时更改. 1. Esp8266之 搭建开发环境,开始一个"hello ...

  8. OAuth 2.0 笔记 (1) 世界观

    OAuth 2.0笔记(1)世界观 来自台湾同胞的博客:https://blog.yorkxin.org/posts/oauth2-1-introduction.html,繁体字做了复制转换. 最近需 ...

  9. 乐鑫esp8266学习rtos3.0笔记第5篇:基于乐鑫idf框架,研究出超稳定、掉线重连、解决内存泄露问题的Mqtt框架,支持esp8266和esp32!(附带链接)

    本系列博客学习由非官方人员 半颗心脏 潜心所力所写,不做开发板.仅仅做个人技术交流分享,不做任何商业用途.如有不对之处,请留言,本人及时更改. 1. Esp8266之 搭建开发环境,开始一个" ...

  10. 乐鑫esp8266学习rtos3.0笔记第12篇:无需外网,如何实现在本地局域网与控制端做数据交换,分享开发心得。(附带demo)

    本系列博客学习由非官方人员 半颗心脏 潜心所力所写,不做开发板.仅仅做个人技术交流分享,不做任何商业用途.如有不对之处,请留言,本人及时更改. 1. Esp8266之 搭建开发环境,开始一个" ...

最新文章

  1. android 开源Spanner,著名的分布式事务数据库谷歌Spanner设计有坑!
  2. springcloud基于ribbon的canary路由方案
  3. Centos7 安装 memcached 1.4.25
  4. 教你如何成为一名区块链工程师!
  5. Nginx中木马解决方法
  6. 使用GruntJS构建Web程序 (1)
  7. mysql性能优化-慢查询分析、优化索引和配置
  8. MapReduce运行机制-Reduce阶段
  9. php version 5.5.17-1~dotdeb.1,Ubuntu 12.04使用Dotdeb安装PHP5.4 / Nginx1.4/Redis2.6等新版本
  10. 深入浅出mybatis之入门使用
  11. 为什么都建议学java而不是python-为什么都建议学Java而不是Python?两者有什么区别吗?...
  12. 3.Kong入门与实战 基于Nginx和OpenResty的云原生微服务网关 --- Kong 的管理运维
  13. Mysql 存储过程、存储函数 与 递归查询
  14. 基于android的垃圾分类识别,垃圾分类扫描识别
  15. 爬虫小程序 - 周杰伦歌曲
  16. tp6分页显示首页和尾页
  17. 跨模态行人重识别综述 - 计算机视觉
  18. AC-DMIS 5.3自动测量平面(自定义触测点、批量测量)
  19. imx6ull 以太网
  20. android怎么测试网速,Android网速测试App(三)

热门文章

  1. 利用天翎知识文档+群晖NAS搭建企业知识库,享用智能检索
  2. 爬虫实例5:使用scrapy框架获取链家网二手房最新信息(获取单个城市所有街区二手房信息可以使用selenium动态获取页数)
  3. 一个脚本打比赛之SMP WEIBO 2016
  4. 城市区域二手房信息python爬取、保存和初步分析—笔记
  5. ffmpeg 合并拼接 mp4视频
  6. cmd.exe启动参数详解
  7. Matlab数字信号处理的仿真系统(具有界面)
  8. 【LiteOS】小白进阶之系统移植配置解析
  9. VMware下怎么批量创建,克隆,迁移虚拟机
  10. 从大学毕业的迷茫,到现在拿到高薪,感谢爱创课堂的老师