简体   繁体   中英

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!

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.

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.

如果您对 4Kb 的限制有疑问,那么您应该节食我们的令牌并通过删除不必要的声明来减小其大小。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM