Ras*_*kov 6 c# authorization asp.net-mvc-5 iis-8.5
我正在进行索赔基础身份验证,它工作正常.现在我想添加角色自动化.我有用户的角色声明(例如"管理员")
调用IsInRole()方法时,会检查当前用户是否具有该角色.在声明感知应用程序中,角色由应在令牌中提供的角色声明类型表示.角色声明类型使用以下URI表示:http: //schemas.microsoft.com/ws/2008/06/identity/claims/role
//Include all claims
//claims is List<Claim> with all claims
var id = new ClaimsIdentity(claims, "Cookies");
Request.GetOwinContext().Authentication.SignIn(id);
Run Code Online (Sandbox Code Playgroud)
如果我检查用户是否在角色中,我将得到错误.虽然我的角色声称具有"管理员"值
User.IsInRole("Admin");
Run Code Online (Sandbox Code Playgroud)
同时授权我的api attrubute也行不通
[Authorize (Roles = "Admin")]
Run Code Online (Sandbox Code Playgroud)
我可能误解了如何让用户可以看到角色.可能还不足以让Roles列入索赔列表?
Rob*_*Rob 12
如果您的服务使用Windows身份验证,那么IPrincipal.Identity您收到的将是类型WindowsPrincipal.这是一个有点误导,但是ClaimType这WindowsPrincipal.IsInRole()看起来对于是不是ClaimTypes.Role因为你可能合理预期,但ClaimTypes.GroupSid.
但是,您不应假设当前标识用于指定角色的实际ClaimType,因为不同类型的标识使用不同的值.相反,你应该引用该ClaimsIdentity.RoleClaimType属性.
我们实施了IAuthenticationFilter以下几项:
public Task AuthenticateAsync(HttpAuthenticationContext context, cancellationToken)
{
var principal = context.Principal;
if(principal.Identity is ClaimsIdentity && principal.Identity.IsAuthenticated)
{
var ci = (ClaimsIdentity)principal.Identity;
// get the user's additional roles from somewhere and add Claims
ci.AddClaim(new Claim(ci.RoleClaimType, "MyRole"));
}
}
Run Code Online (Sandbox Code Playgroud)
这允许我们在ASP.Net控制器中使用标准的AuthorizeAttribute机制.例如
[Authorize(Roles="MyRole")]
public IHttpActionResult Get()
{
//authenticated and authorised code here
}
Run Code Online (Sandbox Code Playgroud)
有关进一步说明,请参阅MSDN上的ClaimsIdentity.RoleClaimType.
请注意:添加用户定义的角色WindowsPrincipal可能会导致问题.似乎.Net Framework 4.5的当前实现(截至2017年4月)在检查角色时有时会抛出异常,期望从Active Directory获得角色的详细信息.有关替代方法,请参阅此问题.
| 归档时间: |
|
| 查看次数: |
5785 次 |
| 最近记录: |