AuthorizeAttribute处理有效的授权用户

时间:2015-07-31 18:27:43

标签: c# asp.net-mvc

我实现了一个自定义的AuthorizeAtrribute类

public class AdminAuthorizeAttribute : AuthorizeAttribute
{
    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        base.HandleUnauthorizedRequest(filterContext);
    }
} 

行动方法

[AdminAuthorize(Roles = "Admin")]
public ViewResult AdminOnly()
{
    return View();
}

[AdminAuthorize(Roles = "Admin, Mod")]
public ViewResult Index()
{
    return View();
}

当我有一个IsAuthenticated但没有Admin角色的用户时,我想将它们重定向到Index页面而不是登录页面。

我已经阅读了上的许多其他SO帖子,但我的HandleUnauthorizedRequest()方法没有解雇。

2 个答案:

答案 0 :(得分:1)

您正在覆盖一个比您想象的更晚的方法。您需要覆盖其中一种方法来实现您的身份验证逻辑:

    public override void OnAuthorization(AuthorizationContext filterContext)
    {
        base.OnAuthorization(filterContext);

        //do custom work here
    }

OR

    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        if (!base.AuthorizeCore(httpContext))
            return false;

        //do custom work here
    }

答案 1 :(得分:1)

这是我使用活动目录时总是使用的代码

#each line is a list: 
a = ['1\t2\t3\t4\t5']
#type(a) is list
#str(a) shows as below:
["['1\\t2\\t3\\t4\\t5']"]

忘了告诉Groups变量代表我的属性

中的字段
public string Groups { get; set; }

protected override bool AuthorizeCore(HttpContextBase httpContext)
{
    if (base.AuthorizeCore(httpContext))
    {
        if (String.IsNullOrEmpty(Groups)) { return true; }

        var groups = Groups.Split(',').ToList();

        var context = new PrincipalContext(ContextType.Domain,"yourDomain");

        var userPrincipal = UserPrincipal.FindByIdentity(context,IdentityType.SamAccountName,httpContext.User.Identity.Name);

        foreach(var group in groups){ // this will check user if the right role in active directory
            if(userPrincipal.IsMemberOf(context, IdentityType.Name, group)){
                return true;
            }
        }
    }

    return false;
}

protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
    if (filterContext.HttpContext.User.Identity.IsAuthenticated)
    {
        var result = new ViewResult();
        result.ViewName = "NotAuthorized";
        result.MasterName = "_Layout";
        filterContext.Result = result;
    }
    else
    {
        base.HandleUnauthorizedRequest(filterContext);
    }
}