How to redirect [Authorize] to loginUrl only when Roles are not used?

后端 未结 3 887
独厮守ぢ
独厮守ぢ 2020-12-13 02:45

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

3条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-13 03:32

    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")]
    

提交回复
热议问题