Search code examples
c#asp.net-coreauthenticationbearer-token.net-8.0

Using a token instead of a cookie in an ASP.net web app that uses Entra ID authentication


I have a .NET 8 web application that uses Microsoft Entra ID to authenticate users.

I have a requirement to migrate this app from using cookies to using some kind of token-based approach (JWT or something else like the new .NET 8 bearer token, the type of token doesn't really matter, what matters is that I need to avoid using cookies).

I've been searching online a bit, but I couldn't find a decent tutorial on how to do this. There are plenty that explain how to use token-based authentication, but they all use a user database and manually invoke the .SignIn() method to handle authentication, while I need to implement the Azure Id / Entra ID authentication flow, where the user gets redirected to the Microsoft/SSO login page and once logged in is redirected back to my web app.

At the moment, this is my authentication setup that uses a cookie:

services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApp(options =>
{
    options.Instance = appSettings.AzIdInstance;
    options.Domain = appSettings.AzIdDomain;
    options.TenantId = appSettings.AzIdTenantId;
    options.ClientId = appSettings.AzIdClientId;
    options.CallbackPath = appSettings.AzIdCallbackPath;
    options.SignedOutCallbackPath = appSettings.AzIdSignOutCallbackPath;
    options.NonceCookie.Name = "myAppNonceCookieName";
    options.NonceCookie.SameSite = SameSiteMode.None;
    options.CorrelationCookie.Name = "myAppCorrelationCookieName";
    options.CorrelationCookie.SameSite = SameSiteMode.None;
});

Can someone share some pointers on how to move this over to a token-based approach?


Solution

  • You can use the Microsoft.Identity.Web.UI to Implement authentication and acquire tokens: https://learn.microsoft.com/en-us/entra/identity-platform/tutorial-web-app-dotnet-sign-in-users?tabs=visual-studio#implement-authentication-and-acquire-tokens.

    builder.Services.AddMicrosoftIdentityWebAppAuthentication(builder.Configuration, "AzureAd")
        .EnableTokenAcquisitionToCallDownstreamApi(initialScopes)
            .AddDownstreamApi("DownstreamApi", builder.Configuration.GetSection("DownstreamApi"))
            .AddInMemoryTokenCaches();
    

    And there are relevant code examples here that you can refer to directly: https://learn.microsoft.com/en-us/entra/identity-platform/sample-v2-code?tabs=apptype#web-applications