成功登录后,User.Identity.IsAuthenticated为false
成功登录后,我需要直接获取UserId Guid。 以下代码不起作用:
if (Membership.ValidateUser(txtUsername.Value, txtPassword.Value)) { FormsAuthentication.SignOut(); FormsAuthentication.SetAuthCookie(txtUsername.Value, true); if (HttpContext.Current.User.Identity.IsAuthenticated) { // doesn't run Guid puk = (Guid)Membership.GetUser().ProviderUserKey; } }
以下代码确实有效:
if (Membership.ValidateUser(txtUsername.Value, txtPassword.Value)) { FormsAuthentication.SignOut(); FormsAuthentication.SetAuthCookie(txtUsername.Value, true); MembershipUser user = Membership.GetUser(txtUsername.Value); if (user != null) { Guid puk = (Guid)user.ProviderUserKey; } }
为什么会这样? 除了SetAuthCookie
之外还有更多的事情SetAuthCookie
吗?
因为当你调用FormsAuthentication.SetAuthCookie(txtUsername.Value, true);
您将密钥存储在客户端的cookie上。 为此,您需要对用户做出响应。 而对于要填充cookie的HttpContext.Current.User.Identity
,还需要一个请求。
简而言之,您的计划如下所示:
-
客户端发送他的用户名和密码。
-
服务器获取并检查它。 如果它们有效,则服务器将
Set-Cookie
标头发送到客户端。 -
客户端接收并存储它。 对于每个请求,客户端都会将cookie发送回服务器。
更新@Jake
添加在HttpContext
中设置User
的示例
var identity = new System.Security.Principal.GenericIdentity(user.UserName); var principal = new GenericPrincipal(identity, new string[0]); HttpContext.Current.User = principal; Thread.CurrentPrincipal = principal;
请注意,您可以创建inheritance自GenericPrincipal
或ClaimsPrincipal
自定义主体类
我也有同样的问题。 我忘了设置web.config配置。
也许你错过了。
我尝试了上述所有解决方案,但解决我问题的方法是在web.config中对此进行评论
在我的开发环境案例中,requireSSL属性设置为true,我通过将问题更改为requireSSL = false
来解决问题。