我正在使用aspx和c#来设置登录认证cookie。
FormsAuthentication.SetAuthCookie(UserName, True)
我希望在同一个cookie中存储更多的信息。我可以向该身份验证cookie添加值,还是必须使用第二个http cookie?
基本上,我想要存储用户的Id
,以便我可以使用用户表行键访问数据库。
谢谢, Eden
我正在使用aspx和c#来设置登录认证cookie。
FormsAuthentication.SetAuthCookie(UserName, True)
我希望在同一个cookie中存储更多的信息。我可以向该身份验证cookie添加值,还是必须使用第二个http cookie?
基本上,我想要存储用户的Id
,以便我可以使用用户表行键访问数据库。
谢谢, Eden
查看 这个问题 以获取更多信息
只要对你有用,你可以在auth cookie中放入任何内容。但是,如果你要存放敏感信息,至少应该加密,但我建议不要将敏感信息放在那里。你可以这样做:
Forms.SetAuthCookie (UserName + "|" + UserId, true);
然后,每当您需要用户名或用户ID时,它就在那里。只需加载Cookie并解析出所需的值即可。public int CurrentUserId
{
get
{
int userId = 0;
if (HttpContext.Current.Request.IsAuthenticated)
{
userId = Convert.ToInt32(HttpContext.Current.User.Identity.Name.Split('|')[1]);
}
return userId;
}
}
public string CurrentUserName
{
get
{
string userName = string.Empty;
if (HttpContext.Current.Request.IsAuthenticated)
{
userName = HttpContext.Current.User.Identity.Name.Split('|')[0];
}
return userName;
}
}
使用 "|" 来添加更多信息是明智的做法。如果微软有另一个重载方法
public static void SetAuthCookie(String userName, bool createPersistentCookie, string userData)`
将用户ID作为userName参数传递。
FormsAuthentication.SetAuthCookie(userId, True)
您可以将额外的信息存储在FormsAuthenticationTicket
的UserData
属性中:
using Newtonsoft.Json;
using System.Web;
using System.Web.Security;
public class LoggedInUser
{
public string FirstName { get; set; } = null;
public bool IsAdmin { get; set; } = false;
}
public static class Authentication
{
static void SignIn(
HttpContextBase context,
string emailAddress,
bool rememberMe,
LoggedInUser user = null)
{
var cookie = FormsAuthentication.GetAuthCookie(
emailAddress.ToLower(),
rememberMe);
var oldTicket = FormsAuthentication.Decrypt(cookie.Value);
var newTicket = new FormsAuthenticationTicket(
oldTicket.Version,
oldTicket.Name,
oldTicket.IssueDate,
oldTicket.Expiration,
oldTicket.IsPersistent,
JsonConvert.SerializeObject(user ?? new LoggedInUser()));
cookie.Value = FormsAuthentication.Encrypt(newTicket);
context.Response.Cookies.Add(cookie);
}
static void SignOut(HttpContextBase context)
{
FormsAuthentication.SignOut();
}
static LoggedInUser GetLoggedInUser()
{
if (HttpContext.Current.User?.Identity?.Name != null && HttpContext.Current.User?.Identity is FormsIdentity identity)
return JsonConvert.DeserializeObject<LoggedInUser>(identity.Ticket.UserData);
return new LoggedInUser();
}
}