0

Authorize在控制器或动作上使用属性,例如:

[Authorize(Roles="admin,user", Users="user1,user2")]
public ActionResult LogOn(LogOnModel model, string returnUrl) {
    return view();
}

[Authorize(Roles="admin,user",Users="user1")]但是,我必须在每个控制器或动作上这样定义它。

如何在一个地方/文件中定义它?

RegisterGlobalFilters会这样做吗?我不知道如何[Authorize(Roles="*",Users="*")]使用全局过滤器进行定义。

4

1 回答 1

1

尝试这个

创建一个新文件并在操作中使用此属性头

public class AuthorizeAttribute : FilterAttribute, IAuthorizationFilter
{
   private readonly RoleEnum[] _acceptedRoles;


public AuthorizeAttribute(params RoleEnum[] acceptedroles)
{
    _acceptedRoles = acceptedroles;
}

public AuthorizeAttribute(params bool[] allowAll)
{
    if (allowAll[0])
        _acceptedRoles = new RoleEnum[] { RoleEnum.Admin, RoleEnum.user};
}

public void OnAuthorization(AuthorizationContext filterContext)
{
    if (SessionHelper.UserInSession == null)//user not logged in
    {
        FormsAuthentication.SignOut();
        filterContext.Result =
             new RedirectToRouteResult(new System.Web.Routing.RouteValueDictionary {{ "controller", "Home" },
                                         { "action", "Index" },
                                         { "returnUrl",    filterContext.HttpContext.Request.RawUrl } });//send the user to login page with return url
        return;
    }
    if (!_acceptedRoles.Any(acceptedRole => SessionHelper.UserInSession.UserRoles.Any(currentRole => acceptedRole == currentRole.Role)))
        //allow if any of the user roles is among accepted roles. Else redirect to login page
        throw new UnauthorizedAccessException();

 }
}

这也适用于返回 URL

参考

于 2013-04-13T03:47:08.303 回答