is it right to revoke, invalidate, delete or auth logout for making the user logout in a guarded passport api

Viewed 438

If i login to my external app via passport as shown in many tutorial:

public function login(Request $request)
{ 
    $data=$request->all();
    $validator = Validator::make($data, [
        'email' => 'email|required',
        'password' => 'required'
        
    ]);

    if($validator->fails()){
        return response()->json(['error' => $validator->errors(), 'Validation Error',400]);
    }

    if (!auth()->attempt($data)) {
        return response(['message' => 'Invalid Credentials'],400);
    }

    $accessToken = auth()->user()->createToken('authToken')->accessToken;
    return response()->json(['user' => auth()->user(), 'access_token' => $accessToken], 200);

}

I've read lots of post, howto and seen some video, but there is not a clear procedure to logout an user in this scenario, and laravel's manual do not said anything about it ( why? or where is it).

I found as possible solutions:

  • auth()->user()->token()->revoke();
  • $request->user()->token()->revoke();
  • auth()->logout();
  • $request->session()->invalidate();

Which of these performs the rights step for logout? My method should looks something like:

 public function logout(Request $request) {
        //auth()->user()->token()->revoke();
        //$request->user()->token()->revoke();
       // auth()->logout();
        //$request->session()->invalidate();

        return response()->json(['message' => 'User successfully signed out'], 200);
    }

and the routhe should be:

Route::post('/logout', [AuthController::class, 'logout'])->middleware('auth:api');

or I wrong???

Even how to not redirect to login route if an user is not authenticated to see a resource? If im send back:

class Authenticate extends Middleware
{
    /**
     * Get the path the user should be redirected to when they are not authenticated.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return string|null
     */
    protected function redirectTo($request)
    {
        if (! $request->expectsJson()) {
            response()->json(['mex'=>'not authorized'], 401);
        }
    }
}

not works and send me back an error:

ErrorException: Header may not contain more than a single header, new line detected in file ...../vendor/symfony/http-foundation/Response.php on line 359

1 Answers

Logout Also, check you have the "oauth_access_tokens" table in your database if you have used a passport it will be there.

public function logout(Request $request) {
        
    DB::table('oauth_access_tokens')->where('user_id', Auth::id())->delete();
    
    
    return response()->json(['message' => 'User successfully signed out'], 200);
 }

and the route should be:-

 Route::group('middleware'=>['auth:api'], function(){
    
    Route::post('logout', [AuthController::class, 'logout'])->name('logout');
});

If a user is not authenticated:-

Add Below code to App\Exceptions\Handler.php

use Illuminate\Auth\AuthenticationException;
use Illuminate\Support\Facades\Auth;

/**
     * Convert an authentication exception into an unauthenticated response.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Illuminate\Auth\AuthenticationException  $exception
     * @return \Illuminate\Http\Response
     */
    protected function unauthenticated($request, AuthenticationException $exception)
    {
        $current_gaurd = array_get($exception->guards(), 0);
        $route = route('login');

        // if ($current_gaurd == 'admin') {
           // $route = route('admin.login');
        //}

        return $request->expectsJson()
        ? response()->json(['meta' => ['messsage' => $exception->getMessage()]], 401)
        : redirect()->guest($route);
    }

Also, Place all route inside the middleware AUTH group for the user is not authenticated

Hope this will be helpful to you.

Related