FormsAuthentication没有成员资格的角色

cha*_*ara 9 asp.net asp.net-mvc forms-authentication asp.net-membership login

我正在尝试使用FormsAuthentication,它目前使用用户名和密码正常工作.我需要将用户角色添加到Forms身份验证故障单,我不使用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);

 }
Run Code Online (Sandbox Code Playgroud)

Hus*_*vic 24

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);
}
Run Code Online (Sandbox Code Playgroud)

在那之后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;
    }
}
Run Code Online (Sandbox Code Playgroud)

现在你在IPrincipal对象(HttpContext.Current.User)中有角色,当你查询时,HttpContext.Current.User.IsUserInRole("RoleName")你会得到真或假.这样你应该能够避免使用Roles提供者.

更新:一个更好的事件来调用以处理重新创建用户主体Application_AuthenticateRequest而不是BeginRequest.我已更新代码以反映这一点.

  • 很好的答案,但如果用户未经过身份验证,则会抛出空引用异常.使用`base.PostAuthenticateRequest + = OnAfterAuthenticateRequest;`代替 (4认同)