0

I use the Authorize attribute on controller or action, such as:

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

However, I have to define it like this [Authorize(Roles="admin,user",Users="user1")] on every controller or action.

How can I define this in one place/file?

Will RegisterGlobalFilters do this? I don't know how to define [Authorize(Roles="*",Users="*")] using Global Filters.

Jesse
  • 8,605
  • 7
  • 47
  • 57
zomboo
  • 1
  • 2
  • Why didn't Global Filters work? Did you try this: http://stackoverflow.com/questions/13346801/register-global-filters-in-asp-net-mvc-4-and-autofac – rliu Apr 13 '13 at 04:18

1 Answers1

1

Try this

Create a new file and use this attribute header inthe action

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();

 }
}

This is also work for return URL

Reference

Community
  • 1
  • 1
Amit
  • 15,217
  • 8
  • 46
  • 68