Я разработал API, и у меня проблема с истечением срока действия токена, и я пытаюсь найти способы обновить токены, отправленные API, и ничего не нашел Это мой пользователь mdoal:
<?php
namespace App;
use Tymon\JWTAuth\Contracts\JWTSubject;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable implements JWTSubject
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'email', 'password','username','lastname','tel','tel',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
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 [];
}
}
и это мой loginController
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Http\Controllers\Controller;
use App\User;
use JWTFactory;
use JWTAuth;
use Validator;
class APILoginController extends Controller
{
//
public function login( Request $request){
$validator = Validator::make($request -> all(),[
'email' => 'required|string|email|max:255',
'password'=> 'required'
]);
if ($validator -> fails()) {
# code...
return response()->json($validator->errors());
}
$credentials = $request->all('email','password');
try{
if (! $token = JWTAuth::attempt( $credentials) ) {
# code...
return response()->json( ['error'=> 'invalid username and password'],401);
}
}catch(JWTException $e){
return response()->json( ['error'=> 'could not create token'],500);
}
$currentUser = Auth::user();
return response()->json( ['user'=> $currentUser,'token'=>compact('token')],200);
///return response()->json( compact('token'));
}
}
, и я нашел в github решение для создания пользовательского промежуточного программного обеспечения. Когда срок действия токена истекает, обновленный токен добавляется в заголовки ответа.Приложению просто необходимо выполнить поиск, если ответ есть, и обновить обновленный токен.
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
class RedirectIfAuthenticated
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @param string|null $guard
* @return mixed
*/
public function handle($request, Closure $next)
{
try
{
if (! $user = JWTAuth::parseToken()->authenticate() )
{
return response()->json([
'code' => 101, // means auth error in the api,
'response' => null // nothing to show
]);
}
}
catch (TokenExpiredException $e)
{
// If the token is expired, then it will be refreshed and added to the headers
try
{
$refreshed = JWTAuth::refresh(JWTAuth::getToken());
$user = JWTAuth::setToken($refreshed)->toUser();
header('Authorization: Bearer ' . $refreshed);
}
catch (JWTException $e)
{
return response()->json([
'code' => 103, // means not refreshable
'response' => null // nothing to show
]);
}
}
catch (JWTException $e)
{
return response()->json([
'code' => 101 ,//, means auth error in the api,
'response' => null // nothing to show
]);
}
// Login the user instance for global usage
Auth::login($user, false);
return $next($request);
}
}