您现在的位置是:首页 >技术交流 >Laravel使用JWT网站首页技术交流
Laravel使用JWT
简介Laravel使用JWT
开始安装jwt
(本次安装不建议直接在项目中安装及使用)
1.composer 安装jwt
composer require tymon/jwt-auth 1.0.0-rc.1
2.在config 文件夹的app.php 中注册服务提供者
'providers' => [
TymonJWTAuthProvidersLaravelServiceProvider::class,
]
'aliases' => [
'JWTAuth'=> TymonJWTAuthFacadesJWTAuth::class,
'JWTFactory'=> TymonJWTAuthFacadesJWTFactory::class,
]
3.生成配置文件
php artisan vendor:publish --provider="TymonJWTAuthProvidersLaravelServiceProvider"
4.生成jwt 密钥
php artisan jwt:secret
然后会在我们的 .env 文件中生成jwt密钥
5.在auth.php 文件中 配置 auth guard 让api的driver使用jwt
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'jwt',//更改此处为jwt
'provider' => 'users',
],
],
6.更改 User model使其支持 jwt-auth
<?php
namespace App;
use TymonJWTAuthContractsJWTSubject;
use IlluminateNotificationsNotifiable;
use IlluminateFoundationAuthUser as Authenticatable;
class User extends Authenticatable implements JWTSubject
{
use Notifiable;
protected $table = 'users';
/**
* 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 [];
}
7.配置 中间件
在 Middleware 文件夹下新建 ApiAuth.php 中间件文件
<?php
namespace AppHttpMiddleware;
use Closure;
use TymonJWTAuthFacadesJWTAuth;
use TymonJWTAuthExceptionsJWTException;
use TymonJWTAuthExceptionsTokenExpiredException;
use TymonJWTAuthExceptionsTokenInvalidException;
class ApiAuth
{
/**
* Handle an incoming request.
*
* @param IlluminateHttpRequest $request
* @param Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
try {
if (! $user = JWTAuth::parseToken()->authenticate()) { //获取到用户数据,并赋值给$user
return response()->json([
'errcode' => 1004,
'errmsg' => '无此用户'
], 404);
}
return $next($request);
} catch (TokenExpiredException $e) {
return response()->json([
'errcode' => 1003,
'errmsg' => 'token 过期' , //token已过期
]);
} catch (TokenInvalidException $e) {
return response()->json([
'errcode' => 1002,
'errmsg' => 'token 无效', //token无效
]);
} catch (JWTException $e) {
return response()->json([
'errcode' => 1001,
'errmsg' => '缺少token' , //token为空
]);
}
}
}
注册中间件 在 Kernel.php 中注册中间件 并设置别名
protected $routeMiddleware = [
'api.auth' => AppHttpMiddlewareApiAuth::class,
];
到此你的jwt就算安装配置完成了
**基本使用**
1.新建AuthCtorller.php 控制器
php artisan make:controller AuthController
2.编辑 测试控制器
<?php
namespace AppHttpControllers;
use AppUser;
use IlluminateHttpRequest;
use TymonJWTAuthFacadesJWTAuth;
use IlluminateSupportFacadesHash;
class AuthController extends Controller
{
/**
* jwt 测试
*/
//登录
public function login(Request $request){
$username = $request->get('username');
$password = $request->get('password');
$user_mes = User::where('username','=',$username)->first();
if (!$user_mes || !Hash::check($password, $user_mes->password)) {
return "账号或密码错误";
}
$token=JWTAuth::fromUser($user_mes);//生成token
if (!$token) {
return "登录失败,请重试";
}
return response()->json(['token'=>$token]);
}
//获取用户信息
public function home(){
$user=JWTAuth::parseToken()->touser();//获取用户信息
return $user;
}
//退出
public function logout(){
JWTAuth::parseToken()->invalidate();//退出
return '退出成功';
}
}
3.编辑路由
<?php
Route::post('/login','AuthController@login');//登录
Route::group(['middleware' => 'api.auth'], function () {
Route::post('/home','AuthController@home');//获取用户信息
Route::post('/logout','AuthController@logout');//退出
});
配置JWT过期时间
config/jwt.php
token过期刷新
public function refresh()
{
try {
// 获取旧token
$old_token = JWTAuth::getToken();
// 刷新token
$token = JWTAuth::refresh($old_token);
// 使老的token无效
JWTAuth::invalidate($old_token);
return response()->json([
'token' => $token,
]);
} catch (JWTException $JWTException) {
// 如果捕获到此异常,即代表 refresh 也过期了,用户无法刷新令牌,需要重新登录。
throw new UnauthorizedHttpException('jwt-auth', $JWTException->getMessage());
}
}
风语者!平时喜欢研究各种技术,目前在从事后端开发工作,热爱生活、热爱工作。