[英]Custom authorization in Web API - IClaimsPrincipal from ASP.Net Web API User (System.Security.Claims.ClaimsPrincipal)
I have a Web API for which I need to do custom authorization. 我有一个Web API,我需要为其进行自定义授权。 I'm using oAuth tokens and I was thinking I might do additional checks by implementing an authorizationManager
我正在使用oAuth令牌,并且我想我可能会通过实现AuthorizationManager进行其他检查
using Microsoft.IdentityModel.Claims;
using System.Diagnostics;
using System.Linq;
public override bool CheckAccess(AuthorizationContext context){
public override bool CheckAccess(AuthorizationContext context)
{
//authorization code here
}
}
The problem arises when I attempt to create an AuthorizationContext I don't have the right principal type. 当我尝试创建没有正确的主体类型的AuthorizationContext时,就会出现问题。 I noticed that from my Web API call I get a user which is a System.Security.Claims.ClaimsPrincipal which is not castable to IClaimsPrincipal which is needed by new AuthorizationContext.
我注意到,从Web API调用中,我得到一个用户,该用户是System.Security.Claims.ClaimsPrincipal,该用户不可转换为新AuthorizationContext所需的IClaimsPrincipal。
var authorizationContext = new AuthorizationContext(principal, "resource", "action");//System.Security.Claims.ClaimsPrincipal is the wrong type of principal here, but is what user is on Web API call.
This of course results in the following error: 当然,这会导致以下错误:
cannot convert from 'System.Security.Claims.ClaimsPrincipal' to 'Microsoft.IdentityModel.Claims.IClaimsPrincipal' 无法从“ System.Security.Claims.ClaimsPrincipal”转换为“ Microsoft.IdentityModel.Claims.IClaimsPrincipal”
Is there something other than ClaimsAuthorizationManager I should be implementing? 除ClaimsAuthorizationManager之外,我还应该执行其他操作吗? Is there a simple way to create the context object I need given the type of principal I have?
给定我拥有的委托人类型,是否有一种简单的方法来创建需要的上下文对象?
I did notice that ClaimsAuthorizationManager is in Microsoft.IdentityModel.Claims while much of the other web api stuff is in Microsoft.AspNet.Identity or Microsoft.AspNet.Identity.Core which is perhaps a clue that it might not be the right thing to use. 我确实注意到ClaimsAuthorizationManager在Microsoft.IdentityModel.Claims中,而其他许多Web api东西在Microsoft.AspNet.Identity或Microsoft.AspNet.Identity.Core中,这也许是一个提示,可能不是正确的选择。
I was in fact headed down the wrong path as indicated by the clues. 实际上,线索提示我走错了路。 I ended up implementing System.Web.Http.AuthorizeAttribute similar to this:
我最终实现了类似于以下内容的System.Web.Http.AuthorizeAttribute:
using System;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
public class AuthAttribute : System.Web.Http.AuthorizeAttribute
{
public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext)
{
//authorization stuff here
}
}
and then in my WebApiConfig.cs in the Register method added: 然后在我的WebApiConfig.cs中的Register方法中添加:
config.Filters.Add(new AuthAttribute());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.