ASP.NET Web API-设置自定义IIdentity或IPrincipal [英] ASP.NET web api - Set custom IIdentity or IPrincipal

查看:227
本文介绍了ASP.NET Web API-设置自定义IIdentity或IPrincipal的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我们的asp.net mvc/web api项目中,我们想使用AuthorizeAttribute自定义授权.我们已经注意到,有两种不同的AuthorizeAttribute,一种在MVC的System.Web.MVC命名空间中,另一种在Web api的System.Net.Http命名空间中.

In our asp.net mvc/web api project, we want to customize the authorization using AuthorizeAttribute. We have noticed that there are two different AuthorizeAttribute, one in System.Web.MVC namespace for MVC and the other in System.Net.Http namespace for web api.

它可以在MVC中工作,我们的代码如下:

It works in MVC, our code like this:

public class MyPrincipal : IPrincipal
{
    //some custom properties
    public bool IsValid()
    {
        //custom authentication logic
    }

    private IIdentity identity;
    public IIdentity Identity
    {
        get { return this.identity; }
    }

    public bool IsInRole(string role)
    {
        return true;
    }
}

//override AuthorizeCore
public class MyAuthorizeAttribute : AuthorizeAttribute
{
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        MyPrincipal user = new MyPrincipal();

        if (user.isValid())
        {
            httpContext.User = user;
        }
        else
        {
            httpContext.Response.Redirect("~/Common/NoAuthorize", true);
        }
    }
}

[MyAuthorizeAttribute]
public class BaseMyController : Controller
{
    protected virtual new MyPrincipal User
    {
        get { return HttpContext.User as MyPrincipal; }
    }
}

然后在MVC控制器中,我们可以通过MyPrincipal用户属性获取用户信息.

Then in MVC controller,we can get the user information via MyPrincipal user property.

但是,当我们开始在Web api中使用相同的方法时,我们发现Web api没有HttpContext属性,而在System.Web.Http.AuthorizeAttribute中,要覆盖的方法接受HttpActionContext参数,它也具有没有HttpContext属性,或者我们可以在其他地方设置MyPrincipal实例的地方.

However, when we start to use the same way in web api, we found that the web api has no HttpContext property and in System.Web.Http.AuthorizeAttribute, the method to be override accepts a HttpActionContext argument, it also has no HttpContext property or some where else we can set the MyPrincipal instance.

我注意到System.Web.Http.AuthorizeAttribute摘要指出

指定用于验证请求的IPrincipal的授权过滤器

似乎还有其他方法可以设置IPrincipal实例.

It seems that there is some other way to set the IPrincipal instance.

我对此一无所知,有什么好的建议吗?顺便说一句,为什么asp.net Web API控制器没有HttpContext?是否有任何设计模式?

I have no idea about it, any good advice? By the way, why does the asp.net web api controller have no HttpContext? Is there any design pattern about it?

相关问题 ASP.NET MVC-设置自定义IIdentity或IPrincipal

The related questions ASP.NET MVC - Set custom IIdentity or IPrincipal

推荐答案

我主要通过以下方式实现了一些概念验证:

I implemented something as a proof of concept following mostly this: Authentication Filters in ASP.NET Web API 2

对于Web API,您可以创建一个属性IAuthenticationFilter. 如果我没记错的话,您可以将其作为过滤器添加到WebApiConfig中的全局过滤器中

For Web API you can create an Attribute, IAuthenticationFilter. If I remember rightly, you can add it as a filter to the global filters in WebApiConfig

config.Filters.Add(new YourAuthenticationAttribute());

或者您可以将其用作api控制器/方法上的属性.

Or you can use it as an attribute on the api controller/ method.

然后,您可以实现AuthenticateAsync,获取请求的授权标头,检查方案并验证参数,如果所有方法都有效,则设置主体.

You can then implement AuthenticateAsync, get the request's authorization header, check the scheme, and validate the parameter, and if all is valid, set the principal.

我认为您可以在一个链中添加多个这些过滤器,并且它们都可以针对一组特定的要求进行身份验证,例如他们要寻找的方案,并且可以在链中某个位置设置主体,或者挑战被返回.

I think the idea is that you can add multiple of these filters in a chain and they can all authenticate against a specific set of requirements, like the scheme they look for, and somewhere in the chain the principal gets set, or a challenge is returned.

public class YourAuthenticationAttribute : Attribute, IAuthenticationFilter
{

public Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken)
{
HttpRequestMessage request = context.Request;

if (request.Headers.Authorization != null &&
    request.Headers.Authorization.Scheme.Equals("yourScheme", StringComparison.OrdinalIgnoreCase))
    {
        // get the value sent with the header.
        string authParam = request.Headers.Authorization.Parameter;

        // do some validation on the parameter provided...
        // if it's all valid, create a principal with claims:


    List<Claim> claims = new List<Claim>()
    {
        new Claim(ClaimTypes.Name, "Eddie Admin"),
        new Claim(ClaimTypes.Role, "Admin"),
        // new Claim(ClaimTypes.Role, "Delete"),
    };

    // create an identity with the valid claims.
    ClaimsIdentity identity = new ClaimsIdentity(claims, "yourScheme");

    // set the context principal.
    context.Principal = new ClaimsPrincipal(new[] { identity });

在创建主体时,您可以申请索赔,并根据常规的authorize属性对其进行检查.例如

When creating the principal you can apply claims and these are checked against the normal authorize attribute. e.g.

[Authorize(Roles = "Admin")]

除了使用它,我还没有使用它,但是希望这可以为您指明正确的方向.

I haven't used it beyond doing this, but hopefully this points you in the right direction.

这篇关于ASP.NET Web API-设置自定义IIdentity或IPrincipal的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆