事实证明,WindowsIdentity
它保留在HttpContext.User
对象中,允许我们检查组/角色成员资格。
内联示例
using System.Security.Principal;
[Authorize(AuthenticationSchemes = IISServerDefaults.AuthenticationScheme)]
public ActionResult SomeAction()
{
var windowsIdentity = HttpContext.User.Identity as WindowsIdentity;
var windowsUser = new WindowsPrincipal(windowsIdentity);
var role = "[MY-COMPUTER-NAME || AD GROUP NAME]\\[GROUP NAME]";
var inInRole = windowsUser.IsInRole(role);
// todo: if not allowed write code to handle it
return View();
}
完整来源
策略示例
//AuthorizationHandler<T>
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, RoleRequirement requirement)
{
if (!(context.User.Identity is WindowsIdentity windowsIdentity))
return Task.CompletedTask;
var windowsUser = new WindowsPrincipal(windowsIdentity);
try
{
var hasRole = windowsUser?.IsInRole(requirement.GroupName) ?? false;
if (hasRole)
context.Succeed(requirement);
}
catch (Exception ex)
{
logger.LogError(ex, "Unable to check groups the user belongs too");
}
return Task.CompletedTask;
}
//IAuthorizationRequirement
public class RoleRequirement : IAuthorizationRequirement
{
public RoleRequirement(string groupName)
{ GroupName = groupName; }
/// <summary>
/// The Windows / AD Group Name that is allowed to call the OMS API
/// </summary>
public string GroupName { get; }
}
//action protected with the policy
[Authorize("Super User Role")]
public IActionResult Contact()
{ return View(); }
//startup.cs
public void ConfigureServices(IServiceCollection services)
{
//pull group name from the config
var securityOptions = Configuration.GetSection("Security").Get<SecurityOptions>();
services.AddAuthentication(IISDefaults.AuthenticationScheme);
services.AddAuthorization(options =>
{
options.AddPolicy("Super User Role", policy =>
{
policy.Requirements.Add(new RoleRequirement(securityOptions.AllowedGroup));
policy.AddAuthenticationSchemes("Windows");
});
});
services.AddSingleton<IAuthorizationHandler, RoleHandler>();
// ...
}
完整来源