2012-03-02 114 views
1

我有兩個網站,我使用相同的cookie登錄,它工作正常。單點登錄網站 - MVC 3

我遇到的問題是這兩個網站在設計上看起來完全不同,我希望其中一個網站處理登錄功能,另一個只需將用戶名/密碼發佈到另一個網站並在後端創建cookie。

我有這個功能,但問題是如何通知其他網站,登錄已成功或失敗,實際上沒有去其他網站完成登錄過程?

我已經創建了類似這樣的工作正常,但這是我應該如何處理另一個網站上的帖子以及我應該返回的問題作爲回答困惑我的問題。

任何想法或替代解決方案都會對我有很大幫助!

[HttpPost] 
public ActionResult FormPost(LogOnModel model) 
{ 
WebRequest request = WebRequest.Create(strServer); 

      // Set the Method property of the request to POST. 
      request.Method = "POST"; 
      // Create POST data and convert it to a byte array. 
      byte[] byteArray = Encoding.UTF8.GetBytes("password=" + model.Password); 
      // Set the ContentType property of the WebRequest. 
      request.ContentType = "application/x-www-form-urlencoded"; 
      // Set the ContentLength property of the WebRequest. 
      request.ContentLength = byteArray.Length; 
      // Get the request stream. 
      Stream dataStream = request.GetRequestStream(); 
      // Write the data to the request stream. 
      dataStream.Write(byteArray, 0, byteArray.Length); 
      // Close the Stream object. 
      dataStream.Close(); 

      // Get the response. 
      WebResponse response = request.GetResponse(); 
      // Get the stream containing content returned by the server. 
      dataStream = response.GetResponseStream(); 
      // Open the stream using a StreamReader for easy access. 
      StreamReader reader = new StreamReader(dataStream); 
      // Read the content. 
      string responseFromServer = reader.ReadToEnd(); 
      // Clean up the streams. 
      reader.Close(); 
      dataStream.Close(); 
      response.Close(); 

TempData["Response"] = responseFromServer; 

return View(); 
+1

聽起來像您可以從共享的[WebService](http://msdn.microsoft.com/zh-cn/library/t745kdsh.aspx)中受益。 – jrummell 2012-03-02 15:13:24

回答

1

你可以捕捉由該認證行動所發送的cookie,並簡單地把它們添加到響應,使得執行請求的實際用戶得到這個cookie在他的瀏覽器:

[HttpPost] 
public ActionResult FormPost(LogOnModel model) 
{ 
    using (var client = new WebClient()) 
    { 
     var data = new NameValueCollection 
     { 
      { "username", "foo" }, 
      { "password", "bar" }, 
     }; 
     var result = client.UploadValues("http://localhost:1631/account/logon", data); 
     var cookie = client.ResponseHeaders[HttpResponseHeader.SetCookie]; 
     Response.AddHeader("Set-Cookie", cookie); 
    } 
    return View(); 
} 

但使用通用認證服務似乎是一個更好的主意,而不是做屏幕抓取。

0

您可以簡單地使用ajax請求將憑證發送到其他站點,假設使用相同的cookie域。你的控制器如果成功會返回一個ajax結果。查看MVC4模板,因爲它們提供了ajax樣式的登錄。

+0

我在想這樣,但我想保留在後端。基本所有我需要傳回來的是一個我可以處理的字符串。如何做到這一點不確定? – Sparkle 2012-03-02 16:08:31

+0

查看mvc4模板 - 只需使用jquery .ajax()調用並指定post方法,即可查看:http://stackoverflow.com/questions/7296470/how-to-login-through-ajax-in-asp -net-MVC -3- – 2012-03-02 17:14:52