Search code examples
asp.netjwtauthorizationbearer-tokencookie-httponly

Jwt priority HttpOnly Cookie versus Authorisation bearer


I have a backend in Asp.net Core that handle authorization with jwt tokens.

This backend may interact with differents clients.

  • To some of them (browser, compliant lib... ) it will send a secure httpOnly cookie to hold the token.
  • To others (specific clients requests) it will send them the jwt as response and rely on the client to set the Authorization Bearer {AccessToken} on following queries

Everything is working fine.

My question is :

=> What should happens if I receive BOTH Authorization Bearer {AccessToken} and httpOnly cookie token ?

Is there any kind of priority? I have assumed that the explicit Authorization Bearer {AccessToken} has higher priority but I wonder if I am right.

As far as I know, I could have only one context.Token so I have to pick one. Am I right?


Solution

  • You're on the right track. When both the Authorization Bearer {AccessToken} header and the HTTP-only cookie token are present, it's generally best practice to prioritize the Authorization header. This is because it's explicitly set by the client and typically indicates the client's intended token.

    Here's why:

    1. The Authorization header is more explicit. The client deliberately sends this token for authentication, so it should take precedence.

    2. Relying solely on the cookie could expose you to certain CSRF attacks. Since the Authorization header is not automatically sent by browsers, it's less likely to be involved in such attacks.

    3. You're correct that typically there is only one context token. Prioritizing the Authorization header simplifies your token handling logic.

    So yes, prioritize the Authorization Bearer {AccessToken} over the cookie token. If the header is present, use that token for authentication. If it's absent, then fall back to the cookie.

    Here’s a concise way to implement this in your code:

    var token = context.Request.Headers["Authorization"].FirstOrDefault()?.Split(" ").Last();
    if (string.IsNullOrEmpty(token))
    {
        token = context.Request.Cookies["YourCookieName"];
    }
    
    // Now use the token