I am looking for some help implementing Windows authentication / authorization in .NET Core 6. I can't find any good videos on the topic and plan to make one once I finish this project.
I found the following document to Configure Windows Authentication in ASP.NET Core
and implemented this code:
using Microsoft.AspNetCore.Authentication.Negotiate;
var builder = WebApplication.CreateBuilder(args);
builder.Services
.AddAuthentication(NegotiateDefaults.AuthenticationScheme)
.AddNegotiate();
builder.Services
.AddAuthorization(options =>
{
options.FallbackPolicy = options.DefaultPolicy;
});
Now that this is implemented, I can't seem to find where I would specify which users are allowed to access the website. I would like this setup so there is no user login, however as long as they are using a windows account that is part of the right group they can access the parts of the website that are setup for that group.
As of right now the only thing I need to secure is a Web API, however in the future there will be a front end to secure as well (possibly Blazor).
Can anybody point me to a tutorial on implementing this or tell me how to set this up?
Can anybody point me to a tutorial on implementing this or tell me how to set this up?
According to the description, I suggest you could create a claim transfer class to query the role and add it to the claims when using the windows authentication.
Then you could directly use the Authorize Roles attribute to allow just specific group use to that controller.
More details, you could refer to below codes:
public class ClaimsTransformer : IClaimsTransformation
{
public Task<ClaimsPrincipal> TransformAsync(ClaimsPrincipal principal)
{
var ci = (ClaimsIdentity)principal.Identity;
var re = ci.Claims.Where(x => x.Type == ClaimTypes.GroupSid || x.Type == ClaimTypes.PrimaryGroupSid).ToList();
foreach (var item in re)
{
string account = new System.Security.Principal.SecurityIdentifier(item.Value).Translate(typeof(System.Security.Principal.NTAccount)).ToString();
var roleClaim = new Claim(ClaimTypes.Role, account);
ci.AddClaim(roleClaim);
}
return Task.FromResult(principal);
}
}
Inject it inside the program.cs
builder.Services.AddSingleton<IClaimsTransformation, ClaimsTransformer>();
Usage:
[Authorize(Roles = "NT AUTHORITY\\Local account and member of Administrators group")]
[HttpPost("WindowsAuthTest")]
public IActionResult WindowsAuthTest()