2014-06-12 47 views
0

我需要在用戶登錄後在一個MVC 4應用程序中強制執行ssl連接。 我在Login操作上使用了[RequireHttps]屬性,但用戶仍然能夠使用http協議如果他手動將協議設置爲http。 如何避免這種情況? 我不希望每次都強制在整個網站上使用SSL,而只是在登錄頁面和用戶登錄時註銷後,他應該使用http協議重定向到主頁在MVC中登錄後強制HTTPS

+0

爲什麼你不想在整個網站上強制使用SSL? –

+0

對於 – dot404

回答

0

閱讀您的評論,您最好通過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,如果你能夠的話。在大多數情況下,安全優勢大大超過了非常小的性能影響。

+0

謝謝你的回覆性能,控制器是相似的,但問題是訪問其他控制器和動作不具備[RequireHttps]屬性 – dot404

+0

@當dot404你要求,以確保其他操作都在HTTP? –

+0

假設用戶已登錄,然後他需要訪問products/details/id url。即使他登錄了,他也能夠手動從https中刪除s,並且無需ssl即可訪問該鏈接。當沒有登錄這個行動應該訪問低谷 – dot404