【发布时间】:2020-02-08 01:41:15
【问题描述】:
我在ASP Net Forum 上看到了针对 net core 2.2 的基本相同问题。 当我尝试为我的 net core 3.1 应用程序实现时,出现错误
System.InvalidCastException: Unable to cast object of type 'System.Security.Claims.ClaimsIdentity' to type 'System.Security.Principal.WindowsIdentity'
错误发生在 RoleAuthHandler.cs 试图将 Identity 转换为 WindowsIdentity。
我想知道核心 2.2 和 3.1 之间是否发生了变化来解释这一点,或者我做错了什么。任何帮助都会很棒。
Startup.cs 包含
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddSingleton<IAuthorizationHandler, RoleAuthHandler>();
services.AddAuthorization(options =>
options.AddPolicy(
Role.Admin,
policy => policy.AddRequirements(new RoleRequirement(Role.Admin))));
}
角色.cs
public static class Role
{
public const string Guest = "Guest";
public const string Admin = "Admin";
}
RoleRequirement.cs
public class RoleRequirement : IAuthorizationRequirement
{
public string[] Roles { get; }
public RoleRequirement(params string[] roles)
{
this.Roles = roles;
}
}
RoleAuthHandler.cs 包含
protected override Task HandleRequirementAsync(
AuthorizationHandlerContext context,
RoleRequirement requirement)
{
var wi = (WindowsIdentity)context.User.Identity;
var groupSet = new HashSet<string>();
if (wi.Groups != null)
{
foreach (var group in wi.Groups)
{
groupSet.Add(group.Translate(typeof(NTAccount)).ToString());
}
}
string[] userRoles = roleService.GetRolesForGroup(groupSet);
var intersectRoles = Enumerable.Intersect(userRoles, requirement.Roles, StringComparer.OrdinalIgnoreCase);
if (intersectRoles.Count() > 0)
{
context.Succeed(requirement);
}
return Task.CompletedTask;
}
控制器类
[Authorize]
[ApiController]
[Route("[controller]")]
public class InterestingController : ControllerBase
{
[HttpGet]
public string Get()
{
return "Something Interesting";
}
}
【问题讨论】:
-
您能否检查这行代码 var
wi = (WindowsIdentity)context.User.Identity您应该在您的 CAS 中返回ClaimsIdentity您需要将您更改为wi = (ClaimsIdentity)context.User.Identity。
标签: c# asp.net-core-3.1