繁体   English   中英

如何在.Net Core 中访问来自 HttpContext 的声明?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM