.Net Core 5.0 身份脚手架代码不适用于 Windows 身份验证

.Net Core 5.0 Identity Scaffolded Code not working with Windows Authentication

我有一个 .net Core 5.0 MVC 应用程序,目前正在使用 Windows 身份验证。我想向应用程序添加角色,因此决定使用 Identity 框架,然后复制站点的用户并基本上为他们分配本地角色。

这被证明是非常棘手的,我最终得到了一个半途而废的解决方案,我有一个使用 Windows 身份验证的可见身份验证用户,我可以使用它通过 UserManager 访问用户和角色表和角色管理器。但是,方法装饰不适用于我的本地角色,并且重定向到 Areas 文件夹中的 AccessDenied 等文件也不起作用。 所以

var identityUser = _userManager.FindByNameAsync(User.Identity.Name).Result;
        var roles = _userManager.GetRolesAsync(identityUser).Result;
        var isAdmin = _userManager.IsInRoleAsync(identityUser, "Admin").Result;
        if (isAdmin)
            return Forbid();

懂我

No webpage was found for the web address: https://localhost:44312/Account/AccessDenied?ReturnUrl=%2FHome

这是在 IdentityHostingStartup.cs

中创建的脚手架代码
public class IdentityHostingStartup : IHostingStartup
{
    public void Configure(IWebHostBuilder builder)
    {
        builder.ConfigureServices((context, services) => {
            services.AddDbContext<IdentityContext>(options =>
                options.UseSqlServer(
                    context.Configuration.GetConnectionString("YWAFTraceConnection")));

            services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = false)
                .AddRoles<IdentityRole>()
                .AddEntityFrameworkStores<IdentityContext>()
                .AddDefaultUI();

            services.AddAuthorization(options =>
            {
                options.FallbackPolicy = new AuthorizationPolicyBuilder()
                    .RequireAuthenticatedUser()
                    .Build();
            });

            services.ConfigureApplicationCookie(options =>
            {
                options.AccessDeniedPath = new Microsoft.AspNetCore.Http.PathString("/Account/AccessDenied");                    
            });
        });
    }

AccessDeniedPath 的路径条目组合似乎不起作用 - 我得到的只是一个 404 - 我可以解决缺少装饰工作但确实需要访问被拒绝页面才能触发。

这是我的区域文件夹的结构

[![区域文件夹结构][1]][1]

它在本地使用 IIS Express 或在 IIS 上部署时都不起作用

Startup.cs 中的 app.UseEndpoints 中添加 endpoints.MapRazorPages(); 解决了找不到区域页面的问题。

按照优秀教程 here

中所述,通过实施自定义策略修复了控制器和方法身份验证