views:

30

answers:

2

I have a webserver running IIS 6, .NET MVC with a single domainname. The site uses URL rewriting to produce URLs like:

domain.com/controller/action

I would like to force one (1) controller to use SSL (others should work without SSL). How should I implement this?

A: 

You could annotate controllers that require SSL with the RequireHttps attribute or make them derive from a base controller that's marked with this attribute.

Darin Dimitrov
+2  A: 

Decorate the controller that needs SSL with the RequireHttpsAttribute.

[RequireHttps]
public class SecureController : Controller
{
   ...
}

Although, you may prefer a custom version that ignores this for requests from localhost if you are using Cassini for debugging.

[AttributeUsage( AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false )]
public class RemoteRedirectToHttpsAttribute : RequireHttpsAttribute
{
    public override void OnAuthorization( AuthorizationContext filterContext )
    {
        if (filterContext == null)
        {
            throw new ArgumentNullException( "filterContext" );
        }

        if (filterContext.HttpContext != null && (filterContext.HttpContext.Request.IsLocal || filterContext.HttpContext.Request.IsSecureConnection))
        {
            return;
        }

        filterContext.Result = new RedirectResult( filterContext.HttpContext.Request.Url.ToString().Replace( "http:", "https:" ) );
    }
}
tvanfosson
I use a custom RequireSSL attribute already. However my website (IIS) is not setup for SSL yet. And I'm only able to setup by setting 'Directory security' for the entire website. Or will this **not** automatically disable normal 'http' requests?
Ropstah
@ropstah -- if you use this attribute on a controller/action (from other than a local connection), it will redirect to a secure request. Also, you should note that the initial request really ought to be a GET, not a POST. If the first request to a protected action is a POST, it won't work since the redirect will be a GET to the same url (except using https instead).
tvanfosson
@tvanfosson - I get what you're saying, no problems there. However my real issue is probably setting up SSL in IIS. Does 'setting up SSL' imply that 'normal' `http` (yes not `https`) requests will still work for the website? (except for the attributed controller of course..)
Ropstah
@ropstah - in general, yes, if you have it configured properly you can make both SSL and non-SSL requests to the same web site. With MVC, you'd default to having the site not require SSL, then mark only those actions that require it with the attribute. Note that you need it on both the GET/POST versions of your login actions. The login page needs to be encrypted to prevent man-in-the-middle attacks.
tvanfosson