简体   繁体   中英

.NET Core 3 Cookie Authentication not setting identity

Windows 10, .NET Core 3.0

I have a blank mvc project(dotnet new mvc).

Home Index:

public async Task<IActionResult> Index()
    {
        if(User.Identity.Name == null) {
            var props = new AuthenticationProperties
            {
                IsPersistent = true,
                ExpiresUtc = DateTime.UtcNow.AddMinutes(30)
            };

            var identity = new ClaimsIdentity(new[]
            {
                new Claim(ClaimTypes.Name, "sometestuser")
            }, CookieAuthenticationDefaults.AuthenticationScheme);
            await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(identity), props);
        }

        return Content(User.Identity.Name);
    }

Startup.cs(ConfigureServices and Configure)

services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(CookieAuthenticationDefaults.AuthenticationScheme);
app.UseAuthentication();

When refreshing the Index, User.Identity.Name is always null and IsAuthentication never gets set.

In the Configure method, UseAuthentication method should come before UseMvcWithDefaultRoute. It has to be before because the AuthenticationMiddleware will then set the HttpContext.User before the request comes to your Index method.

Please see the link https://docs.microsoft.com/en-us/aspnet/core/security/authentication/cookie?view=aspnetcore-2.2

Have you tried following:

var val = User.FindFirst(ClaimTypes.Name).Value;

This should retrieve what you are looking for.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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