从AddAzureADB2C迁移到Microsoft.Identity.Web后的认证链接问题
我有一个API,在纯手写HTML页面(无Razor页面、ASP页面)上设置了简单的“登录”链接。登录后会存储Cookie,方便直接使用Swagger UI进行API调用,这对测试和开发非常有用。
该API使用Azure AD-B2C进行身份验证。
我遵循微软文档指引,将原有代码:
.AddAzureADB2C(AzureADB2CDefaults.AuthenticationScheme, "AzureADB2COpenID", "AzureADB2CCookie", AzureADB2CDefaults.AuthenticationScheme, options => { StartupValidator.B2cConfiguration.Bind(options); });
替换为新代码:
services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme) .AddMicrosoftIdentityWebApp(options => { StartupValidator.B2cConfiguration.Bind(options); });
代码编译运行正常,但原HTML页面中硬编码的登录链接:
<a href='/AzureADB2C/Account/SignIn/AzureADB2C'>Sign-in</a> |
已无法正常触发认证重定向。我的问题是:新配置下的登录URL是什么?该页面仅用于开发调试,不想引入Razor页面等依赖,能否实现?
更新于2023年5月24日美国东部时间上午10:39:14
通过引入Microsoft.Identity.Web.UI并调用services.AddRazorPages().AddMicrosoftIdentityUI(),可通过/MicrosoftIdentity/Account/SignIn登录,但此方案引入大量Razor和UI依赖,大幅增加容器体积,有没有无需引入这些组件的方法?
一、新配置下的默认登录URL说明
使用AddMicrosoftIdentityWebApp且未引入Microsoft.Identity.Web.UI时,没有现成的默认登录端点。旧版AzureADB2C中间件提供的/AzureADB2C/Account/SignIn/AzureADB2C端点,在新版Microsoft.Identity.Web中不再默认提供。
二、不引入Razor依赖的实现方案
你可以手动创建极简的登录/登出端点,完全不依赖额外UI组件,步骤如下:
添加自定义认证控制器
创建一个基础API控制器,专门触发Azure AD B2C的认证流程:using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.Authentication.OpenIdConnect; using Microsoft.AspNetCore.Mvc; [ApiController] [Route("auth")] public class AuthController : ControllerBase { // 触发登录流程,重定向到Azure AD B2C认证页 [HttpGet("signin")] public IActionResult SignIn() { return Challenge( new AuthenticationProperties { RedirectUri = "/" }, OpenIdConnectDefaults.AuthenticationScheme); } // 触发登出流程,清除Cookie并跳转回主页 [HttpGet("signout")] public IActionResult SignOut() { return SignOut( new AuthenticationProperties { RedirectUri = "/" }, CookieAuthenticationDefaults.AuthenticationScheme, OpenIdConnectDefaults.AuthenticationScheme); } }更新HTML页面的链接
将原登录链接替换为自定义端点:<a href='/auth/signin'>Sign-in</a> | <a href='/auth/signout'>Sign-out</a>确认认证配置完整性
确保AddMicrosoftIdentityWebApp的配置已正确绑定Azure AD B2C的核心参数(租户ID、客户端ID、用户流/政策名称等),保证Challenge方法能正确重定向到B2C认证页面。
这种方案仅依赖ASP.NET Core基础认证组件,不会引入任何Razor或UI相关依赖,既能满足开发调试的登录需求,又能避免容器体积膨胀。
内容的提问来源于stack exchange,提问作者David Dombrowsky

