在用户登录后,我需要在一个MVC 4应用程序中强制使用ssl连接。我在Login操作中使用了RequireHttps属性,但是如果用户手动将协议设置为http,则仍然能够使用http协议导航。如何避免这种情况?我不想每次都在整个站点上强制SSL,只是在登录页面和用户登录时。在他登出后,应该用http协议重定向到主页。
发布于 2014-06-12 14:35:24
在阅读了您的评论之后,您最好只是通过HTTPS发送所有的流量,而不是选择是否应该使用HTTPS,这取决于它们是否登录。
但是,如果您还想要扩展RequireHttpsAttribute,请尝试
public class RequireUserHttpsAttribute : RequireHttpsAttribute
{
public override void OnAuthorization(AuthorizationContext filterContext)
{
if (filterContext == null)
{
throw new ArgumentNullException("filterContext");
}
if (!filterContext.HttpContext.Request.IsSecureConnection && filterContext.HttpContext.User.Identity.IsAuthenticated)
{
HandleNonHttpsRequest(filterContext);
}
}
}您可能希望将其添加为全局筛选器,这样它就可以在每个请求上运行。如果用户没有登录,它也不会处理HTTP重定向,但是添加一个条件来处理重定向回HTTP应该非常容易。
同样,您将花费更多的时间来实现这一点,而不仅仅是将所有流量推到HTTPS。
我有种感觉,您有一个登录控制器,如下所示:
public class LoginController : Controller {
public ActionResult Login() {
// something here
return View();
}
[RequireHttps, HttpPost]
public ActionResult Login(FormCollection form) {
// test login
return RedirectToAction("/");
}
}注意,原始的Login操作没有RequireHttps属性。试一试:
[RequireHttps] // put it here to make the entire controller HTTPS
public class LoginController : Controller {
[RequireHttps] // or here
public ActionResult Login() {
// something here
return View();
}
[RequireHttps, HttpPost]
public ActionResult Login(FormCollection form) {
// test login
return RedirectToAction("/");
}
}但是,如果能够的话,我会强烈鼓励您在整个应用程序中使用HTTPS。在大多数情况下,安全性的好处远远超过了非常小的性能打击。
https://stackoverflow.com/questions/24186859
复制相似问题