简体   繁体   English

PasswordSignInAsync 未设置 User.Identity

[英]PasswordSignInAsync not setting User.Identity

I'm using Net Core 3.1 and doing the below code for login:我正在使用 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");
        }
    }

When I try to use User.Identity.IsAuthenticated , this always returns false.当我尝试使用User.Identity.IsAuthenticated时,它总是返回 false。

What am I missing here?我在这里想念什么?

Adding config files below.在下面添加配置文件。

Let me know if anything could be missing from the config files.让我知道配置文件中是否缺少任何内容。

Startup.cs启动.cs

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

        services.AddRazorPages();
    }

IdentityHostingStartup.cs 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();
        });
    }

This is my configuration files used to configuration.这是我用来配置的配置文件。

Cookie-auth obviously requires setting a cookie. Cookie-auth 显然需要设置一个 cookie。 That is done via the Set-Cookie response header, which will be sent with the response once you return it.这是通过Set-Cookie响应 header 完成的,一旦您返回它,它将与响应一起发送。 Once the browser receives the response with that header, it will set the cookie, and then on subsequent requests will send that cookie back to re-authenticate the user for each request.一旦浏览器收到带有 header 的响应,它将设置 cookie,然后在后续请求中将发送该 cookie 以重新验证每个请求的用户。

Until you send the response, none of this has happened, yet, and therefore, User is not populated.在您发送响应之前,这一切都没有发生,因此,不会填充User Long and short, you can't get at things like User.Identity.IsAuthenticated() or User.Identity.Name until the next request .总而言之,在下一个 request之前,您无法获得User.Identity.IsAuthenticated()User.Identity.Name之类的东西。

That said, since all you're doing is logging here, you can just log those values from the information you already have.也就是说,由于您所做的只是在此处记录,因此您可以从已有的信息中记录这些值。 Obviously the user is authenticated or they wouldn't have reached this point in the control flow, so just return true there, instead of User.Identity.IsAuthenticated .显然,用户已通过身份验证,否则他们不会在控制流中到达这一点,因此只需在此处返回true ,而不是User.Identity.IsAuthenticated For User.Identity.Name , use user.UserName , etc.对于User.Identity.Name ,使用user.UserName等。

.Net core 2.1 or higher on is built-in supports GDPR (General Data Protection Regulation). .Net core 2.1 或更高版本内置支持GDPR (通用数据保护条例)。

and until you accept the cookie, cookie does not set in the browser and User.Identity.IsAuthenticated always return false .并且在您接受 cookie 之前,不会在浏览器中设置 cookie,并且User.Identity.IsAuthenticated始终返回false

You must set IsEssential to true to ignore GDPR您必须将IsEssential设置为true才能忽略GDPR

services.Configure<CookiePolicyOptions>(options =>
            {
                options.ConsentCookie.IsEssential = true;//<-- NOTE THIS
                options.CheckConsentNeeded = context => false;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

Or add this line to ConfigureApplicationCookie method to ignore GDRP and save cookie in the browser或者将此行添加到ConfigureApplicationCookie方法以忽略GDRP并将 cookie 保存在浏览器中

 options.Cookie.IsEssential = true;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM