在我的登录方法中,我使用此代码登录用户:
FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
因为我想在需要时避免数据库调用UserId
以及一些其他数据,所以我做了一些事情,但我不太确定我做对了。
所以这就是为什么我需要有人检查我的代码,它是否安全而不是愚蠢:)
我这样做是否违反了一些规则。
这是我网站安全阶段的最后阶段,因为我不再使用会员/角色。
所以我改变了上面的 SetAuth... 代码:
CustomPrincipalSerializeModel serializeModel = new CustomPrincipalSerializeModel();
var usr = userRepository.GetUser(model.UserName);
serializeModel.UserId = usr.UserId;
serializeModel.Username = usr.UserName;
JavaScriptSerializer serializer = new JavaScriptSerializer();
string userData = serializer.Serialize(serializeModel);
FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(
1,
usr.UserName,
DateTime.Now,
DateTime.Now.AddMinutes(30),
model.RememberMe,
userData);
string encTicket = FormsAuthentication.Encrypt(authTicket);
HttpCookie faCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket);
Response.Cookies.Add(faCookie);
在我的Global.asax中,我添加了:
protected void Application_PostAuthenticateRequest(Object sender, EventArgs e)
{
HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];
if (authCookie != null)
{
FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
JavaScriptSerializer serializer = new JavaScriptSerializer();
CustomPrincipalSerializeModel serializeModel = serializer.Deserialize<CustomPrincipalSerializeModel>(authTicket.UserData);
CustomPrincipal newUser = new CustomPrincipal(authTicket.Name);
newUser.UserId = serializeModel.UserId;
newUser.Username = serializeModel.Username;
newUser.FirstName = serializeModel.FirstName;
newUser.LastName = serializeModel.LastName;
HttpContext.Current.User = newUser;
}
}
自定义主体代码 - 对于问题的主要目标可能并不重要:
public interface ICustomPrincipal : IPrincipal
{
int UserId { get; set; }
string Username { get; set; }
string FirstName { get; set; }
string LastName { get; set; }
}
public class CustomPrincipal : ICustomPrincipal
{
public IIdentity Identity { get; private set; }
public bool IsInRole(string role) { return false; }
public CustomPrincipal(string email)
{
this.Identity = new GenericIdentity(email);
}
public int UserId { get; set; }
public string Username { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
public class CustomPrincipalSerializeModel
{
public int UserId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Username { get; set; }
}