AspNetCore5API控制器中的IHttpContextAccessor返回空的用户名声明
创始人
2024-09-20 08:00:52
0

在AspNetCore 5中,IHttpContextAccessor服务用于获取HTTP上下文信息。但是,有时在API控制器中使用IHttpContextAccessor时,它可能会返回空的用户名声明。这是因为在ASP.NET Core 5中修改了默认模板,使得Claims属性不再自动填充。

为了解决这个问题,我们需要手动填充Claims属性。我们可以通过在Startup.cs文件中添加以下代码来完成填充:

services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
    options.TokenValidationParameters = new TokenValidationParameters
    {
        ValidateIssuer = true,
        ValidateAudience = true,
        ValidateLifetime = true,
        ValidateIssuerSigningKey = true,

        ValidIssuer = "yourIssuer",
        ValidAudience = "yourAudience",
        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("yourSecretKey"))
    };

    // Add a delegate to get username from Claims
    options.Events = new JwtBearerEvents
    {
        OnTokenValidated = context =>
        {
            var claimsIdentity = context.Principal.Identity as ClaimsIdentity;

            if (claimsIdentity != null)
            {
                claimsIdentity.AddClaim(new Claim("username", context.Principal.FindFirstValue(ClaimTypes.Name)));
            }

            return Task.CompletedTask;
        }
    };
});

services.AddHttpContextAccessor();

这里我们首先将身份验证服务添加到DI容器中,然后在AddJwtBearer方法中添加JwtBearerOptions。在JwtBearerOptions中,我们设置了TokenValidationParameters并添加了一个委托来从声明中获取用户名,并将其添加到身份验证上下文中。最后,我们将IHttpContextAccessor服务添加到DI容器中。

这样,在我们的API控制器中,我们可以使用IHttpContextAccessor服务获取用户名声明,如下所示:

[ApiController]
[Route("[controller]")]
public class TestController : ControllerBase
{
    private readonly IHttpContextAccessor _httpContextAccessor;

    public TestController(IHttpContextAccessor httpContextAccessor)
    {
        _httpContextAccessor = httpContextAccessor;
    }

    [HttpGet("username")]
    public IActionResult GetUsername()
    {
        var username = _httpContextAccessor.HttpContext.User.FindFirstValue("username");

        return Ok(username);
    }
}

如此一来,我们就可以在API控制器中成功获取用户名声明了。

相关内容

热门资讯

透视有挂!aapoker安装包... 透视有挂!aapoker安装包怎么使用,aapoker脚本,专业教程(有挂秘笈)1、用户打开应用后不...
透视软件!wepoker有没有... 透视软件!wepoker有没有机器人,wepoker透视脚本是什么(透视)切实教程(有挂技巧)1、w...
透视计算!hhpoker一直输... 透视计算!hhpoker一直输有挂吗,hhpoker的辅助是真的吗,攻略教程(有挂秘笈);亲,关键说...
透视游戏!wepoker透视苹... 透视游戏!wepoker透视苹果系统,wepoker脚本(透视)2025新版总结(有挂详情)该软件可...
透视美元局!hhpoker脚本... 透视美元局!hhpoker脚本,aapoker辅助工具安全吗,2025新版教程(有挂规律)透视美元局...
透视规律!wepokerh5破... 透视规律!wepokerh5破解,wepoker辅助分析器(透视)存在挂教程(有挂介绍)1、用户打开...
透视计算!hhpoker辅助挂... 透视计算!hhpoker辅助挂,哈糖大菠萝有挂吗,AA德州教程(有挂详情);1、这是跨平台的哈糖大菠...
透视能赢!wepoker透视脚... 透视能赢!wepoker透视脚本网页,wepoker透视方法(透视)必备教程(有挂细节)1、wepo...
透视脚本!wepoker私人局... 透视脚本!wepoker私人局俱乐部辅助,约局吧德州可以透视吗,线上教程(有挂技巧);1、许多玩家不...
透视攻略!hhpoker透视脚... 透视攻略!hhpoker透视脚本,wepoker辅助透视软件,AI教程(有挂详情)透视攻略!hhpo...