我正在使用Tymon的jwtAuth
package处理从我的laravel后端到vue
spa前端的Auth,我正在创建AuthController,我从文档中获取了很多内容,只是进行了调整满足我的需求。从登录到注销以及令牌过期,一切工作都很好。
问题是我确实看到该控制器上有一个令牌刷新功能,如果我的猜测正确,它将刷新客户端已经拥有的当前令牌。但是该怎么做呢?如何在前端处理该刷新令牌?由于非常令人讨厌的是每60分钟(默认情况下为令牌生存期),它将抛出401。
我想要的可能是每次用户请求后端时,它将刷新令牌或增加令牌的生存期。因此,令牌只有在用户闲置整整60分钟后才会过期。
我们能做到吗?这是最佳做法吗?在整个jwt
和令牌方面,我还是一个新手,过去,我只依靠laravel令牌过期,因为我不使用spa,但是刀片前端非常有用,因此基本上不需要搞乱laravel验证用户身份的方式。
有关添加的信息,这里是我认为与整个身份验证有关的每个文件。
这是我的授权控制器
<?php
namespace App\Http\Controllers;
use DB;
use Hash;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Input;
use App\Http\Controllers\Controller;
use App\User;
use Response;
class Authcontroller extends Controller
{
/**
* Create a new AuthController instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('auth:api', ['except' => ['login']]);
}
/**
* Get a JWT via given credentials.
*
* @return \Illuminate\Http\JsonResponse
*/
public function login()
{
$credentials = request(['username', 'password']);
if (! $token = auth('api')->attempt($credentials)) {
return response()->json(['error' => 'Unauthorized'], 401);
}
return $this->respondWithToken($token);
}
/**
* Get the authenticated User.
*
* @return \Illuminate\Http\JsonResponse
*/
public function me()
{
return response()->json(auth('api')->user());
}
/**
* Log the user out (Invalidate the token).
*
* @return \Illuminate\Http\JsonResponse
*/
public function logout()
{
auth('api')->logout();
return response()->json(['message' => 'Successfully logged out']);
}
/**
* Refresh a token.
*
* @return \Illuminate\Http\JsonResponse
*/
public function refresh()
{
return $this->respondWithToken(auth('api')->refresh());
}
/**
* Get the token array structure.
*
* @param string $token
*
* @return \Illuminate\Http\JsonResponse
*/
protected function respondWithToken($token)
{
$id = auth('api')->user()->getId();
$kelas = User::with('pus','cu')->findOrFail($id);
return response()->json([
'access_token' => $token,
'user' => $kelas,
'token_type' => 'bearer',
'expires_in' => auth('api')->factory()->getTTL() * 60
]);
}
public function guard()
{
return Auth::Guard('api');
}
}
这是我的API路线
Route::group(['prefix' => 'auth'],function($router){
Route::post('/login', 'AuthController@login');
Route::post('/logout', 'AuthController@logout');
Route::post('/refresh', 'AuthController@refresh');
Route::get('/me', 'AuthController@me');
});
这是我的vue general.js
文件中的文件,该文件处理路由并将标头提供给Axios
export function initialize(store, router) {
router.beforeEach((to, from, next) => {
const requiresAuth = to.matched.some(record => record.meta.requiresAuth);
const currentUser = store.state.auth.currentUser;
if(requiresAuth && !currentUser) {
next('/login');
} else if(to.path == '/login' && currentUser) {
next('/');
} else {
next();
}
});
axios.interceptors.response.use(null, (error) => {
if (error.response.status == 401) {
store.dispatch('auth/logout');
router.push('/login');
}
return Promise.reject(error);
});
if (store.state.auth.currentUser) {
setAuthorization(store.state.auth.currentUser.token);
}
}
export function setAuthorization(token) {
axios.defaults.headers.common["Authorization"] = `Bearer ${token}`
}
这里是auth.js
,用于处理登录
import { setAuthorization } from "./general";
export function login(credentials){
return new Promise((res,rej) => {
axios.post('/api/auth/login', credentials)
.then((response) => {
setAuthorization(response.data.access_token);
res(response.data);
})
.catch((err) => {
rej("Username atau password salah");
})
})
}
答案 0 :(得分:0)
您可以调整令牌到期时间(从.env
更改为JWT_TTL
)并刷新时间(JWT_REFRESH_TTL
)以满足您的需要。并检查令牌是否有效和/或需要在中间件中刷新,以便令牌在需要时立即刷新。
关于这是否是一种好习惯,请参阅Laravel项目的JWT_REFRESH_TTL
中对config/jwt.php
的注释。
最适合我的解决方案是使用扩展Tymon\JWTAuth\Http\Middleware\BaseMiddleware
的自定义中间件。样板看起来像这样:
Class TryTokenRefresh extends BaseMiddleware
{
public function handle($request, Closure $next)
{
$newToken = $this->tryRefresh($request);
if ($newToken) {
// in case there's anything further to be done with the token
// we want that code to have a valid one
$request->headers->set('Authorization', 'Bearer ' . $newToken);
}
...
...
$response = $next($request);
...
...
if ($newToken) {
// send new token back to frontend
$response->headers->set('Authorization', $newToken);
}
return $response;
}
// Refresh the token
protected function tryRefresh()
{
try {
$token = $this->auth->parseToken()->refresh();
return $token;
} catch (JWTException $e) {
// token expired? force logout on frontend
throw new AuthenticationException();
}
return null;
}
在前端,这很简单,就像在响应中查找Authorization
标头一样:
// check for the `Authorization` header in each response - refresh on frontend if found
axios.interceptors.response.use((response) => {
let headers = response.headers
// your 401 check here
// token refresh - update client session
if (headers.authorization !== undefined) {
setAuthorization(headers.authorization);
}
return response
})
希望这会有所帮助。