如何为Azure AD登录链接添加额外参数修改登录功能
实现方案
你可以通过两种方式在现有基于OWIN的Microsoft身份认证流程中添加prompt=login参数,根据业务需求选择即可:
- 全局强制配置:所有发起的登录请求默认携带该参数
在Startup类的OpenIdConnectAuthenticationOptions配置中新增RedirectToIdentityProvider通知逻辑,在向微软身份平台发起授权请求前注入参数即可,修改后的OpenID Connect中间件配置如下:
app.UseOpenIdConnectAuthentication( new OpenIdConnectAuthenticationOptions { ClientId = appId, Authority = authority, RedirectUri = redirectUri, TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true }, Notifications = new OpenIdConnectAuthenticationNotifications { AuthenticationFailed = OnAuthenticationFailedAsync, AuthorizationCodeReceived = OnAuthorizationCodeReceivedAsync, // 新增以下通知逻辑 RedirectToIdentityProvider = notification => { // 仅在构造授权请求时追加参数,避免回调、令牌刷新等其他流程误携带参数 if (notification.ProtocolMessage.RequestType == OpenIdConnectRequestType.Authentication) { notification.ProtocolMessage.Prompt = "login"; } return Task.FromResult(0); } } } );
- 按需触发配置:仅在用户主动点击登录按钮时强制重新登录,不做全局生效
如果不需要对所有登录场景强制要求输入凭据,不需要修改全局中间件配置,在控制器中构造登录挑战(Authentication Challenge)时传入参数即可,示例代码:
public ActionResult Login() { var authenticationProperties = new AuthenticationProperties { RedirectUri = Url.Action("Index", "Home") }; // 传入prompt=login参数 authenticationProperties.Dictionary["prompt"] = "login"; HttpContext.GetOwinContext().Authentication.Challenge( authenticationProperties, OpenIdConnectAuthenticationDefaults.AuthenticationType ); return new HttpUnauthorizedResult(); }
补充说明:你当前代码中在
OnAuthorizationCodeReceivedAsync里调用idClient.RemoveAsync(account)只会清除MSAL本地的账户缓存,无法绕过Azure AD本身的会话单点登录逻辑,因此必须通过prompt=login参数告知身份平台忽略现有会话,强制用户重新输入凭据完成登录。
其他常用的prompt参数可选值:
none:不弹出任何交互界面,若不存在有效登录会话直接返回错误consent:强制弹出授权同意页面,即使用户之前已经完成过授权select_account:强制弹出账户选择界面,不会自动使用当前会话中的唯一账户登录
内容的提问来源于stack exchange,提问作者Psychonaut007
相关产品推荐
相关产品推荐

