【问题标题】:Angular 7 .net core 2.2 WebApi Windows Authentication CORSAngular 7 .net 核心 2.2 WebApi Windows 身份验证 CORS
【发布时间】:2019-08-26 01:13:08
【问题描述】:

我正在使用带有 .net core 2.2 和 Asp.net WebApi 的 Angular 7,并尝试使用 Windows 身份验证来识别用户。当我发布数据时,CORS 飞行前请求被阻止,除非我启用匿名身份验证。当我启用“匿名身份验证”时,

的值

HttpContext.User.Identity.Name

即使仍然启用了“Windows 身份验证”也为 null

我已经在本地开发机器上使用 IIS Express、IIS 7.5 和 Windows 2012 上的 IIS 8 进行了尝试

在 Startup.cs 中

public IServiceProvider ConfigureServices(IServiceCollection services)
{
            services.AddHttpContextAccessor();

            services.AddCors(o => o.AddPolicy("TreasuryPolicy", builder =>
            {
                builder                
                .WithOrigins("http://localhost:4200")
                .AllowAnyMethod()
                .AllowAnyHeader()
                .AllowCredentials();
            }));
            services.AddCors();

            services.AddTransient<IClaimsTransformation, ClaimsLoader>();
            services.AddAuthentication(IISDefaults.AuthenticationScheme);
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
            app.UseAuthentication();
            app.UseMvc();
}

在 ClaimsLoader.cs 和 Controller 中,当启用“Windows 身份验证”时,adLoginName 都是正确的,但在 IIS 中也选择了匿名身份验证时,adLoginName 为空

ClaimsLoader.cs

public async Task<ClaimsPrincipal> TransformAsync(ClaimsPrincipal principal)
{
      var adLoginName = (ClaimsIdentity)principal.Identity.Name;
}

SecurityController.cs

[HttpGet("HasPermission/{permissionName}")]        
public ActionResult<bool> HasPermission(string permissionName)
{
     var adLoginName = _httpContextAccessor.HttpContext.User.Identity.Name;
}

【问题讨论】:

  • 如果未启用匿名身份验证,则来自 CORS 的此错误:从源 'localhost:4200' 对 XMLHttpRequest 的访问已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。
  • 在处理飞行前请求期间您很可能没有看到任何身份。
  • 不幸的是,我没有看到所有请求的身份,即在没有飞行前检查的 Get 请求中
  • Keith,你有没有为你的查询找到任何解决方案
  • 嗨,是的,如下 0 似乎如果您将属性 [Authorize] 添加到控制器或在选择“启用匿名身份验证”和“启用 Windows 身份验证”时强制 Windows 身份验证的操作docs.microsoft.com/en-us/aspnet/core/security/authentication/…

标签: angular .net-core cors asp.net-web-api2 windows-authentication


【解决方案1】:

您忘记启用 cors:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    app.UseAuthentication();
    app.UseMvc();
    app.UseCors("TreasuryPolicy")
}

更多信息:https://docs.microsoft.com/de-de/aspnet/core/security/cors?view=aspnetcore-2.2

【讨论】:

  • 谢谢,但我已经启用了上面的 CORS,我在我的代码 sn-p 中错过了它
【解决方案2】:

如果您将属性 [Authorize] 添加到控制器或操作,它似乎会在选择“启用匿名身份验证”和“启用 Windows 身份验证”时强制 Windows 身份验证https://docs.microsoft.com/en-us/aspnet/core/security/authentication/windowsauth?view=aspnetcore-2.2&tabs=visual-studio

【讨论】:

    猜你喜欢
    • 2018-01-07
    • 2019-11-03
    • 2019-02-23
    • 1970-01-01
    • 1970-01-01
    • 2018-06-27
    • 2020-01-13
    • 2012-09-12
    • 2019-12-24
    相关资源
    最近更新 更多