![](/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.