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

Categories

0 votes
715 views
in Technique[技术] by (71.8m points)

asp.net mvc - How to redirect [Authorize] to loginUrl only when Roles are not used?

I'd like [Authorize] to redirect to loginUrl unless I'm also using a role, such as [Authorize (Roles="Admin")]. In that case, I want to simply display a page saying the user isn't authorized.

What should I do?

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

Here is the code from my modified implementation of AuthorizeAttribute; I named it SecurityAttribute. The only thing that I have changed is the OnAuthorization method, and I added an additional string property for the Url to redirect to an Unauthorized page:

// Set default Unauthorized Page Url here
private string _notifyUrl = "/Error/Unauthorized"; 

public string NotifyUrl { 
    get { return _notifyUrl; } set { _notifyUrl = value; } 
}

public override void OnAuthorization(AuthorizationContext filterContext) {
    if (filterContext == null) {
        throw new ArgumentNullException("filterContext");
    }

    if (AuthorizeCore(filterContext.HttpContext)) {
        HttpCachePolicyBase cachePolicy =
            filterContext.HttpContext.Response.Cache;
        cachePolicy.SetProxyMaxAge(new TimeSpan(0));
        cachePolicy.AddValidationCallback(CacheValidateHandler, null);
    }

    /// This code added to support custom Unauthorized pages.
    else if (filterContext.HttpContext.User.Identity.IsAuthenticated)
    {
        if (NotifyUrl != null)
            filterContext.Result = new RedirectResult(NotifyUrl);
        else
           // Redirect to Login page.
            HandleUnauthorizedRequest(filterContext);
    }
    /// End of additional code
    else
    {
         // Redirect to Login page.
        HandleUnauthorizedRequest(filterContext);
    }
}

You call it the same way as the original AuthorizeAttribute, except that there is an additional property to override the Unauthorized Page Url:

// Use custom Unauthorized page:
[Security (Roles="Admin, User", NotifyUrl="/UnauthorizedPage")]

// Use default Unauthorized page:
[Security (Roles="Admin, User")]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...