1

Inside my MVC Core app i am getting the user to sign into Azure through the below configuration

public void Configure(string name, OpenIdConnectOptions options) {
                options.ClientId = _azureOptions.ClientId;
                options.Authority = _azureOptions.Authority;
                options.UseTokenLifetime = true;
                options.CallbackPath = _azureOptions.CallbackPath;
                options.RequireHttpsMetadata = false;
                options.ClientSecret = _azureOptions.ClientSecret;
                options.Resource = "https://graph.microsoft.com"; // AAD graph
                options.SaveTokens = true;
                // Without overriding the response type (which by default is id_token), the OnAuthorizationCodeReceived event is not called.
                // but instead OnTokenValidated event is called. Here we request both so that OnTokenValidated is called first which 
                // ensures that context.Principal has a non-null value when OnAuthorizeationCodeReceived is called
                options.ResponseType = "id_token code";

                // Subscribing to the OIDC events
                options.Events.OnAuthorizationCodeReceived = OnAuthorizationCodeReceived;
                //options.Events.OnAuthenticationFailed = OnAuthenticationFailed;
            }

Then once i have got the bearer token from Azure through the AcquireTokenByAuthorizationCodeAsync method, i then send off that bearer token into my Web API which returns another bearer token which will then be used within the MVC app as authentication for future calls into the Web API.

My questions is, how do i save this second bearer token as a cookie so i can send it on every request to the API or is there a better way to do it?

bobby
  • 183
  • 9

1 Answers1

0

There are two patterns for client-side storage of bearer tokens: cookies and using HTML5 local storage.

If cookies are being used to transmit the bearer token from client to server, then cookies would also be used to store the bearer token on the client side.

Likewise, if the authorization header is used to transmit the token, then HTML5 local storage (or session storage) would have to be used to store the bearer token.

You could refer to this SO thread to store Bearer Token in MVC, the code section.

public class Startup
{
    public void Configuration(IAppBuilder app)
    {
        app.UseCookieAuthentication(new CookieAuthenticationOptions()
        {
            AuthenticationType = "ApplicationCookie",
            LoginPath = new PathString("/Account/Login"),
        });
    }
}
Joey Cai
  • 18,968
  • 1
  • 20
  • 30