【问题标题】:GenericPrincipal IsInRole returns false for HttpContext.UserGenericPrincipal IsInRole 为 HttpContext.User 返回 false
【发布时间】:2014-05-21 07:26:07
【问题描述】:

我有一个通过 GenericPrincipal 设置用户凭据的凭据方法。我正在使用 asp.net MVC

    public void SetCredentials(HttpContextBase context, string username, bool createPersistenceCookie)
    {
        FormsAuthentication.SetAuthCookie(username, createPersistenceCookie);

        IIdentity identity = new GenericIdentity(username);
        IPrincipal principal = new GenericPrincipal(identity,new []{"standart"});

        context.User = principal;
    }

我想在控制器操作中检查 User.IsInRole("standart"),但它返回 false。

  • context.User.IsInRole("standart") //返回false

我想在我的应用程序中使用 context.User,但它总是返回 false。

【问题讨论】:

  • 上下文用户和CurrentPrincipal一样吗?
  • Thread.CurrentPrincipal.IsInRole("standart") 返回 true 的事实与您帖子的标题相矛盾。我建议您调查一下 Thread.CurrentPrincipal 和 context.User 是否与您的 principal 相同。

标签: asp.net asp.net-mvc asp.net-mvc-4


【解决方案1】:

我想你以前用过 asp.net 会员 api。现在您想在您的应用程序中创建自定义主体。

当你向服务器发送请求时,服务器使用一个新的干净的 HttpContext。因此,您丢失了旧信息。如果您想在应用程序中使用旧的会话信息,您应该将数据保存在服务器端或客户端。您可以通过两种方式做到这一点。

  • 客户端 cookie
  • 服务器会话

我建议您使用客户端 cookie。因为数据是存储到客户端的,所以节省了服务器资源。

   public void SetCredentials(HttpContextBase context, string username, bool createPersistenceCookie)
    {
        var formsAuthenticationTicket = new FormsAuthenticationTicket(
            1,
            username,
            DateTime.Now,
            DateTime.Now.AddMilliseconds(FormsAuthentication.Timeout.TotalMilliseconds),
            createPersistenceCookie,
            roles
        );

        var encryptedTicket = FormsAuthentication.Encrypt(formsAuthenticationTicket);
        var authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);

        HttpContext.Current.Response.AppendCookie(authCookie);
    }

我将加密的 cookie 发送到客户端。我应该检查这个 cookie 对服务器应用程序的所有传入请求。

现在在 Global.asax 文件中:

    protected void Application_AuthenticateRequest(object sender, System.EventArgs e)
    {
        HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];

        if (authCookie == null) return;

        FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(authCookie.Value);

        IIdentity identity = new GenericIdentity(ticket.Name);
        IPrincipal principal = new GenericPrincipal(identity, ticket.UserData.Split('|'));

        HttpContext.Current.User = principal;
    }

希望能解决你的问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-12-18
    • 2016-05-06
    • 1970-01-01
    • 1970-01-01
    • 2013-09-18
    • 2017-05-17
    • 2011-05-05
    • 1970-01-01
    相关资源
    最近更新 更多