user3167162
user3167162

Reputation: 495

How to store JWT Token in authorization header in Aspnet Core

I have an "Auth Service" application in .Net Core which authenticates via a Challenge Request and then redirects back to the client application with a token.

    [AllowAnonymous]
    [HttpGet("Login")]
    public IActionResult Login()
    {
        return Challenge(new AuthenticationProperties
        {
            RedirectUri = returnUrlQs
        }, OpenIdConnectDefaults.AuthenticationScheme);
    }

Currently I transmit the token through a HTTP cookie using the options.Events.OnAuthorizationCodeReceived OpenId Connect event. However the 4kb cookie length is too small and so I want to try move it to the authorization header.

I've tried setting the Response header but it's not received on the other side; on the client app.

Is this possible to achieve?

Thanks for any help!

Upvotes: 0

Views: 2481

Answers (3)

Tore Nestenius
Tore Nestenius

Reputation: 19931

If you have trouble with the 4Kb limit, then you should put our token on a diet and reduce its size by removing unnecessary claims.

Upvotes: 0

jean
jean

Reputation: 31

Put your token inside the body of response and include [Authorize] attribute. eg:

//in your api
[Authorize]
[HttpPost("update")]
private IActionResult update([FromBody] Model model){
//do some actions here
}

and in your client side, you store your token via session or any temporary storage then retrieve it if necessary and put it in your header. do something like this:

  //in your client
  $.ajax({
  type: "POST",
  url: "/update",
  data: {someParameter: "some value"},
  contentType: "application/json; charset=utf-8",
  Authorization : "Bearer " + yourToken,
  dataType: "json",
  success: function(msg) {
    //some code
  }
});

i did not test this code but only to give you some idea.

Upvotes: 0

juunas
juunas

Reputation: 58823

Setting request headers is the client's job, not the API's. So your back-end can't set those. You'll need to return the token so that code on your front-end can get it and then assign it as a request header on future requests.

Another option here might be to do the OpenID Connect authentication from your front-end application (depending on what your identity provider supports). This way it would get tokens and have the ability to refresh them, and your API could focus on just validating tokens in requests.

Upvotes: 5

Related Questions