2012-03-02 57 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