How do I enable ssl for all controllers in mvc application - asp.net-mvc

I have a MVC 5 app and I installed the ssl certificate and I'm now connecting with https, but in my code I had to set the '[requirehttps]' attribute on the homecontroller like so:
[RequireHttps]
public class HomeController : Controller
{}
Isn't there a way to set it for the whole application so I don't have to do this for each and every controller I have in the app?

Use the RegisterGlobalFilters method in your FiltersConfig.
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
filters.Add(new RequireHttpsAttribute());
}
}

The [RequireHttps] attribute is inherited, so you could create a base controller, apply the attribute to that, and then derive all your controllers from that base.
[RequireHttps]
public abstract class BaseController : Controller
{}
public class HomeController : BaseController
{}
public class FooController : BaseController
{}

Related

AllowAnonymous attribute make Authorize ignored

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

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());
}
}

Is it possible to decorate a class or action to ignore a global attribute such as AuthorizeAttribute?

I am using MVC3, ASP.NET4.5, C# and Razor.
I would like to set an attribute globably ie AuthorizeAttribute. However I need to ensure that some classes and/or actions ignore this global setting. Is it possible to decorate a class and/or action to ensure this, and if so how?
Many thanks.
You can use the [AllowAnonymous] attribute (which is the default in ASP.NET MVC) to override your [Authorize] attribute
Assuming you have added your customized authorization logic to the default FilterConfig class:
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
filters.Add(new MyCustomAuthorizationAttribute());
}
}
You can override that setting by decorating your controllers/action methods with [AllowAnonymous]:
// To allow anonymous access to all action methods
[AllowAnonymous]
public class MyController : Controller
{
// Only allow the Index action method to be called anonymously
[AllowAnonymous]
public ActionResult Index()
{
}
}

AuthorizeAttribute, constructors, and stopping dependency injection

I have this (simplified) controller setup:
[CustomAuthorizeAttribute]
public class MainController : Controller {}
public class AccountController : MainController
{
private IService _iService;
public AccountController()
{
_service = DependencyFactory.Resolve<IService>(SessionManager.ServiceKey)
}
public AccountController(IService service)
{
_service = service;
}
}
And CustomAuthorizeAttribute looks something like:
public CustomAuthorizeAttribute : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
bool serviceKeyIsGood = CheckServiceKey(SessionManager.ServiceKey);
return serviceKeyIsGood;
}
}
The goal is to only have the account controller run if the user is authenticated, as defined by the presence of a "good" service key.
The problem I'm having is that the constructor for AccountController runs before OnAuthorize runs which causes the service to blow up (by design) since its service key is bad.
What's the best way to manage this? I'd like to take advantage of the simplicity of the CustomAuthorizeAttribute, and I have to avoid re-architecting the way our services are instantiated. (And the dependency factory is necessary as MVC complains about now having parameterless constructors.)
You can use injection of factorymethod instead of service itself:
[CustomAuthorizeAttribute]
public class MainController : Controller
public class AccountController : MainController
{
private Func<IService> _serviceFactory;
public AccountController()
{
_serviceFactory= DependencyFactory.Resolve<Func<IService>>(SessionManager.ServiceKey)
}
public AccountController(Func<IService> serviceFactory)
{
_serviceFactory= serviceFactory;
}
}
and use: to get service: service = _serviceFactory() when you need it.
PS: I recommend you to use standard methods for DI in MVC (controller factory or internal dependency resolver) to avoid code such _serviceFactory= DependencyFactory.Resolve<Func<IService>>(SessionManager.ServiceKey)

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