AllowAnonymous attribute make Authorize ignored - asp.net-mvc

I've a admin dashboard project that need global authorization and I set it up on
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new AuthorizeAttribute());
}
That code make all my controller is being authorize.. And there is a controller that has [AllowAnonymous] attribute.. However I've sudden change request that an action on this controller need to be authorize..
[AllowAnonymous]
public class AuthController : Controller
{
[Authorize(Roles = "Admin")]
public ActionResult BumbaSection()
{
return View();
}
}
This is not working, I still can access this BumbaSection action.. Any idea?
Thanks

After I peek the authorize code, This part of code make the authorize not working :
public virtual void OnAuthorization(AuthorizationContext filterContext)
{
//code here
if (filterContext.ActionDescriptor.IsDefined(typeof (AllowAnonymousAttribute), true) || filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof (AllowAnonymousAttribute), true))
return;
//code here
}
Override this piece of code in authorize attribute class and my code is start working.. Maybe this will usefull for who that have some problem with me

Related

Authorize attribute on HomeController forces login on AllowAnonymous controller

The HomeController of my mvc 5 application has an [Authorize] attribute
[Authorize]
public class HomeController : Controller
The SimpleController is the followin (a simple test):
[AllowAnonymous]
public class SimpleController : Controller
{
// GET: Simple
public ActionResult Index()
{
return View();
}
}
Why do I have to log in when I browse straight to http://url/simple/index?
I have to extra "force authentication code" or filters registered.
When I remove the [Authorize] on the HomeController, the SimpleController works fine, without the need to log in
You may have configured Global Authorization filter in FilterConfig.cs, located in App_Start folder
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new AuthorizeAttribute());
}
}

MVC Set accessibility level on a method called from ajax

I would like to protect my public method from being called by a user.
Because I'm calling the action from an ajax script I can't use any access modifiers, (private, protected etc).
Also, [HttpPost] doesn't stop the user from doing a fake request.
Anyone got a solution?
Thanks
Create an action filter that allows action methods to be called by AJAX only
namespace MyFilters
{
[AttributeUsage(AttributeTargets.Method)]
public class AjaxOnlyAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (!filterContext.HttpContext.Request.IsAjaxRequest())
{
filterContext.HttpContext.Response.StatusCode = 404;
filterContext.Result = new HttpNotFoundResult();
}
else
{
base.OnActionExecuting(filterContext);
}
}
}
}
Then apply this to the action method
[AjaxOnly]
public JsonResult DoSomething()
{
....

How to validate credential in MVC and redirect to bad login page

I want to centralize authentication that developers are free to worry about the implementation of security.
I dont want to validate the authentication at each request like
public class HomeController : BaseController
{
public ActionResult Home()
{
if (Request.IsAuthenticated == true)
{
return RedirectToAction("Home", "Member");
}
return View();
}
public ActionResult Resources()
{
if (Request.IsAuthenticated == true)
{
return RedirectToAction("Resources", "Member");
}
return View();
}
}
Thanks
You can centralized your credential validation by using a BaseController for all your controller inside your application
public class BaseSupplierFlyersController : BaseController
{
//
// GET: /SupplierFlyers/
public ActionResult Index(string culture)
{
//Some action logic here
return View("Index");
}
}
In your BaseControler
public class BaseController : Controller
{
private bool IsLoged = false;
public BaseController()
: base()
{
}
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (!IsLoged)
{
//Redirection du bad login.
//Affect the Result to cancelled previous Action execution
filterContext.Result = new RedirectResult(string.Concat("~/", ControllerConstants.Error,"/", ActionConstants.BadLogin));
}
base.OnActionExecuting(filterContext);
}
protected override void Execute(RequestContext requestContext)
{
//Validate Credential
ValidateCredential(requestContext);
//Traitement standard
base.Execute(requestContext);
}
private void ValidateCredential(RequestContext requestContext)
{
//Logic to validate credential here
IsLoged = true; //or false
}
}
Each time an Action from a Controller is fired the BaseController will validate credential in Execute method and in OnActionExecuting you can valide if the credential are valid and than take an Action like Redirect to an other page.
Looking at the code you wrote it seems like you are missing Action Filters that are part of asp.net mvc. There is one built in called Authorize that basically requires a request to be authenticated before the controller method is invoked, but creating your own is very simple.
Also in asp.net mvc 3 you can define global filters which will be part of every action invoked on your controllers. You can find some samples here

asp.net MVC antiforgerytoken on exception RedirectToAction

I have implimented the AnitforgeryToken with my asp.net MVC forms, and also added the attribute to my login procedure, however when the check failes i wish to redirect to my fraud action rather than an exception page. is this possible within the attribute ????
thanks
In case you do not want to put [HandleError] attribute on all actions that have [ValidateAntiForgeryToken], you may add a custom filter to your Global filters:
in Global.asax under Application_Start():
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
and then:
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
filters.Add(new AntiForgeryTokenFilter());
}
}
AntiForgeryTokenFilter.cs:
public class AntiForgeryTokenFilter : FilterAttribute, IExceptionFilter
{
public void OnException(ExceptionContext filterContext)
{
if(filterContext.Exception.GetType() == typeof(HttpAntiForgeryException))
{
filterContext.Result = new RedirectResult("/"); // whatever the url that you want to redirect to
filterContext.ExceptionHandled = true;
}
}
}
The ValidateAntiForgeryTokenAttribute will just throw HttpAntiForgeryException. You could use the HandleErrorAttribute to handle this scenario:
[HandleError(
ExceptionType = typeof(HttpAntiForgeryException),
View = "Unauthorized")]
[ValidateAntiForgeryToken]
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult SomeActionThatRequiresToken()
{
return View();
}

ASP.NET MVC RequireHttps

How do I use the ASP.NET MVC 2 Preview 2 Futures RequireHttps attribute?
I want to prevent unsecured HTTP requests from being sent to an action method. I want to automatically redirect to HTTPS.
MSDN:
RequireHttpsAttribute
RequireHttpsAttribute Members
RequireHttpsAttribute.HandleNonHttpsRequest Method
How do I use this feature?
I think you're going to need to roll your own ActionFilterAttribute for that.
public class RedirectHttps : ActionFilterAttribute {
public override void OnActionExecuting(ActionExecutingContext filterContext) {
if (!filterContext.HttpContext.Request.IsSecureConnection) {
filterContext.Result =
new RedirectResult(filterContext.HttpContext.Request.Url.
ToString().Replace("http:", "https:"));
filterContext.Result.ExecuteResult(filterContext);
}
base.OnActionExecuting(filterContext);
}
}
Then in your controller :
public class HomeController : Controller {
[RedirectHttps]
public ActionResult SecuredAction() {
return View();
}
}
You might want to read this as well.
My guess:
[RequireHttps] //apply to all actions in controller
public class SomeController
{
//... or ...
[RequireHttps] //apply to this action only
public ActionResult SomeAction()
{
}
}

Resources