本文介绍了Angular 7 .net core 2.2 WebApi Windows 身份验证 CORS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将 Angular 7 与 .net core 2.2 和 Asp.net WebApi 一起使用,并尝试使用 Windows 身份验证来识别用户.当我发布数据时,除非我启用匿名身份验证,否则 CORS 飞行前请求将被阻止.当我启用匿名身份验证"时,

I am using Angular 7 with .net core 2.2 and the Asp.net WebApi and attempting to use Windows Authentication to identify the user. When I post data the CORS pre flight request is blocked unless I enable Anonymous Authentication. When I enable 'Anonymous Authentication' the value of

HttpContext.User.Identity.Name

即使启用了Windows 身份验证",也为空

is null even though 'Windows Authtication' is enabled still

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

I have tried this using IIS Express, IIS 7.5 on local development machine and IIS 8 on Windows 2012

在 Startup.cs 中

In 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 为空

In both ClaimsLoader.cs and Controller adLoginName is correct when 'Windows Authentication' is enabled but when Anonymous Authentication is also selected in IIS then adLoginName is null

ClaimsLoader.cs

ClaimsLoader.cs

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

SecurityController.cs

SecurityController.cs

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

推荐答案

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

It seems if you add the attribute [Authorize] to the controller or action it forces Windows Authentication when 'Enable Anonymous Authentication' and 'Enable Windows Authentication' are selected https://docs.microsoft.com/en-us/aspnet/core/security/authentication/windowsauth?view=aspnetcore-2.2&tabs=visual-studio

这篇关于Angular 7 .net core 2.2 WebApi Windows 身份验证 CORS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-22 22:18