.Net Core 3.0 Cookie身份验证。授权属性始终重定向

时间:2020-01-22 09:16:43

标签: .net asp.net-core asp.net-core-3.0

我终于可以将一些.Net Framework项目转换为Core(3.0)。我目前仅查看Cookie身份验证,并启动并运行一个简单的示例。

我拥有使用有效数据创建的声明和登录cookie,但是使用[Authorize]进行的任何控制器操作始终都重定向到登录页面(指示我们尚未登录)。但是,在“登录”页面上,我已经输出了声明和IsAuthenticated状态,并且它返回有效数据。

登录功能

 var claims = new List<Claim>
            {
                new Claim(ClaimTypes.NameIdentifier, "ID"),
                new Claim(ClaimTypes.Name, "TEST"),
                new Claim(ClaimTypes.GivenName, "Test"),
                new Claim(ClaimTypes.Surname, "TEST"),
                new Claim(ClaimTypes.DateOfBirth, DateTime.Now.ToString("o"), ClaimValueTypes.DateTime)
            };

            var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
            var principal = new ClaimsPrincipal(identity);
            await HttpContext.SignInAsync(principal);

“安全区域”示例

        [Authorize()]
        public IActionResult Secure()
        {
            return View();
        }

配置服务:

        services.AddControllersWithViews();

        services.AddMvc();

        services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
            .AddCookie(options =>
            {
                options.Cookie.Name = "TestAuthCookie";
                options.LoginPath = "/Home/Login";
                options.LogoutPath = "/Home/Logout";
            });

在启动中配置。

1 个答案:

答案 0 :(得分:2)

根据评论:有时人们忘记了在中间件管道的早期阶段调用app.UseAuthentication();,结果HttpContext.User的设置不正确。

    app.UseAuthentication();   // this line is important
    app.UseAuthorization();

就个人而言,当身份验证不起作用时,我将首先检查是否已启用AuthenticationMiddleware