![](/img/trans.png)
[英]Programmatically login to a website and redirect the user to the logged in page?
[英]Redirect logged in user to new website with automatic authentication
我在 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");
}
我需要一些登录验证 cookies 代码,我使用的是 ASP.NET 身份。
请告诉我如何使用登录凭据从旧网站重定向到新网站www.newsite.com
(在登录页面中提供用户 ID 和密码参数并自动登录新网站)或如何为新网站www.newsite.com
创建 cookies无需输入用户名和密码即可自动登录。
谢谢
从旧站点,您可以将用户名和密码作为参数传递。
return Redirect(string.Format("https://newsite.com/Home/Index?username={0}&password={1}","username", "password"));
在新站点中创建一个允许匿名用户的 function。 然后验证用户凭据。 如果用户是有效的,则添加 cookies 并重定向到您想要的页面。
[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; }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.