智威汤逊/ LARAVEL令牌过期

问题描述 投票:-1回答:1

我开发了一个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);
    }
}
php laravel laravel-5 jwt laravel-5.6
1个回答
2
投票

所以,你正在使用一个Laravel中间件里面设置标题正常的PHP方法,就是行不通的。

你应该检查了这一点:qazxsw POI

https://github.com/tymondesigns/jwt-auth/blob/develop/src/Http/Middleware/BaseMiddleware.php

基本上,变动:

https://github.com/tymondesigns/jwt-auth/blob/develop/src/Http/Middleware/RefreshToken.php

header('Authorization: Bearer ' . $refreshed);

事情是下面的,符合市场预期,因为该请求已经throught您的应用程序后,这种“后中间件”的被执行这种方法是行不通的。所以:

  1. 用户与已过期的令牌请求
  2. 该应用程序将返回一个403或401(记不清了),因为TokenExpired的。
  3. 然而,响应将包含新令牌的头
  4. 你与新的令牌相同的请求,它应该工作。
© www.soinside.com 2019 - 2024. All rights reserved.