Reputation: 29683
I have 4 controllers namely Account
, Admin
, Home
and Gallery
. Out of this 4 controllers I only need to Authorize Admin
controller and remaining can have access by anonymous. So I've decorated my home controller, gallery controller and account controller with [AllowAnonymous]
attribute and I've my Admin
controller decorated with my custom authorization filter named [CustAuthFilter]
and it contains following code.
public class CustAuthFilter : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
var request = httpContext.Request;
string controller = request.RequestContext.RouteData.Values["controller"].ToString().ToLower();
if (controller != "" && controller == "admin")
{
var isAuthorized = base.AuthorizeCore(httpContext);
if (!isAuthorized)
{
return false;
}
else
{
if (!object.ReferenceEquals(httpContext.Session["un"], null))
{
return true;
}
else
{
return false;
}
}
}
else
{
return true;
}
}
override public void OnAuthorization(AuthorizationContext filterContext)
{
base.OnAuthorization(filterContext);
if (filterContext.Result is HttpUnauthorizedResult && filterContext.HttpContext.Request.IsAjaxRequest())
{
String url = System.Web.Security.FormsAuthentication.LoginUrl + "?X-Requested-With=XMLHttpRequest";
filterContext.Result = new RedirectResult(url);
}
}
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
String url = System.Web.Security.FormsAuthentication.LoginUrl;
filterContext.Result = new RedirectResult(url);
}
}
and in my web.config I've following
<authentication mode="Forms">
<forms loginUrl="~/Account/Login" defaultUrl="~/Admin/Index" timeout="2880" protection="Encryption" slidingExpiration="true" cookieless="AutoDetect"/>
</authentication>
<authorization>
<deny users="?"/>
</authorization>
and I have registered my customized authorization attribute in filters as follows:
filters.Add(new CustAuthFilter());
But whenever I try to access domainname/home
or domainname/gallery
it will be automatically redirected to domainname/account/login
. But I don't have any idea why even after decorating home and gallery controller with [AllowAnonymous]
it is redirecting to Account controller!!
Upvotes: 0
Views: 2581
Reputation: 5771
The behavior is happening because of the authorization config i.e.
<authorization>
<deny users="?"/>
</authorization>
Remove this line from your config and it should be working after that.
You are trying to mix the authorization in Web.config and the Authorize attribute available in MVC. Read this link on a clear answer to not using the authorization tag Authorize attribute vs authorization node in web.config
Upvotes: 1