我试图在ASP.NET MVC 4应用程序中创建自己的FormsAuthentication
,我看到了创建我的authcookie的两种不同方式,我想知道其中一个是否有任何缺点或是否安全在我决定使用巫婆之前,我是否应该同时使用它们?
第一个是
FormsAuthentication.SetAuthCookie(userName, rememberMe);
另一个有点长
var authTicket = new FormsAuthenticationTicket(
1,
userName,
DateTime.Now,
DateTime.Now.AddMinutes(30),
rememberMe,
"Users"
);
var encryptedTicket = FormsAuthentication.Encrypt(authTicket);
var authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
HttpContext.Current.Response.Cookies.Add(authCookie);
请赐教我这个决定
答案 0 :(得分:3)
实际上,第一种方法调用第二种方法。我已经采用了SetAuthCookie
的来源来展示这一点,但删除了一些线以保持相关性:
public static void SetAuthCookie(string userName, bool createPersistentCookie)
{
FormsAuthentication.Initialize();
FormsAuthentication.SetAuthCookie(userName, createPersistentCookie, FormsAuthentication.FormsCookiePath);
}
public static void SetAuthCookie(string userName, bool createPersistentCookie, string strCookiePath)
{
(...)
HttpCookie authCookie = FormsAuthentication.GetAuthCookie(userName, createPersistentCookie, flag ? "/" : strCookiePath, !flag);
(...)
HttpContext.Current.Response.Cookies.Add(authCookie);
(...)
}
private static HttpCookie GetAuthCookie(string userName, bool createPersistentCookie, string strCookiePath, bool hexEncodedTicket)
{
(...)
DateTime utcNow = DateTime.UtcNow;
DateTime expirationUtc = utcNow.AddMinutes((double) FormsAuthentication._Timeout);
FormsAuthenticationTicket ticket = FormsAuthenticationTicket.FromUtc(2, userName, utcNow, expirationUtc, createPersistentCookie, string.Empty, strCookiePath);
string str = FormsAuthentication.Encrypt(ticket, hexEncodedTicket);
(...)
HttpCookie httpCookie = new HttpCookie(FormsAuthentication.FormsCookieName, str);
(...)
return httpCookie;
}
答案 1 :(得分:1)
第二个是最好的..因为你可以发送用户数据,设置过期时间等。
我也只使用它...它运作良好..