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.
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?