[英]How to access claims from HttpContext in .Net Core?
使用下面的代碼通過自定義聲明登錄,它工作正常。
private async Task SignInAsync(ApplicationUser user)
{
var claims = await _claimsPrincipalFactory.CreateAsync(user);
claims.Identities.First().AddClaims(new[]
{
new Claim("xxx", "111"),
new Claim("yyy", "222")
});
await HttpContext.SignInAsync(IdentityConstants.ApplicationScheme, claims);
}
但是當嘗試在服務中使用 HttpContext 訪問時,如下所示
var claims = HttpContext.User.Identities.FirstOrDefault().Claims.ToList();
它返回 0 個索賠。
請幫忙。
我的假設是由於構建管道的語句的順序而丟失了聲明。
在Configure
中,您可以將中間件插入管道。 插入中間件時,順序很重要,不像在ConfigureServices
中那樣。
因此,當在用戶通過身份驗證之前在使用聲明的中間件中使用服務時,聲明尚不可用,例如:
app.UseMyMiddlewareThatCallsService();
app.UseAuthentication();
但是當訂單改變時,索賠是。
app.UseAuthentication();
app.UseMyMiddlewareThatCallsService();
這取決於模式的實現,默認情況下身份驗證處理程序可能不會更新HttpContext.User
。
例如,cookie 身份驗證處理程序不會登錄當前用戶,而是僅生成身份驗證票並將其設置為 response 。
SignInAsync
創建一個加密的 cookie 並將其添加到當前響應中。 如果未指定 AuthenticationScheme,則使用默認方案。
如果您使用 cookie 身份驗證,您可以處理CookieAuthenticationEvents.OnSignedIn
事件來更新HttpContext.User
:
.AddCookie(IdentityConstants.ApplicationScheme,
opt =>
{
opt.Events = new CookieAuthenticationEvents
{
OnSignedIn = async ctx =>
{
ctx.HttpContext.User = ctx.Principal;
}
};
});
最后是工作代碼。
services.ConfigureApplicationCookie(options =>
{
options.Events.OnSignedIn = (context) =>
{
context.HttpContext.User = context.Principal;
return Task.CompletedTask;
};
});
if (access token in header or query parameter)
{
// Set the claims like in the Account/Login action from the interactive login form
var claims = ...;
// Local helper method, is used in other places, too
var claimsIdentity = await SignInAsync(httpContext, claims, false);
// Set user for the current request
// This works in that it's in User.Identity, but the auth events won't fire
httpContext.User = new ClaimsPrincipal(claimsIdentity);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.