【问题标题】:Asp.Net Core 2.1 SPA React Template with Windows Authentication带有 Windows 身份验证的 Asp.Net Core 2.1 SPA React 模板
【发布时间】:2018-08-27 16:45:11
【问题描述】:

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

重现我的问题:

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

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

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

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;
        }
    }
}

【问题讨论】:

  • “出于某种原因,这只能在本地工作。”那有什么问题呢?
  • @LexLi 我已经更新了问题,现在应该更清楚了。
  • 解释什么是“在真正的 IIS 服务器上它不会工作”。
  • 我已经提到了什么不起作用,但我会澄清更多。当我在本地运行程序(Visual Studio 使用 IIS Express)并访问我的页面(通过 localhost)时,我得到了正确的 Windows 用户名,其中包含内部活动目录域。但是当我将我的项目部署到一个目录时,一个 IIS 服务被配置为在发生更改时在我们的服务器上侦听和运行应用程序,然后在线访问网页,我没有得到任何 Windows 身份验证。总之,当我通过 Internet 访问该页面时,我没有收到 Windows 用户名。
  • 由于各种安全因素,从不建议通过 Internet 进行 IIS Windows 身份验证。使用基于表单的身份验证或 OAuth。

标签: c# iis windows-authentication asp.net-core-2.1


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-30
    • 1970-01-01
    相关资源
    最近更新 更多