我在 .NET 5 Razor Pages 应用程序中使用 Microsoft 外部身份验证,当用户在身份验证期间取消同意提示时遇到问题。对于个人 Microsoft 帐户,该行为按预期工作 - 当用户取消时,他们会成功重定向回登录页面。但是,当工作帐户用户取消时,我收到以下异常:
处理请求时发生未处理的异常。 例外:consent_required;说明=AADSTS65004:用户拒绝同意访问该应用程序。跟踪 ID:88696573-49b5-472b-8db9-40bd03711600 相关 ID:9babdc71-9c05-4910-8f29-c5b3aa6b5cc1 时间戳:2024-10-14 06:05:38Z;Uri=https://login.microsoftonline.com/error ?代码=65004 未知地点
异常:处理远程登录时遇到错误。** Microsoft.AspNetCore.Authentication.RemoteAuthenticationHandler
.HandleRequestAsync()**
public static class MicrosoftAuthExtension
{
public static void AddMicrosoftAuth(this IServiceCollection services, IConfiguration configuration)
{
services.AddAuthentication()
.AddMicrosoftAccount(options =>
{
IConfigurationSection microsoftAuthNSection = configuration.GetSection("Authentication:Microsoft");
options.ClientId = microsoftAuthNSection["ClientId"];
options.ClientSecret = microsoftAuthNSection["ClientSecret"];
options.CallbackPath = new PathString("/Identity/Account/MicrosoftExternalAccountCallBack");
options.AccessDeniedPath = new PathString("/Identity/Account/Login");
options.SaveTokens = true;
});
}
}
我已设置 options.AccessDeniedPath 以在同意被拒绝时重定向回登录页面。
这对于个人帐户效果很好,但对于工作帐户会引发异常。
有谁知道为什么这种情况只发生在工作帐户上,以及我如何为个人和工作帐户优雅地处理这个问题?任何帮助将不胜感激!
OnRemoteFailure
。
这是示例代码
services.AddAuthentication().AddMicrosoftAccount(options =>
{
IConfigurationSection microsoftAuthNSection = configuration.GetSection("Authentication:Microsoft");
options.ClientId = microsoftAuthNSection["ClientId"];
options.ClientSecret = microsoftAuthNSection["ClientSecret"];
options.CallbackPath = new PathString("/Identity/Account/MicrosoftExternalAccountCallBack");
options.AccessDeniedPath = new PathString("/Identity/Account/Login");
options.SaveTokens = true;
options.Events = new Microsoft.AspNetCore.Authentication.OAuth.OAuthEvents
{
OnRemoteFailure = context =>
{
if (context.Request.Query["error"] == "consent_required")
{
context.Response.Redirect("/Identity/Account/Login?error=consent_declined");
context.HandleResponse();
return Task.CompletedTask;
}
context.Response.Redirect("/Identity/Account/Login?error=unexpected_error");
context.HandleResponse();
return Task.CompletedTask;
}
};
});