MVC RoleProvider and Authorize attribute

时光总嘲笑我的痴心妄想 提交于 2019-11-29 04:23:05

VoodooChild answered #1.

For #2 -

What you can do is check if the user is logged on the login page and display a different message or an entirely different page (or even do a redirect to a different action).

Alternatively you can create your own authorization attribute. This will require that you use this attribute everywhere instead of the default AuthorizeAttribute

public class CustomAuthorizeAttribute : AuthorizeAttribute
{
    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        if (filterContext.HttpContext.Request.IsAuthenticated)
        {
            filterContext.Result = new RedirectToRouteResult(
                               new RouteValueDictionary 
                               {
                                   { "action", "ActionName" },
                                   { "controller", "ControllerName" }
                               });
        }
        else
            base.HandleUnauthorizedRequest(filterContext);
    }
}

Update:

Just thought of another method. When a redirect is done to login page from a different page, a querystring ReturnUrl is also passed. So you can also check if it contains something AND the user is authenticated, chances are the user didn't have permission to view that page.

Off the top of my head, if you are using FormsAuthentication then to answer your first question - yes If the user is not Authenticated or logged in then it can be redirected to the log on page:

Make sure you have this in web.config file (not sure if you need anything beside this, will look into it..)

<authentication mode="Forms">
  <forms loginUrl="~/AccountController/LogOn" timeout="2880" />
</authentication>

To answer your second question: "If a user IS logged in but does not have the correct role, redirect to a different page"

The way we did this was, we used the System.Web.Security.Roles.GetRolesForUser(username); method to get the Roles and based on this we redirected the user to the correct view, after login.

Hope this helps!

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