Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have implemented my own role provider, and I'm not using the default one. It works to the point that it can tell when someone should or should not be able to view a page.

However, can it do the following:

  1. If a user is not logged in, redirect to my login page
  2. If a user IS logged in but does not have the correct role, redirect to a different page

I haven't figured out how to do this with the Authorize attribute, all I have is:

[Authorize(Roles="Admin")]

Basically I need to redirect to a different page based on what part of the authorization fails.

I've looked to see if it were something in web.config but nothing obvious jumps out.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
278 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...