0

Im using Laravel Passport and I'm trying to convert my code from using tokens stored in the localhost to using httponly cookies.

I followed this documentation: https://laravel.com/docs/5.8/passport#consuming-your-api-with-javascript , and added this to my Kernel.php:

'web' => [ // Other middleware... \Laravel\Passport\Http\Middleware\CreateFreshApiToken::class, ],

This is my Login function in my AuthController:

public function login(Request $request) {
    if(Auth::attempt(['email' => $request->email, 'password' => $request->password])){
        $user = Auth::user();
        $token = $user->createToken('API')->accessToken;
        
        return response()->json(['user' => $user], 200)->withCookie(
            'X-Secure-Token', 
            $token,
            null,
            null,
            null,
            false,
            true
        );
    } else {
        return response()->json(['message' => 'Unauthorized'], 401);
    }
}

I'm successfully seeing the 'X-Secure-Token' in my Postman environment after I use the login route. But when I try to access in Postman the other routes protected by the 'auth:api' middleware, I am still returned with the Unauthenticated message. In the Authorization header of the request, I set the Auth Type to "No Auth".

I'm fairly a beginner in API creation. What should I do to make my authentication system work with httponly cookie in Postman?

1 Answer 1

0

The auth:api middleware expects the token in the Authorization header,But you are sending it in http-only cookie so you need a custom middleware to check the token from HTTP-only cookies instead.

Route::middleware('auth.cookie')->get('/user', function (Request $request) {
    return $request->user();
});

But I wouldn't suggeast this approch an important issue when using only HTTP cookies for API authentication is to limit cross-platform compatibility.

The APIs that use cookies are entirely dependent on the state of the client, which can be an issue for mobile applications and other non-web clients. These clients do not handle cookies as well as web browsers.

This state dependency contrasts the approach of stateless APIs, making it difficult to maintain consistent and secure authentication across platforms, If you use a stateless approach such as token-based authentication, it will be much secure and also cross-platform compact-able

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.