我觉得我已经阅读了 Stack Overflow 上的每一篇文章,但没有任何内容符合我的情况。我有一个 ASP.NET Core 网站,它使用 Microsoft Identity Platform 进行身份验证。这是通过调用来设置的:
services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApp(options => ...)
然后,我使用基于角色的声明来授权谁可以访问该网站。当用户进行身份验证时,我用他们所属的安全组填充他们的角色(使用图表来查找组成员身份)。
这是完整的身份验证块:
// Setup Graph and authentication
private static void ConfigureAuthentication(
IServiceCollection services,
ConfigurationManager configuration)
{
var initialScopes =
configuration["DownstreamApi:Scopes"]?.Split(' ') ??
configuration["MicrosoftGraph:Scopes"]?.Split(' ');
services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApp(options =>
{
configuration.Bind("AzureAd", options);
options.TokenValidationParameters.RoleClaimType = "groups";
options.AccessDeniedPath = "/Error/AccessDenied";
options.ErrorPath = "/Error/Error";
options.Events.OnTokenValidated = async context =>
{
if(context != null)
{
var allGroupIds = GetConfigurationGroups(configuration);
await ClaimHelpers.PopulateGroupClaims(context, allGroupIds);
}
};
})
.EnableTokenAcquisitionToCallDownstreamApi(options =>
configuration.Bind("AzureAd", options), initialScopes)
.AddMicrosoftGraph(configuration.GetSection("MicrosoftGraph"))
.AddInMemoryTokenCaches();
services.AddControllersWithViews().AddMicrosoftIdentityUI();
}
// Populate the authorization policies and set the default.
private static void ConfigureGroupAuthorization(
IServiceCollection services,
ConfigurationManager configuration)
{
services.AddAuthorization(p =>
{
p.AddPolicy(PolicyNames.PortalUser, policy =>
{
policy.RequireAuthenticatedUser();
policy.RequireRole(configuration["Groups:PortalUserGroupID"]!);
});
});
services.AddAuthorization(options =>
{
options.FallbackPolicy = options.GetPolicy(PolicyNames.PortalUser);
options.DefaultPolicy = options.GetPolicy(PolicyNames.PortalUser)!;
});
}
一切正常,除非有人没有正确的主张。然后,他们被重定向到
https://localhost:44321/MicrosoftIdentity/Account/AccessDenied?ReturnUrl=%2F
。
这不是我想要的。我希望未经授权的用户能够定向我的自定义
/Error/AccessDenied
操作。我不希望他们定向到默认的 Microsoft Identity 回调。
我需要告诉我的用户,如果他们无法访问该页面,他们需要加入哪个安全组。我需要更改或配置哪些内容才能将用户定向到
/Error/AccessDenied
而不是 Microsoft Identity?我需要在我的 Azure 应用程序注册中更改某些内容吗?
如果我的术语有错误,请纠正。我还在学习 ASP.NET Core。
我读过很多类似的帖子。
这可能是最相似的帖子,但没有实现重定向:How to override default Identity AccessDenied route in ASP.NET CORE MVC
咨询了我们的高级工程师,他对这个问题并不熟悉。 尝试询问 ChatGPT。
AddMicrosoftIdentityWebApp
实际上是使用cookie方案,您可以如下配置访问拒绝路径...
...
services.Configure<CookieAuthenticationOptions>(CookieAuthenticationDefaults.AuthenticationScheme, options =>
{
options.AccessDeniedPath = new PathString("/Error/AccessDenied");
});
...