using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Security;
using System.Web;
using System.Security.Principal;
using System.Configuration;
using System.Reflection;
namespace Bowin.Common
{
public class FormsAuthenticationHelper
{
///
/// 创建登陆票据和存cookie
/// 用于登陆成功后标记已登陆和用户信息
///
/// 当前httpContext
/// 系统cookie名字
/// 用户信息和CustomPrincipal对应
///
public bool loginFormsAuthentication(HttpContextBase httpContext, string cookieName, List luserData)
{
bool result = false;
try
{
FormsAuthenticationTicket authTicket;
authTicket = new FormsAuthenticationTicket(
1, //version
luserData[0], //loginID
DateTime.Now, // creation
DateTime.Now.Add(FormsAuthentication.Timeout),//expired time
false, //Persistent
string.Join("|", luserData));
//加密authTicket
string data = FormsAuthentication.Encrypt(authTicket);
HttpCookie cookies = new HttpCookie(cookieName, data);
cookies.Domain = FormsAuthentication.CookieDomain;
cookies.Secure = false;
cookies.Path = FormsAuthentication.FormsCookiePath;
cookies.Expires = authTicket.Expiration;
httpContext.Response.Cookies.Add(cookies);
result = true;
}
catch (Exception ex)
{
result = false;
}
return result;
}
///
/// 在Global.asax的Application_AuthenticateRequest事件使用
/// 把客户端cockie解密存放于Page.User.(CustomPrincipal)对象
///
/// 当前httpContext
/// 系统cookie名字
/// 排除掉需要验证登陆的url关健词
/// 必须要验证登陆的url关健词
public void AuthenticateRequest(HttpContext httpContext, string cookieName, List l_unvalidateUrl, List l_validateUrl = null)
{
HttpCookie authCookie = httpContext.Request.Cookies[cookieName];
if (authCookie == null)
{
string rurl = httpContext.Request.Path.ToLower();
l_unvalidateUrl.Add(FormsAuthentication.LoginUrl.TrimStart('~'));
if ((l_validateUrl != null && l_validateUrl.Any(w => rurl.IndexOf(w.ToLower()) >= 0))
|| !l_unvalidateUrl.Where(w => rurl.IndexOf(w.ToLower()) >= 0).Any())
{
httpContext.Response.Redirect(FormsAuthentication.LoginUrl + "?targetUrl=" + httpContext.Server.UrlEncode(httpContext.Request.Url.AbsoluteUri));
}
return;
}
FormsAuthenticationTicket authTicket = null; //票椐
try
{
authTicket = System.Web.Security.FormsAuthentication.Decrypt(authCookie.Value); // Cookie 解密
}
catch (Exception ex)
{
//cookie解密报错清除
authCookie.Expires = DateTime.Now.AddDays(-1);
httpContext.Response.Cookies.Add(authCookie);
httpContext.Response.Redirect(FormsAuthentication.LoginUrl);
return;
}
string UserName = authTicket.UserData; //分解存在Cookie内的用户信息--
FormsIdentity id = new FormsIdentity(authTicket);
ICustomPrincipal principal = CustomPrincipalFactory.Create(id, UserName);
httpContext.User = principal;
}
public void GetTicket(HttpContext httpContext, string url)
{
try
{
System.Web.Security.FormsAuthenticationTicket tk = ((System.Web.Security.FormsIdentity)httpContext.User.Identity).Ticket;
string key = System.Web.Security.FormsAuthentication.Encrypt(tk); //每次加密后的字串都是不同的
httpContext.Response.Redirect(url + "?ssologin=1&ticket=" + key); //跳转至下一页面
}
catch
{
httpContext.Response.Redirect(url + "?ssologin=0"); //跳转至下一页面
}
finally
{
httpContext.Response.End();
}
}
public ICustomPrincipal ValidateTitcket(HttpContext httpContext, string ticket)
{
FormsAuthenticationTicket authTicket = null; //票椐
try
{
authTicket = System.Web.Security.FormsAuthentication.Decrypt(ticket); // Cookie 解密
}
catch (Exception ex)
{
return null;
}
string UserName = authTicket.UserData; //分解存在Cookie内的用户信息--
FormsIdentity id = new FormsIdentity(authTicket);
ICustomPrincipal principal = CustomPrincipalFactory.Create(id, UserName);
return principal;
}
}
public interface ICustomPrincipal : IPrincipal
{
Guid UserID { get; set; }
string LoginID { get; set; }
string Name { get; set; }
void ProcessData(IIdentity id, string data);
}
public class CustomPrincipalFactory
{
public static ICustomPrincipal Create(IIdentity id, string data)
{
string assemblyName = ConfigurationManager.AppSettings["CustomPrincipanAssembly"];
string className = ConfigurationManager.AppSettings["CustomPrincipanClass"];
Assembly assembly = Assembly.Load(assemblyName);
ICustomPrincipal principal = (ICustomPrincipal)assembly.CreateInstance(className);
principal.ProcessData(id, data);
return principal;
}
}
}