ASP.NET MVC Roles and Security

若如初见. 提交于 2019-11-29 13:02:29

As per my thinking you need to code for authorization.

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.

As per comments, if you are using custom authentication/authorization mechanism then you need to implement custom authorize attribute where you can put custom logic to check if user has admin role or not. Something like below:

public class CustomizedAuthorizeAttribute : AuthorizeAttribute
{
    public override void OnAuthorization(AuthorizationContext filterContext)
    {
        //check for role in session variable "ADMIN_ROLE"

    //if not valid user then set
    filterContext.Result = new RedirectResult(URL)
    }
}

There is a small nice explanation in this link:

http://weblogs.asp.net/jgalloway/archive/2011/04/28/looking-at-how-asp-net-mvc-authorize-interacts-with-asp-net-forms-authorization.aspx

as per this:

ASP.NET MVC includes an [Authorize] attribute, which when placed on any controller actions will forbid unauthorized access. The AuthorizeAttribute allows you to specify a list of roles or users. You can also place the AuthorizeAttribute on a controller, in which case it will apply to all actions in the controller. Attempting to access an action secured by the AuthorizeAttribute when you're not logged in will take you to a standard LogOn screen, with a link to register if you don't already have an account.

How does the [Authorize] attribute redirect me to Log On?

The AuthorizeAttribute is an ActionFilter, which means that it can execute before the associated controller action. The AuthorizeAttribute performs its main work in the OnAuthorization method, which is a standard method defined in the IAuthorizationFilter interface. Checking the MVC source code, we can see that the underlying security check is really just looking at the underlying authentication information held by the ASP.NET context:

IPrincipal user = httpContext.User;

if (!user.Identity.IsAuthenticated)
{
    return false;
}

If the user fails authentication, an HttpUnauthorizedResult ActionResult is returned, which produces an HTTP 401(Unauthorized) status code. If it weren’t for ASP.NET Forms Authentication, an HTTP 401 status code would be sent to the browser, which would show the browser’s default login prompt.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!