我应该在哪里插件在Asp.net的WebAPI授权? [英] Where should I plugin the Authorization in Asp.net WebAPI?

查看:163
本文介绍了我应该在哪里插件在Asp.net的WebAPI授权?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我看到我有3个可能的地方插上我的东西在管道

As I see I have 3 possible places to plug my stuff in the pipeline

1)     AuthorizationFilters

2)     Action Filters

3)     DelegatingHandler

最明显的是AuthorizationFilters,在那里我可以装饰自己的行动/控制器,我自定义的授权属性。说.. MyCustomAuthorizationAttribute

由于HTTP消息处理程序是在处理管线的第一阶段。这有什么意义,把它放在那里?

Since HTTP message handlers are in the first stage in the processing pipeline. Does it make any sense to put it in there ?

授权给我,现在只是意味着检查在头一个令牌是认证后交给客户端。

Authorization for me right now simply means checking a token in the header which is given to the client after authentication.

推荐答案

更新2014年7月

我原来的答复覆盖的WebAPI 1. 2的WebAPI有一些变化,即现在有一个 IAuthenticationFilter 这意味着你可以将认证逻辑出了 DelegatingHandler 这是一个小更优雅。

My original answer covered WebApi 1. with WebApi 2 there were some changes i.e. there is now an IAuthenticationFilter meaning you can move authentication logic out of the DelegatingHandler which is a little more elegant.

这里有一个项目的NuGet ,提供IAuthenticationFilter的实现并解释一些背景。据其介绍。

There is a Nuget project here that offers an implementation of IAuthenticationFilter and also explains some background to its introduction.

OWIN中间件,现在也许是实现你的认证逻辑最好的地方 - 有证书认证<一个示例href=\"http://leastprivilege.com/2013/11/11/client-certificate-authentication-middleware-for-katana/\">here与基本身份验证OWIN中间件在这里<一个href=\"http://lbadri.word$p$pss.com/2013/07/13/basic-authentication-with-asp-net-web-api-using-owin-middleware/\">this博客文章前者的例子是pferred一个$ P $,因为它演示了如何使用基本的的AuthenticationHandler 类。

OWIN middleware is now perhaps the best place to implement your authentication logic - there is an example of Certificate Authentication here and Basic Authentication OWIN Middleware here in this blog post the former example is the preferred one as it demonstrates the use of the base AuthenticationHandler class.

上的意见 AuthorizationFilters 在很大程度上仍然不变。

The advice on AuthorizationFilters remains largely unchanged.

结束更新

通常...

使用 DelegatingHandler 来进行身份验证...即谁有人。使用此设置线程和用户上下文的原则,加上索赔等,你可以在这里放置授权逻辑太多,但在相当全球范围。我个人一直使用AuthorizationFilters进行授权。

Use DelegatingHandler to carry out Authentication... i.e. who someone is. Use this to set the Principle of the Thread and User context, add claims etc. You can place authorisation logic here too but on a fairly global scale. I would personally always use AuthorizationFilters for authorisation.

使用 AuthorizationFilters 来限制控制器和行动,以具体的人。这些被使用时,您可以在债权,本金,URL或HTTP请求参数的信息推断他们的许可。默认授权过滤器可用于限制访问匿名用户或角色(如果设置的东西就像一个委托处理程序) - 很明显,你可以实现自己的AuthorizationFilters太多,如果你需要它

Use AuthorizationFilters to restrict controllers and actions to specific people. These are used when you can extrapolate their permission with the information in claims, principal, url or the http request parameters. The default authorisation filter can be used to restrict access to anonymous users or by roles (if set in something like a delegating handler) - obviously you can implement your own AuthorizationFilters too if you need it.

偶尔使用 ActionFilters 当你需要使用例如邮件内容作出了批准决定您需要访问的实体属性,以决定他们是否有机会(当然要小心对待这个(!))。

Occasionally use ActionFilters when you need to make the decision over authorisation using the message content e.g. you need access to a property on the entity to decide whether they have access (obviously be careful with this(!)).

请注意:

AuthorizationFilters 被称为因此阅读正文的内容之前,他们没有获得邮件正文作出授权决定,这就是为什么 ActionFilters 专门 OnActionExecuting 是用来偶尔加薪身份验证错误。

The AuthorizationFilters are called before the content of the body is read therefore they do not have access to the message body to make authorization decisions this is why the ActionFilters specifically the OnActionExecuting is used to occasional raise authentication errors.

所以

在您的情况我会放一个简单的 DelegatingHandler 来把你的头,并设置本金。

In your scenario I would put a simple DelegatingHandler to take your header and set the principal.

public class CustomAuthenticationMessageHandler : DelegatingHandler
{


    public CustomAuthenticationMessageHandler ()
    {

    }

    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,
                                                           CancellationToken cancellationToken)
    {
        Authenticate(request);

        return base.SendAsync(request, cancellationToken);
    }

    protected virtual void Authenticate(HttpRequestMessage request)
    {

        var authorisationHeader = request.Headers.Authorization;

        if (authorisationHeader == null)
        {
            return;
        }

        //Ensure you are happy with the header contents then

        {
            var principal = new GenericPrincipal(//new Identity , //Roles);
            Thread.CurrentPrincipal = principal;
            HttpContext.Current.User = principal;
        }

    }
}

然后使用 AuthorizationFilters 来限制访问:

    [Authorize]
    public string Get()
    {

    }

    [Authorize(Roles = "Admin")]
    public string GetAdminOnly()
    {

    }

要注册全球认证

config.MessageHandlers.Add(new CustomAuthenticationMessageHandler());

这将意味着,在每一个请求中的主体将被设置为null或有效身份证件。它不会处理授权即不会拒绝访问任何控制器或动作。

This will mean that in every request the principal will be set to either null or a valid identity. It won't handle authorisation i.e. wont deny access to any controllers or actions.

要开始保护资源

无论目标保护控制器和动作与标准或自定义[授权]属性。或全球注册:

Either target protected controllers and actions with the standard or custom [Authorize] attributes. Or register globally:

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

和只有白名单中的控制器和动作你要不安全使用 [使用AllowAnonymous] 属性。

And only white list the controllers and actions you want unsecured using the [AllowAnonymous] attribute.

如果您只想对部分航线认证

然后,你可以修改你的 DelegatingHandler 一点点地将 InnerHandler 路由到正确的控制器例如:

Then you can modify your DelegatingHandler a little to set the InnerHandler to route to the correct controller e.g.

public CustomAuthenticationMessageHandler(HttpConfiguration configuration)
{
       InnerHandler = new HttpRoutingDispatcher(configuration);
}

然后你就可以在你的路由指定该处理程序,像这样:

And then you can specify this handler on your routes like so:

config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "myurl",
            defaults: new {},
            constraints: new {},
            handler: new CustomAuthenticationHandler(config)
            );

这篇关于我应该在哪里插件在Asp.net的WebAPI授权?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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