Asp.net

沒有成員資格的 FormsAuthentication 角色

  • June 5, 2013

我正在嘗試使用 FormsAuthentication ,目前使用使用者名和密碼可以正常工作。我需要將使用者角色添加到表單身份驗證票證中,並且我沒有使用 ASP.NET 成員資格。

if (rep.CheckUser(model.UserName, model.Password,out UserRole))//Check User
 {

 FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);

// Roles.AddUserToRole(model.UserName, UserRole);//This Requires Membership

 return Redirect(FormsAuthentication.DefaultUrl);

}

FormsAuthenticationTicket建構子(具有最多參數的建構子)具有userData接受字元串的參數。在這裡,您可以添加角色,由管道 (|) 或雜湊等字元分隔。您打算如何使用取決於您。您通常會做的是註冊AuthenticateRequest事件。因此,您可以創建一個票證:

private void CreateTicket()
{
   var ticket = new FormsAuthenticationTicket(
           version: 1,
           name: UserName,
           issueDate: DateTime.Now,
           expiration: DateTime.Now.AddSeconds(httpContext.Session.Timeout),
           isPersistent: false,
           userData: String.Join("|", arrayOfRoles));

   var encryptedTicket = FormsAuthentication.Encrypt(ticket);
   var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);

   httpContext.Response.Cookies.Add(cookie);
}

在那之後global.asax你會做這樣的事情:

public override void Init()
{
   base.AuthenticateRequest += OnAuthenticateRequest;
}

private void OnAuthenticateRequest(object sender, EventArgs eventArgs)
{
   if (HttpContext.Current.User.Identity.IsAuthenticated)
   {
       var cookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
       var decodedTicket = FormsAuthentication.Decrypt(cookie.Value);
       var roles = decodedTicket.UserData.Split(new[] {"|"}, StringSplitOptions.RemoveEmptyEntries);

       var principal = new GenericPrincipal(HttpContext.Current.User.Identity, roles);
       HttpContext.Current.User = principal;
   }
}

現在您在 IPrincipal 對象 ( HttpContext.Current.User) 中有角色,當您查詢時,HttpContext.Current.User.IsUserInRole("RoleName")您將得到真或假。這樣你應該能夠避免使用Roles提供者。

更新:為了處理重新創建使用者主體而呼叫的更好的事件是Application_AuthenticateRequest而不是BeginRequest. 我已經更新了程式碼以反映這一點。

引用自:https://stackoverflow.com/questions/16933366