Search code examples
asp.net-mvchttp-redirectsslfluent-security

How do you use Fluent Security to Setup SSL Redirection in an ASP.net MVC application?


What is the best way to use Fluent Security to setup SSL Redirection on Controllers' Views within an mvc web app?


Solution

  • The best way is to create a custom Policy and Policy Handler. Here is how I completed it:

    My Custom Policy

    public class RequireSslPolicy : ISecurityPolicy
    {
        public PolicyResult Enforce(ISecurityContext context)
        {
            var req = HttpContext.Current.Request;
            if (!req.IsSecureConnection && !req.IsLocal)
                return PolicyResult.CreateFailureResult(this, "A Secure Connection is Required.");
            return PolicyResult.CreateSuccessResult(this);
        }
    }
    

    My Custom Policy Handler

    public class RequireSslPolicyViolationHandler : IPolicyViolationHandler
    {
        public ActionResult Handle(PolicyViolationException exception)
        {
            var req = HttpContext.Current.Request;
            var url = req.Url.ToString().ToLower().Replace("http:", "https:");
            return new RedirectResult(url);
        }
    }
    

    Code to add the Policy to a Controller or Actions within a Controller

    c.For<AccountController>().AddPolicy<RequireSslPolicy>();
    

    And that'it! Of course you need to make sure that you are configuring your Dependency Injection correctly and following the Fluent Security naming conventions. But once those are correct, you should see that this code works perfectly!