При создании билета для проверки подлинности с помощью форм вы, как правило, используете часть своего билета UserData для хранения информации, связанной с вашим пользователем. Это могут быть роли.
Затем в Global.asax в событии Application_AuthenticateRequest вы проанализируете свой бланк форм и назначите роли текущему участнику безопасности.
Вот несколько руководств по проверке подлинности с помощью различных провайдеров:
http://weblogs.asp.net/scottgu/archive/2006/02/24/ASP.NET-2.0-Membership_2C00_-Roles_2C00_-Forms-Authentication_2C00_-and-Security-Resources-.aspx
Обычно я обычно пишу свои собственные System.Security.Principal.GenericPrincipal и System.Web.Security.FormsIdentity, чтобы сделать всю работу за меня.
public class UserIdentity: System.Web.Security.FormsIdentity
{
public string[] Roles { get; private set; }
public string FirstName { get; private set; }
public string UserName { get; private set; }
public int UserID { get; private set; }
public UserIdentity(System.Web.Security.FormsAuthenticationTicket ticket) : base(ticket)
{
if (ticket.UserData != null && ticket.UserData.IndexOf("|") != -1)
{
string[] dataSections = ticket.UserData.Split('|');
//Get the first name
FirstName = dataSections.Length >= 3 ? dataSections[2] : "";
//Get the username
UserName = ticket.Name;
#region Parse the UserID
int userID = 0;
int.TryParse(dataSections[0], out userID);
this.UserID = userID;
#endregion
this.Roles = System.Text.RegularExpressions.Regex.Split(dataSections[1], ",");
}
}
}
public class UserPrincipal : System.Security.Principal.GenericPrincipal
{
public UserPrincipal(UserIdentity identity) : base(identity, identity.Roles )
{
}
}
А в вашем Global.asax:
protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
if (HttpContext.Current.User != null && HttpContext.Current.User.Identity.IsAuthenticated && HttpContext.Current.User.Identity is System.Web.Security.FormsIdentity)
{
HttpContext.Current.User = new CAA.Utility.Security.UserPrincipal(HttpContext.Current.User.Identity is CAA.Utility.Security.UserIdentity? HttpContext.Current.User.Identity as CAA.Utility.Security.UserIdentity : new Utility.Security.UserIdentity(((System.Web.Security.FormsIdentity)HttpContext.Current.User.Identity).Ticket));
}
}
И написать билет:
System.Web.Security.FormsAuthenticationTicket ticket = new System.Web.Security.FormsAuthenticationTicket(1, user.Username, DateTime.Now, DateTime.Now.AddDays(1), false, String.Format("{0}|{1}|{2}", user.UserID ,user.Roles.ToString(), user.FirstName ), System.Web.Security.FormsAuthentication.FormsCookiePath);
HttpCookie cookie = new HttpCookie(System.Web.Security.FormsAuthentication.FormsCookieName, System.Web.Security.FormsAuthentication.Encrypt(ticket));
if (model.RememberMe)
cookie.Expires = ticket.Expiration;
Response.Cookies.Add(cookie);
Код может быть сложным для отслеживания, но логика заключается в том, что пользовательский «UserPrincipal» будет автоматически анализировать раздел UserData билета Autms Forms для любой информации, которую вы хотите сохранить там. В моем случае я храню имя, роли, идентификатор и т. Д. В моем коде пространство имен «CAA.Utility.Security» - это место, где хранятся мои пользовательские идентификационные данные и принципал.