lundi 9 septembre 2019

Why Auth::user() still use old data on the first request?

I'm on Laravel 5.8, PHP 7.2. For authentication process my application is talking an Auth Server that will give me :

  • refreshToken
  • accessToken

Every 30 mins, I require to call the Auth endpoint with my refreshToken to request for new accessToken. After I got the 200 ok, I will then update my users table accordingly.


Testing

By refreshing page when session time-out, I shall do :

  • call /refreshToken API
  • if 200 success, update the current user record with updated accessToken from the API
  • use that updated accessToken from Auth::user()->accessToken to make any future API calls

Result

I keep getting the crash on the first refresh.

I did a var_dump() to investigate further, the reason behind that crash is that my first request still using the old accessToken. I have no idea why and how on earth that this happen, but it is.

Any hints on how I should debug this further ?


Code

public static function reAuthenticate($result) {

    if ($result['http_code'] == 401){

        $refreshToken = Auth::user()->refreshToken;

        //reAuth the accessToken with refreshToken
        $header = [
            'headers' => [
                'Content-Type' => 'application/json',
                'Authorization' => 'Bearer '.$refreshToken
            ]
        ];

        $url    = 'http://'.env('CONTROLLER_IP').':'.env('CONTROLLER_PORT').'/boss/controller/v1/account/refreshToken';
        $refreshTokenResult = HTTP::get($url,$header);

        // dd($refreshTokenResult);

        if ($refreshTokenResult['http_code'] == 200){

            $user = User::where('uuid',$refreshTokenResult['uuid'])->first();
            $user->accessToken  = $refreshTokenResult['access_token'];
            $user->save();

            Auth::setUser($user);

        } else {

            $user = User::where('uuid',$result['uuid'])->first();
            $user->delete();
            Session::flush();
            Auth::logout();

            return Redirect::to(env('APP_URL').'/')->with('success', 'Session Time Out.');

        }

    }


}



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire