首页 > 解决方案 > PasswordSignInAsync 未设置 User.Identity

问题描述

我正在使用 Net Core 3.1 并执行以下代码进行登录:

     public async Task LoginAsync(string username, string pass) {            
        _logger.LogDebug("Attempting Login... {0}", username);
        var result = await _signInManager.PasswordSignInAsync(username,
                       pass, true, lockoutOnFailure: true);   
        if (result.Succeeded && !result.IsLockedOut && !result.IsNotAllowed) {
            var user = await _signInManager.UserManager.FindByNameAsync(username);
            await _signInManager.SignInAsync(user, false);

            _logger.LogDebug("{0} Logged in successfully. {1}", username, System.DateTime.Now);
            _logger.LogDebug("{0} {1}", User.Identity.IsAuthenticated, user.UserName);
            _logger.LogDebug("{0}", User.Identity.Name);
            Response.Redirect("/Dashboard");
        } else {
            _logger.LogDebug("{0} Wrong Credentials.", username);
            Response.Redirect("/?error=wrong-credentials");
        }
    }

当我尝试使用User.Identity.IsAuthenticated时,它总是返回 false。

我在这里想念什么?

在下面添加配置文件。

让我知道配置文件中是否缺少任何内容。

启动.cs

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddDbContext<GazelleIdentityContext>(options =>
            options.UseSqlServer(Configuration.GetConnectionString("GazelleCS")));

        services.AddRazorPages();
    }

IdentityHostingStartup.cs

    public void Configure(IWebHostBuilder builder)
    {
        builder.ConfigureServices((context, services) => {
            services.AddDbContext<GazelleIdentityContext>(options =>
                options.UseSqlServer(context.Configuration.GetConnectionString("GazelleCS"))
            );
            services.AddDefaultIdentity<IdentityUser>().AddEntityFrameworkStores<GazelleIdentityContext>();

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

                // Lockout settings.
                options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(60);
                options.Lockout.MaxFailedAccessAttempts = 3;
                options.Lockout.AllowedForNewUsers = true;

                // User settings.
                options.User.AllowedUserNameCharacters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._@+";
                options.User.RequireUniqueEmail = true;
            });

            services.ConfigureApplicationCookie(options =>
            {
                // Cookie settings
                options.Cookie.Name = "GACOOKIE_USER";
                options.Cookie.HttpOnly = true;
                options.ExpireTimeSpan = TimeSpan.FromMinutes(2);
                options.LoginPath = "/";
                options.LogoutPath = "/Logout";
                options.AccessDeniedPath = "/LoginFailed";
                options.SlidingExpiration = true;
                options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
                options.Cookie.SameSite = SameSiteMode.Lax;
            });

            services.AddAuthentication(options =>
            {
                options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            }).AddCookie();
        });
    }

这是我用来配置的配置文件。

标签: c#asp.net-corerazor.net-coreasp.net-identity

解决方案


Cookie-auth 显然需要设置一个 cookie。这是通过Set-Cookie响应标头完成的,一旦您返回响应,它将与响应一起发送。一旦浏览器收到带有该标头的响应,它将设置 cookie,然后在后续请求中将发送该 cookie 以重新验证每个请求的用户。

在您发送响应之前,这一切都没有发生,因此User没有填充。总而言之,在下一个 request之前,您无法解决诸如User.Identity.IsAuthenticated()or之类的事情。User.Identity.Name

也就是说,由于您所做的只是在此处记录,因此您可以从已有的信息中记录这些值。显然用户已经过身份验证,否则他们不会在控制流中到达这一点,所以只需返回true那里,而不是User.Identity.IsAuthenticated. 为User.Identity.Name、 使用user.UserName


推荐阅读