.NET Core 3 Cookie 身份验证未设置身份

.NET Core 3 Cookie Authentication not setting identity

Windows10、.NET 核心 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(配置服务和配置)

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

刷新索引时,User.Identity.Name 始终为 null,并且永远不会设置 IsAuthentication。

您是否尝试过以下操作:

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

这应该会检索到您要查找的内容。

在Configure方法中,UseAuthentication方法应该在UseMvcWithDefaultRoute之前。它必须是之前,因为 AuthenticationMiddleware 将在请求到达您的 Index 方法之前设置 HttpContext.User。

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