[AllowAnonymous]
public class AccountController : Controller
{
public IActionResult SignIn(string? policy)
{
var properties = new AuthenticationProperties
{
RedirectUri = this.Url.Content("~/"),
};
// in this example we're allowing the policy name to be passed in as a parameter to the action, but this would be replaced by your custom policy selection logic
if (!string.IsNullOrWhiteSpace(policy))
{
properties.Items["policy"] = policy;
// HACK: Microsoft.Identity.Web removes the policy item as part of the redirect to IdP but we need to update the token URL when using code flow, so fix that...
properties.Items["customPolicy"] = policy;
}
return this.Challenge(properties, OpenIdConnectDefaults.AuthenticationScheme);
}
}
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApp(opt =>
{
// other setup here...
opt.Events.OnAuthorizationCodeReceived += ctx =>
{
if (ctx.Properties?.Items.TryGetValue("customPolicy", out var customPolicy) == true)
{
ctx.TokenEndpointRequest.TokenEndpoint = $"{opt.Instance}/{opt.Domain}/{customPolicy}/oauth2/v2.0/token";
}
return Task.CompletedTask;
};
},
opt =>
{
// this should be the actual URL, not just the controller and action name
opt.LoginPath = "/Account/SignIn";
opt.Cookie.SameSite = SameSiteMode.None;
opt.Cookie.SecurePolicy = CookieSecurePolicy.Always;
opt.Cookie.IsEssential = true;
});
1条答案
按热度按时间pengsaosao1#
是的,假设您使用的是Microsoft.Identity.Web,那么您的登录链接将不会转到
/MicrosoftIdentity/Account/SignIn
,而是转到您创建的自定义操作,该操作将填充您要使用的策略名称,例如/Account/SignIn
:字符串
通过填充
AuthenticationProperties.Items["policy"]
,Microsoft.Identity.Web在重定向到B2C/authorize
端点时将自动使用该策略名称。但是,如果您正在使用OpenID Connectcode
流(您应该这样做),则需要确保/token
端点也使用正确的策略。Microsoft.Identity.Web在
/authorize
调用之后删除policy
项,因此上面的示例还将策略名称设置为customPolicy
,以便在需要交换令牌时可用。只需更新Startup.cs
中的Microsoft.Identity.Web配置,即可处理OnAuthorizationCodeReceived
事件:型
如果你想让
[Authorize]
正常工作,你还需要更改默认的身份验证方案,以便它检查你的cookie并更新cookie配置,使用你的自定义登录URL而不是默认的Microsoft.Identity.Web URL:型