- public class UserInfo : IPrincipal
- {
- public int UserId;
- public int GroupId;
- public string UserName;
- // 如果还有其它的用户信息,可以继续添加。
- public override string ToString()
- {
- return string.Format("UserId: {0}, GroupId: {1}, UserName: {2}, IsAdmin: {3}",
- UserId, GroupId, UserName, IsInRole("Admin"));
- }
- #region IPrincipal Members
- [ScriptIgnore]
- public IIdentity Identity
- {
- get { throw new NotImplementedException(); }
- }
- public bool IsInRole(string role)
- {
- if( string.Compare(role, "Admin", true) == 0 )
- return GroupId == 1;
- else
- return GroupId > 0;
- }
- #endregion
- }
注意:表示用户信息的类型并不要求一定要实现IPrincipal接口,如果不需要用户组的判断,可以不实现这个接口。
登录时需要调用的方法(定义在MyFormsPrincipal类型中):
- /// <summary>
- /// 执行用户登录操作
- /// </summary>
- /// <param name="loginName">登录名</param>
- /// <param name="userData">与登录名相关的用户信息</param>
- /// <param name="expiration">登录Cookie的过期时间,单位:分钟。</param>
- public static void SignIn(string loginName, TUserData userData, int expiration)
- {
- if( string.IsNullOrEmpty(loginName) )
- throw new ArgumentNullException("loginName");
- if( userData == null )
- throw new ArgumentNullException("userData");
- // 1. 把需要保存的用户数据转成一个字符串。
- string data = null;
- if( userData != null )
- data = (new JavaScriptSerializer()).Serialize(userData);
- // 2. 创建一个FormsAuthenticationTicket,它包含登录名以及额外的用户数据。
- FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
- 2, loginName, DateTime.Now, DateTime.Now.AddDays(1), true, data);
- // 3. 加密Ticket,变成一个加密的字符串。
- string cookieValue = FormsAuthentication.Encrypt(ticket);
- // 4. 根据加密结果创建登录Cookie
- HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, cookieValue);
- cookie.HttpOnly = true;
- cookie.Secure = FormsAuthentication.RequireSSL;
- cookie.Domain = FormsAuthentication.CookieDomain;
- cookie.Path = FormsAuthentication.FormsCookiePath;
- if( expiration > 0 )
- cookie.Expires = DateTime.Now.AddMinutes(expiration);
- HttpContext context = HttpContext.Current;
- if( context == null )
- throw new InvalidOperationException();
- // 5. 写登录Cookie
- context.Response.Cookies.Remove(cookie.Name);
- context.Response.Cookies.Add(cookie);
- }
这