How to logout JWT token using Multi authentication with different table of User

一曲冷凌霜 提交于 2021-01-28 03:20:15

问题


Here is a code in config/auth.php

'guards' => [
    'web' => [
        'driver' => 'session',
        'provider' => 'users',
    ],

    'api' => [
        'driver' => 'jwt',
        'provider' => 'users',
        'hash' => false,
    ],
    'client' => [
        'driver' => 'jwt',
        'provider' => 'clients',
    ]
],

'providers' => [
    'users' => [
        'driver' => 'eloquent',
        'model' => App\User::class,
    ],
    'clients' => [
        'driver' => 'eloquent',
        'model' => App\Client::class,
    ],
],

My login function doesnt have a problem with this code for different login user :

config()->set('auth.defaults.guard', 'client');
Config::set('jwt.user', 'App\Client');
Config::set('auth.providers.clients.model', Client::class);

Here is my logout function :

function logout(Request $request)
{
    $this->validate($request, ['token' => 'required']);
    Config::set('jwt.user', 'App\Client');
    Config::set('auth.providers.clients.model', Client::class);
    try {
        JWTAuth::invalidate(JWTAuth::getToken());
        return response()->json(['success' => true]);
    } catch (JWTException $e) {
        return response()->json(['success' => false, 'error' => 'Failed to logout'], 500);
    }
}

I'm using Laravel 6 and tymon/jwt-auth "1.0.0-rc.5.1"


回答1:


If you have one token table for both user and client then you can do like this...For logout you just have to delete the token from token table... Simple way =>

public function logOut($id) {
        if (Auth::check()) {
            $user = Auth::user();
            Token::where('user_id',$user->id)
                    ->where(external identification)
                    ->delete();
            $response = [
                    'status' => true,
                    'message' => 'Successfully Logged Out',
            ];
            return response()->json($response); //@ sending response
        } else {
            $response = [
                    'status' => false,
                    'message' => 'Bad Request!',
            ];
            return response()->json($response); //@ sending response
        }                     
    }



回答2:


you can make it simpler with with the Auth/laravel

    public function logoutapp(){
      $user = Auth::user();
      $userid =$user->id;
      DB::table('oauth_access_tokens')->where('user_id', $userid)->update(['revoked' => true]);
    return Response::json(array('succes' => true, 'data' => 'Logout succesfully!'), 200);
}


来源:https://stackoverflow.com/questions/61494765/how-to-logout-jwt-token-using-multi-authentication-with-different-table-of-user

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!