MVC5 声明版本的 Authorize 属性 [英] MVC5 Claims version of the Authorize attribute

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

问题描述

我正在使用 MVC5 和新的 OWIN 身份验证中间件尝试 VS2013 RC 中的一些新东西.

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

所以,我习惯于使用 [Authorize] 属性来限制角色的操作,但我正在尝试使用基于声明/活动的授权,但我找不到等效的属性为它.

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.

我想特别寻找类似于 [Authorize("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);
        }
    }
}

当然,如果您乐于以某种方式使用控制器-动作-动词三元组进行声明,您可以删除类型和值参数.

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 声明版本的 Authorize 属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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