asp.net - 没有成员身份的 FormsAuthentication 角色

标签 asp.net asp.net-mvc login asp.net-membership forms-authentication

我正在尝试使用 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);

 }

最佳答案

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 .我已经更新了代码以反射(reflect)这一点。

关于asp.net - 没有成员身份的 FormsAuthentication 角色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16933366/

相关文章:

r - 在 R 中使用 rvest 跟踪页面重定向

c# - ASP.NET mvc html 列显示

asp.net - AJAX 请求时 Azure SQL 中的间歇性连接超时

c# - 使用数组将多个参数从 View 传递到 Controller

ASP.NET A/B 拆分测试

c# - 传入字典的模型项是 'System.String' 类型的,但是这个字典需要一个 'JFS.Data.Model.Address' 类型的模型项

Python Mechanize 登录表单,将输入发送到具有随机生成名称的字段

asp.net - 如何在 ASP.NET 中的 Web 应用程序之间共享用户控件?

asp.net - 在 Visual Studio 中看不到清洁解决方案选项

security - Grails-Spring安全帐户创建