首页 > 解决方案 > 使用自动身份验证将登录用户重定向到新网站

问题描述

我有一个用 ASP.NET MVC 5 设计的网站,网站名称为www.oldsite.com.

我们刚刚创建了一个新网站 -www.newsite.com对 ASP.NET MVC 代码进行了一些更改,但两个网站的数据库相同。

当用户登录旧网站时,www.oldsite.com验证登录详细信息(用户名和密码),登录成功后根据某些条件将用户重定向到www.newsite.com自动登录的新网站(用户在登录时无需重新输入用户名和密码页面再次上www.newsite.com)并显示主页www.newsite.com

这是我的代码

int timeout = login.RememberMe ? 600 : 60; // 525600 min = 1 year
var ticket = new FormsAuthenticationTicket(v.PEmailId, login.RememberMe, timeout);

string encrypted = FormsAuthentication.Encrypt(ticket);

var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encrypted);
cookie.Expires = DateTime.Now.AddMinutes(timeout);
cookie.HttpOnly = true;                        

Response.Cookies.Add(cookie);
                 
if (some condition)
{
    return Redirect("www.newsite.com");
}

我需要一些登录身份验证 cookie 代码,我正在使用 ASP.NET 身份。

请告诉我如何www.newsite.com使用登录凭据从旧站点重定向到新站点(在登录页面中提供用户 ID 和密码参数并自动登录到新网站)或如何为新网站创建 cookie 以www.newsite.com在不输入用户 ID 和密码的情况下自动登录。

谢谢

标签: c#asp.netasp.net-mvcasp.net-mvc-5asp.net-identity

解决方案


从旧站点,您可以将用户名和密码作为参数传递。

return Redirect(string.Format("https://newsite.com/Home/Index?username={0}&password={1}","username", "password"));

在新站点中创建一个允许匿名用户的功能。然后验证用户凭据。如果用户是有效的,则添加 cookie 并重定向到您想要的页面。

[AllowAnonymous]
public class HomeController : Controller
{
    public ActionResult Index(string username, string password)
    {
        // validate the user credential
        // add cookie
        User user = new User();
        user.UserName = username;
        user.Password = password;
        AddCookie(user);

        return RedirectToAction("Index", "Dashboard");
    }

    public void AddCookie(User user)
    {
        string encryptTicket, userData;
        HttpCookie httpCookie = null;
        try
        {
            userData = JsonConvert.SerializeObject(user);
            FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
                1, user.UserName, DateTime.Now, DateTime.Now.AddHours(1), true, userData, FormsAuthentication.FormsCookiePath);
            encryptTicket = FormsAuthentication.Encrypt(ticket);
            httpCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptTicket);
            Response.Cookies.Add(httpCookie);
        }
        catch (Exception exception)
        {
        }
        return httpCookie;
    }
}

public class User
{
    public string UserName { get; set; }
    public string Password { get; set; }
}

推荐阅读