单点登录网站 - MVC 3

时间:2012-03-02 15:10:30

标签: asp.net-mvc asp.net-mvc-3

我有两个网站,我使用相同的cookie登录,工作正常。

我遇到的问题是两个网站在设计上完全不同,我希望其中一个网站能够处理登录功能,而另一个网站只需要在另一个网站上发布用户名/密码的帖子。在后端创建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();

2 个答案:

答案 0 :(得分: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();
}

但是使用通用身份验证服务似乎是一个更好的主意,而不是屏幕抓取。

答案 1 :(得分:0)

假设使用相同的cookie域,您可以简单地使用ajax请求将凭据发送到其他站点。如果成功,您的控制器将返回ajax结果。查看MVC4模板,因为它们提供了ajax样式登录。