首页 > 解决方案 > 登录成功返回但用户不是

问题描述

我有一个 Blazor WASM 应用程序。我使用身份框架登录:

SignInResult signInResult = await signInManager<ApplicationUser>.PasswordSignInAsync(parameters.UserName, parameters.Password, parameters.RememberMe, true);

signInResult总是Succeeded。_

在 WebAssembly 的 StateProvider 中,我得到一个 UserInfo 对象,其中包括告诉用户是否已通过身份验证:

    [HttpGet]
    public UserInfoDto UserInfo()
    {
        return BuildUserInfo();
    }

    private UserInfoDto BuildUserInfo()
    {
        var userInfo = new UserInfoDto
        {
            IsAuthenticated = User.Identity.IsAuthenticated,
            UserName = User.Identity.Name
        };

        foreach (var claim in User.Claims)
        {
            userInfo.ExposedClaims.Add(claim.Type, claim.Value);
        }

        if (userInfo.IsAuthenticated)
        {
            userInfo.Id = Guid.Parse(identityService.GetUserId(User));
        }

        return userInfo;
    }

这里User.Identity.IsAuthenticated总是假的。我也在 PasswordSignInAsync 之后检查了它,但它也是一样的。

我的启动是这样设置的:

services.AddIdentity<ApplicationUser, ApplicationIdentityRole>()
        .AddEntityFrameworkStores<SupportToolContext>()
        .AddDefaultTokenProviders();

services.Configure<IdentityOptions>(options =>
        {
            // Password settings
            options.Password.RequireDigit = false;
            options.Password.RequiredLength = MIN_PASSWORD_LENGTH;
            options.Password.RequireNonAlphanumeric = false;
            options.Password.RequireUppercase = false;
            options.Password.RequireLowercase = false;

            // Lockout settings
            options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(LOCKOUT_DURATION);
            options.Lockout.MaxFailedAccessAttempts = MAX_TRIES_BEFORE_LOCKOUT;
            options.Lockout.AllowedForNewUsers = true;

            // Email Settings
            options.User.RequireUniqueEmail = true;
            options.SignIn.RequireConfirmedEmail = true;
        });

// Configure LifeSpan of Identity email tokens
services.Configure<DataProtectionTokenProviderOptions>(options =>
        {
            options.TokenLifespan = TimeSpan.FromDays(3);
        });

services.ConfigureApplicationCookie(options =>
        {
            options.Cookie.HttpOnly = false;
            options.Events = new CookieAuthenticationEvents
                             {
                                 OnRedirectToLogin = context =>
                                                     {
                                                         context.Response.StatusCode = UNAUTHORIZED_STATUS_CODE;
                                                         return Task.CompletedTask;
                                                     }
                             };
        });

Configure 方法包含:

app.UseAuthentication();
app.UseAuthorization();

身份验证状态提供者:

公共类 IdentityAuthenticationStateProvider : AuthenticationStateProvider { private UserInfoDto userInfoCache; 私有只读 IServiceProvider 服务提供者;

    public IdentityAuthenticationStateProvider(IServiceProvider serviceProvider)
    {
        this.serviceProvider = serviceProvider;
    }

    ..

    private async Task<UserInfoDto> GetUserInfoAsync()
    {
        var authorizeApi = serviceProvider.GetRequiredService<IAuthorizeApi>();

        if (userInfoCache != null && userInfoCache.IsAuthenticated) return userInfoCache;
        userInfoCache = await authorizeApi.GetUserInfoAsync();

        return userInfoCache;
    }

    public override async Task<AuthenticationState> GetAuthenticationStateAsync()
    {
        var identity = new ClaimsIdentity();
        try
        {
            UserInfoDto userInfo = await GetUserInfoAsync();
            if (userInfo.IsAuthenticated)
            {
                IEnumerable<Claim> claims = new[] {new Claim(ClaimTypes.Name, userInfoCache.UserName)}.Concat(
                    userInfoCache.ExposedClaims.Select(c => new Claim(c.Key, c.Value)));
                identity = new ClaimsIdentity(claims, "Server authentication");
            }
        }
        catch (HttpRequestException ex)
        {
            Console.WriteLine("Request failed:" + ex);
        }

        return new AuthenticationState(new ClaimsPrincipal(identity));
    }
}

一般来说,整个过程与此示例相同:https ://github.com/stavroskasidis/BlazorWithIdentity (也停止在本地工作)

让我感到困惑的是,它以前工作过并且仍然在服务器上工作,如果我在部署到服务器的点检查该历史记录,它就不能在本地工作。我想念什么?

标签: asp.net-identityblazorblazor-client-side

解决方案


好吧,这很令人沮丧。解决方案是重新启动我的所有计算机。似乎问题出在 IIS Express 左右的某个地方 - 同时在我的两台计算机上。


推荐阅读