我的问题分为两部分。我正在使用Web API将应用程序迁移到.NET Core Identity Server 3.0。
因此,在我的Web api上使用标准的[Authorize(Roles =“ Admin,OtherRole”)]属性无法正常工作。它配置为使用Entity Framework,并且在我的Claims Principle Factory中的ClaimsIdentity中正确设置了角色,如下所示:
public class AppClaimsPrincipalFactory : UserClaimsPrincipalFactory<ApplicationUser, IdentityRole>
{
private readonly IAccountService accountService;
public AppClaimsPrincipalFactory(
UserManager<ApplicationUser> userManager,
RoleManager<IdentityRole> roleManager,
IOptions<IdentityOptions> optionsAccessor,
IAccountService accountService) : base(userManager, roleManager, optionsAccessor)
{
this.accountService = accountService;
}
public async override Task<ClaimsPrincipal> CreateAsync(ApplicationUser user)
{
var principal = await base.CreateAsync(user);
var otherPropertyName= accountService.GetOtherPropertyName(user.Email);
if (!string.IsNullOrWhiteSpace(otherPropertyName))
{
((ClaimsIdentity)principal.Identity).AddClaims(new[] {
new Claim("OtherPropertyName" , otherPropertyName)
});
}
return principal;
}
}
我的第二个问题是我有一些类似于以下的代码:
[HttpGet]
[Route("api/admin/entity-details")]
[ApiRolesAuthorise(Roles = "OtherRole, Admin")]
public SomeDto GetDetails(int entityId)
{
if (!this.IsAuthorisedForEntity(entityId))
{
throw new Exception("Unauthorised Request");
}
return admin.GetDetails(entityId);
}
感觉好像可以整理得更像
[HttpGet]
[Route("api/admin/entity-details")]
[ApiRolesAuthorise(Roles = "OtherRole, Admin")]
[IsAuthorisedForResource("EntityX")]
public SomeDto GetDetails(int entityId)
{
return admin.GetDetails(entityId);
}
有没有一种创建自定义授权属性的方法,该属性考虑是否将参数传递给我的自定义数据模型中的查询,而不管用户是否对该资源具有自定义声明。
我一直在研究策略,但是没有任何东西可以证明从上下文中获取实体ID。
预先感谢