Reputation: 25
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
is null even though 'Windows Authtication' is enabled still
I have tried this using IIS Express, IIS 7.5 on local development machine and IIS 8 on Windows 2012
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();
}
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
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;
}
Upvotes: 1
Views: 1723
Reputation: 25
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://learn.microsoft.com/en-us/aspnet/core/security/authentication/windowsauth?view=aspnetcore-2.2&tabs=visual-studio
Upvotes: 1
Reputation: 844
You forgot to enable cors:
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
app.UseAuthentication();
app.UseMvc();
app.UseCors("TreasuryPolicy")
}
Additional info here: https://learn.microsoft.com/de-de/aspnet/core/security/cors?view=aspnetcore-2.2
Upvotes: 1