AspNetCore 2.0中的Claims总是为空

15
我正在将一个DotNet 4.5 MVC/WebAPI应用程序转换为AspNetCore 2.0,并且我在重新启用Cookie身份验证时遇到了一些问题。当我设置Cookie并尝试访问安全方法时,我无法到达那里。当我进入匿名方法并检查用户对象时,它是空的 - 没有身份验证类型,没有声明等。
我尽可能地按照这篇文章:https://learn.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);

我尝试过的所有方法都无法使我的声明在尝试验证用户时显示出来。


1
遇到了同样的问题。你解决了吗? - Clement
还没有。我现在不得不转而处理其他事情,但我很快会回来处理它。 - Danny Ellis Jr.
6
对我来说解决问题的方法是将 app.UseAuthentication 移到 app.UseMvc 之上。虽然文档中有提到,但很难找到。 - Joey
2个回答

6

对于不阅读评论的人(我自己几乎也快跳过了):

Joey: "我解决了这个问题,是将app.UseAuthentication移到app.UseMvc之上。文档中确实有提到,但很难找到。"

...这样做有效...为什么在之后这样做不会抛出异常就超出了我的理解范围。


3
以下是我正在使用的方法:我学到的大部分内容都来自于这篇微软文档,但正如你所说,文档似乎没有将你带到最后一步。
在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);
        }
    }

如果您可以进行身份验证并将loggedIn分配为您的身份验证请求的结果,那么您应该能够在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);
        }
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接