【问题标题】:When do ASP.NET Core claims become accessible via HttpContext.User.Claims?什么时候可以通过 HttpContext.User.Claims 访问 ASP.NET Core 声明?
【发布时间】:2016-08-22 06:55:42
【问题描述】:

设置:

  1. 创建一个包含一堆声明的ClaimsPrincipal
  2. 致电httpContext.Authentication.SignInAsync("MyAuthScheme", myClaimsPrincipal, myAuthProperties)
  3. 尝试遍历httpContext.User.Claims 上的所有声明。

结果:

来自 pt 的声明。 1 不在httpContext.User.Claims-collection 中。

为什么?

编辑:

var claims = GetPersistentClaims(username.ToLowerInvariant());
var identity = new ClaimsIdentity(claims, AuthenticationScheme);
var principal = new ClaimsPrincipal(identity);
var authenticationManager = _httpContextAccessor.HttpContext.Authentication;
var properties = new AuthenticationProperties {IsPersistent = isPersistent};
await authenticationManager.SignInAsync(AuthenticationScheme, principal, properties);
// This is where I inspect _httpContextAccessor.HttpContext.User.Claims.

【问题讨论】:

  • httpContext.User.Identity.IsAuthenticated的值是多少?
  • @adem caglin 这是false
  • 您在何时何地迭代httpContext.User.Claims?如果可能的话,你能发布你的代码吗?
  • 我已经添加了源代码sn-p。
  • iirc 它们在登录后 的请求中可用,因此您需要在使用 SignInAsync 登录后将用户重定向到新的/受保护的资源,因为在您调用 SignInAsync 时,已经设置了 HttpContext 并且 User 属性在下一次请求之前不会更改

标签: asp.net-core claims-based-identity


【解决方案1】:

当您调用SignInAsync 时,身份验证处理程序会调用自己的SignInAsync()。在您的情况下,它是 cookie 身份验证(它只是设置 cookie)。

如果要认证用户,需要调用authenticationManager.AuthenticateAsync(AuthenticationScheme);

编辑

SignInAsync 之后没有工作,因为当前请求没有 cookie。但HttpContext.User = principal ; 可能是一个解决方案。

ps : 通常你会为下一个请求使用声明。

【讨论】:

  • 是的,我尝试过同样的方法 - 这在 Beta 8 和 RC1 中有效 - 但现在不再有效。令人沮丧。
  • 感谢您的帮助。我想我必须把它扔进“另一件已更改但未记录在案的事情”中。
猜你喜欢
  • 2014-03-11
  • 1970-01-01
  • 2019-07-31
  • 2015-11-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-05
  • 1970-01-01
相关资源
最近更新 更多