ASP.NET Core 2.2身份验证不起作用?

问题描述 投票:0回答:1

我正在尝试创建自己的登录身份验证,但该方法无法正常工作,因此我创建了此快速测试...

    [HttpGet]
    public IActionResult Index()
    {
        try
        {
            var identity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme);
            identity.AddClaim(new Claim(ClaimTypes.Name, "Test Name"));
            var principal = new ClaimsPrincipal(identity);

            SignIn(principal, CookieAuthenticationDefaults.AuthenticationScheme);

            var isAuthenticated = User.Identity.IsAuthenticated;    //-- THIS IS ALWAY FALSE... BUI JUST LOGGED IN?!?!?!?

            return View();
        }
        catch(Exception ex)
        {
            _logger.LogError(ex, "Error:");
            return StatusCode(500);
        }
    }

因此您可以看到我呼叫了SignIn,然后在下一行中检查用户是否已通过身份验证,但它始终返回false,并且User.Identity也看起来为空。有人知道我在做什么错吗?

在我的启动/配置服务中,我具有:

        services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(
                CookieAuthenticationDefaults.AuthenticationScheme,
                options =>
                {
                    options.LoginPath = "/Admin/Index";
                }
            );

并且在启动/配置中

        app.UseAuthentication();
        app.UseCookiePolicy(new CookiePolicyOptions
        {
            MinimumSameSitePolicy = SameSiteMode.Strict,
        });
c# authentication asp.net-core-2.2
1个回答
0
投票

[我看到您的Index方法缺少Authorize属性。请添加Authorize属性,如下所示:

[Authorize]
[HttpGet]
public IActionResult Index()
{
    ....
}

然后在Configure类的Startup方法中,中间件顺序应如下:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
        ......

        app.UseStaticFiles();
        app.UseCookiePolicy(new CookiePolicyOptions
        {
            MinimumSameSitePolicy = SameSiteMode.Strict,
        });

        app.UseAuthentication();
        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });
}

现在它应该对您有用。

© www.soinside.com 2019 - 2024. All rights reserved.