Solution actually used (in as ASP.NET MVC project using OpenID):
I have an AccountController which I use to log users in and out and these methods are there.
#region Methods to log in a user.
/// <summary>
/// Create the auth cookie in the same way it is created my ASP.NET Membership system, hopefully lasting for more than 20 minutes.
///
/// For more information check out http://stackoverflow.com/questions/2122831/is-it-possible-to-use-aspxauth-for-my-own-logging-system
/// </summary>
/// <param name="userId">Id of the user that is logged in</param>
/// <returns>Cookie created to mark the user as authenticated.</returns>
private static HttpCookie CreateAuthCookie(int userId) {
DateTime issued = DateTime.Now;
// formsAuth does not expose timeout!? have to hack around the spoiled parts and keep moving..
HttpCookie fooCookie = FormsAuthentication.GetAuthCookie("foo", true);
int formsTimeout = Convert.ToInt32((fooCookie.Expires - DateTime.Now).TotalMinutes);
DateTime expiration = DateTime.Now.AddMinutes(formsTimeout);
var ticket = new FormsAuthenticationTicket(0, userId.ToString(), issued, expiration, true, "", FormsAuthentication.FormsCookiePath);
return CreateAuthCookie(ticket, expiration, true);
}
/// <summary>
/// Create an auth cookie with the ticket data.
/// </summary>
/// <param name="ticket">Ticket containing the data to mark a user as authenticated.</param>
/// <param name="expiration">Expriation date for the cookie.</param>
/// <param name="persistent">Whether it's persistent or not.</param>
/// <returns>Cookie created to mark the user as authenticated.</returns>
private static HttpCookie CreateAuthCookie(FormsAuthenticationTicket ticket, DateTime expiration, bool persistent) {
string encryptedAuthData = FormsAuthentication.Encrypt(ticket);
var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedAuthData) {
Domain = FormsAuthentication.CookieDomain,
Path = FormsAuthentication.FormsCookiePath
};
if (persistent) {
cookie.Expires = expiration;
}
return cookie;
}
/// <summary>
/// Expire the authentication cookie effectively loging out a user.
/// </summary>
private void ExpireAuthCookie() {
var cookie = new HttpCookie(FormsAuthentication.FormsCookieName);
cookie.Expires = DateTime.Now.AddDays(-1);
Response.Cookies.Add(cookie);
}
#endregion
本文来自电脑杂谈,转载请注明本文网址:
http://www.pc-fly.com/a/jisuanjixue/article-51660-6.html
低收入者可合娶老婆----浙江财经学院教授谢作诗
只有他不像那样耍赖坐滩
各种复杂添加剂