如何在更改用户角色后更改Context.User

时间:2014-03-24 02:17:43

标签: asp.net vb.net asp.net-membership asp.net-identity asp.net-roles

我正致力于创建和审核新用户的过程。用户注册后,会向他们发送一个链接(包含带有令牌的查询字符串)到他们的电子邮件中,以便他们验证他们的电子邮件地址。当用户点击该链接时,会将其重定向到验证其信息的页面,然后将其角色从访客更改为成员

流程

电子邮件> verifyEmail.aspx> dashboard.aspx

当用户已登录到Web应用程序,并且他们单击其电子邮件中的链接时,他们的角色会相应更改;但是,当它们被重定向到dashboard.aspx时,User.IsInRole(" Member")为false。注销后,然后重新登录,User.IsInRole(" Member")为真。所以我的问题是,我如何更新用户的身份,以及用户的上下文而不强制他们退出然后重新登录?我猜它与角色的cookie有关吗?

代码

    If userToken.Token1 = token Then
      Dim userRole = Roles.GetRolesForUser(authUser)
      Dim userIdentity = New GenericIdentity(authUser)
      Dim principal = New GenericPrincipal(userIdentity, userRole)
      Dim isOnline As Boolean = False

      If HttpContext.Current IsNot Nothing AndAlso HttpContext.Current.User.Identity.IsAuthenticated Then
        If Not Membership.GetUser.ProviderUserKey Is Nothing Then
          isOnline = True
        End If
      End If

      Context.User = principal

      If User.IsInRole("Guest") = True AndAlso User.IsInRole("Member") = False Then
        Roles.AddUserToRole(User.Identity.Name, "Member")
        Roles.RemoveUserFromRole(User.Identity.Name, "Guest")

        If isOnline = True Then
          '***do stuff here to change the context
          Response.Redirect("../Account/GetStarted.aspx")
        End If
      End If
    End If

1 个答案:

答案 0 :(得分:1)

假设您使用的是表单身份验证,可能需要使用以下方法:

FormsAuthentication.SetAuthCookie

这将"为提供的用户名创建身份验证票证,并将其添加到响应的cookie集合中,如果您使用的是无Cookie身份验证,则将其添加到URL。"

取自MSDN