参考sharing cookie in subdomains我实施了jro的答案,它适用于登录。(在不同的子域中共享cookie)
但是,此更改会影响退出流程。请参阅下面分享的SignOut和SignIn代码。
问题是,在注销过程中,它会执行FormsAuthentication.SignOut,然后重定向到登录控制器,但即使在注销过程中调用FormsAuthentication.SignOut,"System.Threading.Thread.CurrentPrincipal.Identity.IsAuthenticated"
也会设置为true。
设置表单身份验证Cookie的代码
public static HttpCookie GetAuthenticationCookie(CookieData cookieData)
{
string userData = PrepareCookieContentFromCookieData(cookieData); //Get a string with User data
AuthenticationSection section = WebConfigurationManager.GetWebApplicationSection("system.web/authentication") as AuthenticationSection;
TimeSpan ts = section.Forms.Timeout;
int timeout = (ts.Minutes != 0) ? timeout = ts.Minutes : 1;
bool isPersistent = Convert.ToBoolean(HttpContext.Current.Request.Form["isPersistent"] ?? "False");
if (isPersistent) timeout = 30 * 24 * 60;
//ticket object is formed based on the above details set. Evry page afer login will use this ticket to get base user data
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, cookieData.userName, DateTime.Now,
DateTime.Now.AddMinutes(timeout), isPersistent, userData, FormsAuthentication.FormsCookiePath);
// to encrypt the ticket
string encryptedCookieString = FormsAuthentication.Encrypt(ticket);
// setting the ticket to the cookie.
var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedCookieString);
cookie.HttpOnly = true;
cookie.Domain = "parent.com";
if (isPersistent)
cookie.Expires = DateTime.Now.AddYears(1);
return cookie;
}
退出
public ActionResult SignOut()
{
if (HttpContext != null && HttpContext.Session != null)
{
HttpContext.Session.Abandon();
}
FormsAuthentication.SignOut();
}
return RedirectToAction("SignIn", "User");
}
登入
public ActionResult SignIn(string CompanyCode)
{
//Check if logged in
if (System.Threading.Thread.CurrentPrincipal.Identity.IsAuthenticated)
{
//return to a specific page
}
}
感谢您的任何帮助。
答案 0 :(得分:0)
您必须在SignOut方法中将CurrentPrincipal和用户设置为null
public class LogOffController : Controller
{
public ActionResult Index()
{
FormsAuthentication.SignOut();
HttpContext.User = null;
Thread.CurrentPrincipal = null;
return View();
}
}
希望这有帮助。
答案 1 :(得分:0)
解决了这个问题。如果手动设置域名,则必须从webconfig窗体身份验证设置中设置域名。否则它将尝试清除默认域(在我的情况下为subapp1.parent.com)中的cookie,因为我手动覆盖了cookie域,因此没有这样的cookie。
我的表单身份验证设置如下
<forms cookieless="UseCookies" defaultUrl="~/Applications" loginUrl="~/user/signin" name="FormAuthentication" path="/"/>
然后我添加了domain=".parent.com"
作为域,它开始工作。
以下是我诊断问题的方法,
我尝试按照代码在注销时手动删除任何Cookie,
var cookie = HttpContext.Request.Cookies[FormsAuthentication.FormsCookieName];
if (cookie != null)
{
Logger.Log.InfoFormat("Cookies found. Domain:{0} Name:{1}", cookie.Domain, cookie.Name);
cookie.Expires = DateTime.Now.AddYears(-1);
Response.Cookies.Add(cookie);
}
问题仍然存在。但我记录了(log4net)cookie.Domain以获取详细信息。令人惊讶的是,域名是空的,我期待“parent.com”。然后我检查了表单身份验证设置,并发现域名未设置在那里。
希望这有助于为某人节省几个小时!