首页 > 解决方案 > 带有 Windows 身份验证的 Asp.Net Core 2.1 SPA React 模板

问题描述

当我在调试环境(IIS Express)中使用 Windows 身份验证时,我得到了正确的域名。但是当我将它推送到生产环境(IIS)时,我根本没有得到域名。我错过了什么吗?

重现我的问题:

我使用 React 模板在 VS2017 (15.7.6) 中创建了一个新的 Web 项目,并通过将 launchSettings.json 更改为:

"windowsAuthentication": true,
"anonymousAuthentication": false,

现在我将ConfigureServices方法更改为Startup.cs

public void ConfigureServices(IServiceCollection services) 
{
    services.Configure<IISOptions>(options =>
    {
        options.AutomaticAuthentication = true;
    });
    services.AddAuthentication(IISDefaults.AuthenticationScheme);

    var names = new[] { "peter", "joey" };


    services.AddAuthorization(options =>
    {
        options.AddPolicy("OnlyEmployees", policy =>
        {
            policy.AddAuthenticationSchemes(IISDefaults.AuthenticationScheme);
            policy.Requirements.Add(new CheckForEmployee(names));
        });
    });
    services.AddSingleton<IAuthorizationHandler, CheckForEmployeeHandler>();

    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
    // In production, the React files will be served from this directory
    services.AddSpaStaticFiles(configuration =>
    {
        configuration.RootPath = "ClientApp/build";
    }); 
}

我在项目中添加了 2 个文件:

CheckForEmployee.cs

using Microsoft.AspNetCore.Authorization;

namespace WebServer_WindowsAuthentication
{
    public class CheckForEmployee : IAuthorizationRequirement
    {
        public string[] Names { get; set; }
        public CheckForEmployee(string[] names)
        {
            Names = names;
        }
    }
}

CheckForEmployeeHandler.cs

using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;

namespace WebServer_WindowsAuthentication
{
    public class CheckForEmployeeHandler : AuthorizationHandler<CheckForEmployee>
    {
        protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, CheckForEmployee requirement)
        {
            if (requirement.Names.Contains(context.User.Identity.Name))
            {
                context.Succeed(requirement);
            }

            return Task.CompletedTask;
        }
    }
}

标签: c#iiswindows-authenticationasp.net-core-2.1

解决方案


遇到类似问题的任何人,请确保在您的 IIS 服务上启用了 Windows 身份验证。这解决了我的问题。


推荐阅读