MVC5索赔的授权属性的版本 [英] MVC5 Claims version of the Authorize attribute

查看:160
本文介绍了MVC5索赔的授权属性的版本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在尝试一些新的东西,在VS2013 RC与MVC5和新OWIN认证的中间件。

I'm trying out some of the new stuff in VS2013 RC with MVC5 and the new OWIN authentication middleware.

所以,我习惯使用 [授权] 属性来限制角色的行动,但我试图使用索赔/基于活动的授权,我可以找不到同等属性吧。

So, I'm used to using the [Authorize] attribute to limit actions by role but I'm trying to use claims/activity based authorization, and I can't find an equivalent attribute for it.

时有一个明显的例子我错过或是否需要推出自己的?我还挺期待那里为一个开箱即用的。

Is there an obvious one I'm missing or do I need to roll my own? I kinda expected there to be one out of the box.

我正在寻找具体是沿东西线 [授权(ClaimType,ClaimValue)] 我想。

What I'm looking for specifically is something along the lines of [Authorize("ClaimType","ClaimValue")] I suppose.

先谢谢了。

推荐答案

我最终只是写一个简单的属性来处理它。没有一堆额外配置的我找不到在什么框架开箱的。下面列出。

I ended up just writing a simple attribute to handle it. I couldn't find anything in the framework right out of the box without a bunch of extra config. Listed below.

public class ClaimsAuthorizeAttribute : AuthorizeAttribute
{
    private string claimType;
    private string claimValue;
    public ClaimsAuthorizeAttribute(string type, string value)
    {
        this.claimType = type;
        this.claimValue = value;
    }
    public override void OnAuthorization(AuthorizationContext filterContext)
    {
        var user = filterContext.HttpContext.User as ClaimsPrincipal;
        if (user != null && user.HasClaim(claimType, claimValue))
        {
            base.OnAuthorization(filterContext);
        }
        else
        {
            base.HandleUnauthorizedRequest(filterContext);
        }
    }
}

当然,你可以,如果你乐于使用索赔不知何故控制器动作动词三重删除类型和值PARAMS。

Of course, you could remove the type and value params if you were happy to use the controller-action-verb triplet for claims somehow.

这篇关于MVC5索赔的授权属性的版本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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