Tell me more ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

I was trying to find a way to redirect to different pages on authorization and authentication failure. I found this to be a possible solution.

However, I ended with a different solution by myself. It seems to work fine, however, I am not sure if it is the right thing to do.

I created a custom Authorize Attribute that redirects to an action if the request is Authenticated but not Authorized. Here it is:

public class HandleAuthorizeAttribute : AuthorizeAttribute {
        public static string GlobalUnAuthorizationUrl { get; set; }

        private const string DefaultUnAuthorizationUrl = "~/Account/UnAuthorized";
        private static readonly char[] RolesSeparator = { ',' };

        public string UnAuthorizedUrl { get; set; }

        protected override bool AuthorizeCore(HttpContextBase httpContext) {
            if(httpContext.User.Identity.IsAuthenticated) {
                if(string.IsNullOrEmpty(Roles)) {
                    return true;
                } else {
                    var rolesOfUser = System.Web.Security.Roles.GetRolesForUser(httpContext.User.Identity.Name);
                    var authorizedRoles = Roles.Split(RolesSeparator);

                    var common = rolesOfUser.Intersect(authenticatedRoles);

                    if(common.Count() == 0) {
                        httpContext.Response.Redirect(
                            string.Format("{0}?{1}={2}", ActiveUnAuthorizedUrl, "requestUrl", httpContext.Request.Url.AbsoluteUri));
                        return false;
                    }

                    return true;
                }
            } else {
                return false;
            }
        }

        private string ActiveUnAuthorizedUrl {
            get {
                if(!string.IsNullOrEmpty(UnAuthorizedUrl)) {
                    return UnAuthorizedUrl;
                }
                if(!string.IsNullOrEmpty(GlobalUnAuthorizationUrl)) {
                    return GlobalUnAuthorizationUrl;
                }
                return DefaultUnAuthorizationUrl;
            }
        }
    }

Is it alright to redirect to a url in the middle of a non-action method? Does it have any potential drawbacks?

share|improve this question
If you are confused with how the URL to redirect is formed, just ignore it. Its NOT important! – Mohayemin Jun 7 '12 at 12:30

migrated from stackoverflow.com Jul 19 '12 at 13:15

Know someone who can answer? Share a link to this question via email, Google+, Twitter, or Facebook.

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.