.NET Core 3 Cookie Authentication не устанавливает идентичность - PullRequest
0 голосов
/ 03 февраля 2019

Windows 10, .NET Core 3.0

У меня есть пустой проект mvc (dotnet new mvc).

Домашний индекс:

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 и Configure)

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

При обновлении индекса User.Identity.Name всегда имеет значение null, и IsAuthentication никогда не устанавливается.

Ответы [ 2 ]

0 голосов
/ 04 февраля 2019

В методе Configure метод UseAuthentication должен предшествовать UseMvcWithDefaultRoute.Это должно быть раньше, потому что AuthenticationMiddleware установит HttpContext.User до того, как запрос придет к вашему методу Index.

См. Ссылку https://docs.microsoft.com/en-us/aspnet/core/security/authentication/cookie?view=aspnetcore-2.2

0 голосов
/ 03 февраля 2019

Вы пробовали следующее:

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

Это должно получить то, что вы ищете.

...