James
James

Reputation: 680

.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.

Upvotes: 1

Views: 4077

Answers (2)

kapd
kapd

Reputation: 659

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://learn.microsoft.com/en-us/aspnet/core/security/authentication/cookie?view=aspnetcore-2.2

Upvotes: 1

eVolve
eVolve

Reputation: 1446

Have you tried following:

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

This should retrieve what you are looking for.

Upvotes: 0

Related Questions