1.安装
composer.json中直接添加
"require": {
"tymon/jwt-auth": "0.5.*"
},
然后执行composer update,完成后在vendor目录下会出现tymon文件夹
2.配置
config/app.php中providers添加以下内容:
Tymon\JWTAuth\Providers\JWTAuthServiceProvider::class
config/app.php中aliases添加以下内容:
'JWTAuth' => 'Tymon\JWTAuth\Facades\JWTAuth',
'JWTFactory' => 'Tymon\JWTAuth\Facades\JWTFactory',
app\Http\Kernel.php中$routeMiddleware添加以下内容:
'jwt.auth' => 'Tymon\JWTAuth\Middleware\GetUserFromToken',
'jwt.refresh' => 'Tymon\JWTAuth\Middleware\RefreshToken',
在项目目录 下执行以下命令:
php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\JWTAuthServiceProvider"
php artisan jwt:generate
执行php artisan jwt:generate命令时会报找不到handle()方法找不到,找到vendor\tymon\jwt-auth\src\Commands\JWTGenerateCommand.php文件中添加以下方法:
public function handle()
{
$this->fire();
}
然后再执行以上命令
3.应用
1.添加路由
api.php路由下添加以下内容:
Route::post('register', 'ApiController@register'); // 注册
Route::post('login', 'ApiController@login'); // 登陆
Route::group(['middleware' => 'jwt.auth'], function () {
Route::post('get_user_details', 'ApiController@get_user_details'); // 获取用户详情
});
Route::post('auth/refresh-token', ['middleware' => 'jwt.refresh', function(Request $request) { //刷新token
//这里根据自身情况而定,本身是不会输入结果的,其生成的token会在返回的header中返回
$authorization = $request->headers->get('authorization');
return response()->json(compact('authorization'));
}]);
控制器文件:app\Http\Controllers\ApiController.php
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\User; use Illuminate\Support\Facades\Hash; use Tymon\JWTAuth\Facades\JWTAuth; class ApiController extends Controller { /*注册*/ public function register(Request $request) { $input = $request->all(); if(!isset($input['password'])){ return response()->json(['error' => 'password not given'], 500); } try{ $input['password'] = Hash::make($input['password']); User::create($input); return response()->json(['result'=>true]); }catch (Exception $e) { return response()->json(['error' => 'could_not_create_token'], 500); } } /*登陆*/ public function login(Request $request) { $input = $request->all(); if (!$token = JWTAuth::attempt($input)) { return response()->json(['result' => '邮箱或密码错误.']); } return response()->json(['result' => $token]); } /*获取用户信息*/ public function get_user_details(Request $request) { $user = JWTAuth::parseToken()->authenticate(); return response()->json(['result' => $user]); } } 应用: 登录地址: http://blog.app/api/login 传参数email和password,请求及返回结果如下: 根据token获取用户: http://blog.app/api/get_user_details 传参数email和password,请求及返回结果如下:
刷新token请求地址: http://blog.app/api/auth/refresh-token 请求及返回结果如下: 以上请求注意,请求参数是以头信息传递的
返回头信息如下图: