c# - 使用自动身份验证将登录用户重定向到新网站
问题描述
我有一个用 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 和密码的情况下自动登录。
谢谢
解决方案
从旧站点,您可以将用户名和密码作为参数传递。
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; }
}
推荐阅读
- c++ - 如何删除在另一个函数中初始化的动态分配数组?
- azure - 订阅 Azure 云合作伙伴门户
- javascript - 如何用 dygraphs 显示所有月份?
- java - 为什么从 Eclipse 运行时,此代码列出包中的类,但不在 JAR 中?
- python - 转换 pandas 中的 datetimeindex 对象
- java - java - 如何使用java中的一到两行代码将给定的Before链接转换为After链接?
- visual-studio - 如何在 Visual Studio 中编辑监视窗口以放大或使用更大的文本?
- javascript - 无法将 tflite 模型添加到 React Native 项目
- regex - Chrome 网络请求选项卡中的正则表达式搜索
- jsf - 如何使用切换器素面隐藏组列