/// <summary>
/// 执行用户登录操作
/// </summary>
/// <param name="config">授权配置信息</param>
/// <param name="userData">与登录名相关的用户信息</param>
/// <param name="expiration">登录Cookie的过期时间,单位:分钟,默认120分钟。</param>
public static void SignIn(IovAuthConfig config, UserInfo userData, int expiration = 120)
{
if (config == null)
throw new ArgumentNullException("config");
if (userData == null)
throw new ArgumentNullException("userData");
if(string.IsNullOrWhiteSpace(config.AppID))
throw new ArgumentNullException("AppID");
// 1. 把需要保存的用户数据转成一个字符串。
string data = null;
if (userData != null)
data = JsonHelper.Serialize(userData); // 2. 创建一个FormsAuthenticationTicket,它包含登录名以及额外的用户数据。
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
2, userData.LoginID, DateTime.Now, DateTime.Now.AddDays(1), true, data); // 3. 加密Ticket,变成一个加密的字符串。
string cookieValue = FormsAuthentication.Encrypt(ticket); // 4. 根据加密结果创建登录Cookie
HttpCookie cookie = new HttpCookie(config.AppID, cookieValue);
cookie.HttpOnly = true;
cookie.Secure = FormsAuthentication.RequireSSL;
cookie.Domain = FormsAuthentication.CookieDomain;
cookie.Path = FormsAuthentication.FormsCookiePath;
//if (expiration > 0)
//默认过期时间:120分钟
cookie.Expires = DateTime.Now.AddMinutes(expiration == 0 ? 120 : expiration); HttpContext context = HttpContext.Current;
if (context == null)
throw new InvalidOperationException(); // 5. 写登录Cookie
context.Response.Cookies.Remove(cookie.Name);
context.Response.Cookies.Add(cookie);
}
web.config同时需要修改两个地方,如下:
<system.web>
<authentication mode="Forms">
<forms name="IOV.Test" loginUrl="/" protection="All" timeout="43200" path="/" domain="" requireSSL="false" slidingExpiration="true" />
</authentication>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" />
</system.web>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"></modules>
</system.webServer>
获取已登录用户信息:
/// <summary>
/// 获取当前用户信息
/// </summary>
/// <param name="context">当前Http请求上下文</param>
/// <returns></returns>
public static UserInfo TryGetUserInfo(HttpContext context)
{
if (context == null)
throw new ArgumentNullException("context"); // 1. 读登录Cookie
HttpCookie cookie = context.Request.Cookies[FormsAuthentication.FormsCookieName];
if (cookie == null || string.IsNullOrEmpty(cookie.Value))
return null; try
{
UserInfo userData = null;
// 2. 解密Cookie值,获取FormsAuthenticationTicket对象
FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(cookie.Value); if (ticket != null && string.IsNullOrEmpty(ticket.UserData) == false)
// 3. 还原用户数据
userData = JsonHelper.Desrialize<UserInfo>(ticket.UserData); return userData;
}
catch { /* 有异常也不要抛出,防止攻击者试探。 */ }
return null;
}