生成token的方法 参考我上一篇文章,这篇是在token生成后,对token进行验证
一、app\Providers\AuthServiceProvider.php
文件中有个方法boot,在上一篇中已经创建好了
/**
* Boot the authentication services for the application.
*
* @return void
*/
public function boot()
{
// Here you may define how you wish users to be authenticated for your Lumen
// application. The callback which receives the incoming request instance
// should return either a User instance or null. You're free to obtain
// the User instance via an API token or any other method necessary.
$this->app['auth']->viaRequest('api', function ($request) {
return \App\User::where('email', $request->input('email'))->first();
});
}
二、在控制器中新建方法
/**
* 验证token的方法
*/
public function test(Request $request){
// 获取到客户端header中传过来的 authorization
// $token = $this->jwt->setRequest($request)->getToken();
// 验证token是否可以使用
// $user = $this->jwt->authenticate($token)->toArray();
// 刷新token
// $newToken = $this->jwt->refresh($token);
// 获取token的过期时间
$newToken = $this->jwt->factory()->getTTL() * 60;
dd( $newToken );
exit;
// DB::connection()->enableQueryLog();
$info = app('auth')->user()->toArray();
// $sql = DB::getQueryLog();
echo date('Y-m-d H:i:s',time());
dd( $info );
}
三、创建路由并引入中间件
$api->version( ['v1', 'v2'], ['namespace' => 'App\Http\Controllers\Auth', 'middleware' => 'auth:api'], function($api){
//获取token
$api->post('auth/test', 'AuthenticateController@test');
});
四、在postman上面请求接口
token验证不同过的时候会返回Unauthorized.
这个返回值可以修改中间件中的方法(handle)自定义 路径 App\Http\Middleware\Authenticate.php :
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Contracts\Auth\Factory as Auth;
class Authenticate
{
/**
* The authentication guard factory instance.
*
* @var \Illuminate\Contracts\Auth\Factory
*/
protected $auth;
/**
* Create a new middleware instance.
*
* @param \Illuminate\Contracts\Auth\Factory $auth
* @return void
*/
public function __construct(Auth $auth)
{
$this->auth = $auth;
}
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @param string|null $guard
* @return mixed
*/
public function handle($request, Closure $next, $guard = null)
{
if ($this->auth->guard($guard)->guest()) {
// return response('Unauthorized.', 401);
return response('token验证失败.请重新登录', 401);
}
return $next($request);
}
}
image.png
验证通过的时候请求正常
image.png
有点乱,后面再整理........................
网友评论