Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-core/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Asp.net core 如何读取EF.NETCore中[AllowAnonymous]端点上的JWT令牌_Asp.net Core_.net Core_Entity Framework Core - Fatal编程技术网

Asp.net core 如何读取EF.NETCore中[AllowAnonymous]端点上的JWT令牌

Asp.net core 如何读取EF.NETCore中[AllowAnonymous]端点上的JWT令牌,asp.net-core,.net-core,entity-framework-core,Asp.net Core,.net Core,Entity Framework Core,我有一个端点,我希望它是公共的,但如果用户登录,我也会执行一些操作。如果我添加一个authorized属性,声明就在那里,但是如果我将其设置为AllowAnonymous,声明就为空 [HttpGet] [Authorize("Read")] //I want this to be AllowAnonymous public async Task<ActionResult<List<string>>> Get()

我有一个端点,我希望它是公共的,但如果用户登录,我也会执行一些操作。如果我添加一个authorized属性,声明就在那里,但是如果我将其设置为AllowAnonymous,声明就为空

    [HttpGet]
    [Authorize("Read")] //I want this to be AllowAnonymous
    public async Task<ActionResult<List<string>>> Get()
    {
        //This only works if I use [Authorize("Read")]
        var subject = context.HttpContext.User.Claims.FirstOrDefault(x => x.Type == ClaimTypes.NameIdentifier);

        return Ok(new List<string>() { "A", "B" });
    }
[HttpGet]
[Authorize(“Read”)]//我希望这是允许的
公共异步任务Get()
{
//仅当我使用[授权(“阅读”)]
var subject=context.HttpContext.User.Claims.FirstOrDefault(x=>x.Type==ClaimTypes.NameIdentifier);
返回Ok(新列表(){“A”,“B”});
}

我希望我解释得足够清楚。

HttpContext.User在使用AllowAnonymous时不可用(它为null)。但是,您可以通过使用authenticateSync()方法获取ClaimsPrincipal来绕过此问题。确保将AuthenticationScheme更改为您正在使用的任何方案(本例为JWT)


我使用JWT在Asp.Net Core 2和3.1上使用了这段代码,因此如果使用其他工具,您的里程可能会有所不同。

这正是我所需要的。非常感谢。
var auth = await HttpContext.AuthenticateAsync(JwtBearerDefaults.AuthenticationScheme);
if (auth.Succeeded)
{
   var claimsPrincipal = auth.Principal;
   var subject = claimsPrincipal.Claims.FirstOrDefault(a => a.Type == ClaimTypes.NameIdentifier);
   // use the subject claim as needed (actual value is "subject.Value")
}