在使用 Entra ID 身份验证的 ASP.net Web 应用程序中使用令牌而不是 cookie

问题描述 投票:0回答:1

我有一个

.NET 8
Web 应用程序,它使用
Microsoft Entra ID
对用户进行身份验证。

我需要将此应用程序从使用 cookie 迁移到使用某种基于令牌的方法(JWT 或其他类似新的 .NET 8 不记名令牌的方法,令牌的类型并不重要,重要的是我需要避免使用cookie)。

我在网上搜索了一下,但找不到关于如何做到这一点的像样的教程。有很多解释如何使用基于令牌的身份验证,但它们都使用用户数据库并手动调用

.SignIn()
方法来处理身份验证,而我需要实现 Azure Id / Entra ID 身份验证流程,用户在其中获取重定向到 Microsoft/SSO 登录页面,登录后重定向回我的网络应用程序。

目前,这是我使用 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;
});

有人可以分享一些关于如何将其转移到基于令牌的方法的指导吗?

c# asp.net-core authentication bearer-token .net-8.0
1个回答
0
投票

您可以使用

Microsoft.Identity.Web.UI
来实现身份验证并获取令牌: 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();

并且这里有相关代码示例,可以直接参考: https://learn.microsoft.com/en-us/entra/identity-platform/sample-v2-code?tabs=apptype#web-applications

© www.soinside.com 2019 - 2024. All rights reserved.