![](/img/trans.png)
[英]User.Identity.IsAuthenticated is false in a non-auth methods after successful login in asp.net core
[英]User.Identity.IsAuthenticated is false after successful login
我需要在成功登录后直接获取 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
之外还有其他事情要做吗?
我也有同样的问题。 我忘了设置 web.config 配置。
也许你也错过了。
<system.web>
<authentication mode="Forms">
<forms loginUrl="~/user/login" timeout="1000" name="__Auth" />
</authentication>
</system.web>
因为当你调用FormsAuthentication.SetAuthCookie(txtUsername.Value, true);
您将密钥存储在客户端的 cookie 中。 为此,您需要对用户做出响应。 而HttpContext.Current.User.Identity
填充 cookie,您还需要一个请求。
简而言之,您的方案如下所示:
客户发送他的用户名和密码。
服务器获取并检查它。 如果它们有效,则服务器将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;
请注意,您可以创建从GenericPrincipal
或ClaimsPrincipal
继承的自定义主体类
我尝试了上述所有解决方案,但解决我问题的方法是在 web.config 中对此进行评论
<modules>
<remove name="FormsAuthentication"/>
</modules>
我在 Blazor .NET 6 WASM 应用程序中遇到此错误。 我按照下面的指南将身份验证状态公开为级联参数:
这很好用,但是当与OnInitializedAsync
一起使用时, user.Identity.IsAuthenticated
在成功登录后设置为 false,但在刷新页面时工作。
将组件生命周期更改为OnParametersSetAsync
反而解决了该问题。
MainLayout.razor
中的完整代码:
@code {
bool loadData = true;
[CascadingParameter]
private Task<AuthenticationState> authenticationStateTask { get; set; }
protected override async Task OnParametersSetAsync()
{
var authState = await authenticationStateTask;
var user = authState.User;
if (user.Identity.IsAuthenticated)
{
loadData = true;
await StateContainer.LoadDataAsync();
loadData = false;
}
else
{
loadData = false;
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.