How to deny access only one area in .net MVC?
-
28-06-2021 - |
문제
I'm trying to deny only one area using .Net MVC 4 and I'm not getting results. What happens is when I put <authentication mode="Forms" />
in web.config everything is denied: all the site and is not what I want, I only want to deny the admin area.
I put the AuthorizeAttribute
in BaseController
of my Admin area, still not working:
public class AutenticarAdminAttribute : AuthorizeAttribute
{
public override void OnAuthorization(AuthorizationContext filterContext)
{
base.OnAuthorization(filterContext);
if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
{
filterContext.Result = new RedirectResult("~/admin/login");
}
}
}
Global.asax: filters.Add(new AutenticarAdminAttribute());
If I remove <authentication mode="Forms" />
from web.config the AuthorizeAttribute
do not do the work, IsAuthenticated
is always true.
And when I put again <authentication mode="Forms" />
in web.config everything is denied.
I'm not able to restrict only a area, how do?
BaseController in Admin Area:
[AutenticarAdmin]
public class BaseController : Controller
{
public BaseController()
{
}
}
DefaultAdminController in Admin Area:
public class DefaultController : BaseController
{
public ActionResult Index()
{
return View();
}
}
Public Controller:
public class DefaultController : Controller
{
public ActionResult Index()
{
return View();
}
}
해결책 2
Remove filters.Add(new AutenticarAdminAttribute());
from your global.asax. Registering global filter it will be the same as put the Attribute in all controllers of your application.
다른 팁
You are overriding OnAuthorization method and inside checking if user is IsAuthenticated.
Authorisation and Authentication are 2 different things !
With regards to authentication, you can set default redirect url and login url in .config file (in authentication tag).
Hope that helps.