c# – AspNetCore 2.0声明总是空的

我正在努力将DotNet 4.5 MVC / WebAPI应用程序转换为AspNetCore 2.0,我在使我的Cookie身份验证再次运行时遇到了一些麻烦.当我设置cookie并尝试访问安全方法时,我无法到达那里.当我进入匿名方法并检查用户对象时,它是空的 – 没有身份验证类型,没有声明等.

我尽可能地遵循这篇文章:https://docs.microsoft.com/en-us/aspnet/core/security/authentication/cookie?tabs=aspnetcore2x.我没有使用Identity.

我在startup.cs ConfigureServices中的代码如下:

  services.AddAuthentication("ACE_AUTH")                    
                    .AddCookie("ACE_AUTH",  options =>
                    {
                        options.AccessDeniedPath = "/Home/Index/";
                        options.LoginPath = "/Home/Index/";
                    });

我在Configure方法中的代码:

app.UseAuthentication();

当调用它时,Principal完全填充.我在哪里设置我的cookie:

 await HttpContext.SignInAsync("ACE_AUTH", samlData.Principal);

在尝试验证用户时,我尝试的任何内容都没有导致我的声明出现.

最佳答案 以下是对我有用的东西:我学到的大部分内容都来自
this microsoft doc,但正如你所说,文档似乎并没有带你到处.

在startup.cs中

public void ConfigureServices(IServiceCollection services)
    {
        ...

        services.AddAuthentication("ACE_AUTH")
        .AddCookie("ACE_AUTH", options => {
            options.AccessDeniedPath = "/api/Auth/Forbidden";
            options.LoginPath = "/";
            options.Cookie.Expiration = new TimeSpan(7,0,0,0);
        });
    }


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

        app.UseAuthentication();
    }

然后在处理身份验证的控制器中:

    [HttpPost()]
    [Route("api/[Controller]/[Action]/")]
    public async Task<JsonResult> Login([FromBody]Dictionary<string, string> loginData)
    {
        try
        {
            var loggedIn = true;
            if (loggedIn)
            {
                var claims = new List<Claim> {
                    new Claim(ClaimTypes.Name, "John Doe")
                };

                var identity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme);
                identity.AddClaims(claims);
                ClaimsPrincipal principal = new ClaimsPrincipal(identity);

                await HttpContext.SignInAsync(
                    "ACE_AUTH",
                    principal,
                    new AuthenticationProperties
                    {
                        IsPersistent = true,
                        ExpiresUtc = DateTime.UtcNow.AddDays(7)
                    });
            }
            return new JsonResult(logRtn);
        }
        catch (Exception ex)
        {
            return new JsonResult(ex.Message);
        }
    }

如果您可以验证并分配loggingIn您的身份验证请求的结果,您应该能够在cookie中存储声明.然后,您可以使用以下内容在可能正在执行授权/调用值的控制器中调用该声明:

    [HttpGet("[Action]", Name = "GetSomething")]
    [Route("[Action]")]
    public JsonResult something()
    {
        try
        {
            var loggedInUser = HttpContext.User;
            var claym = loggedInUser.Claims.FirstOrDefault(x => x.Type == ClaimTypes.Name);
            if (claym != null)
            {
                return new JsonResult(claym.Value);
                // returns "John Doe"
            }
            else
            {
                return new JsonResult("");
            }
        }
        catch (Exception ex)
        {
            return new JsonResult(ex.Message);
        }
    }
点赞