Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/asp.net/29.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
C# 通过ASP.NET样板文件中的JWT令牌获取用户Id_C#_Asp.net_Asp.net Core_Aspnetboilerplate - Fatal编程技术网

C# 通过ASP.NET样板文件中的JWT令牌获取用户Id

C# 通过ASP.NET样板文件中的JWT令牌获取用户Id,c#,asp.net,asp.net-core,aspnetboilerplate,C#,Asp.net,Asp.net Core,Aspnetboilerplate,我将JWT Auth添加到我的asp.net样板项目中 我试图通过令牌获得用户身份(理想情况下是Id) 以下是我如何尝试做到这一点 [Authorize] [HttpGet] [ProducesResponseType(typeof(ShowJobDto), (int)System.Net.HttpStatusCode.OK)] public async Task<IActionResult> GetJobs(DateTime? from, DateTime?

我将JWT Auth添加到我的asp.net样板项目中

我试图通过令牌获得用户身份(理想情况下是Id)

以下是我如何尝试做到这一点

[Authorize]
    [HttpGet]
    [ProducesResponseType(typeof(ShowJobDto), (int)System.Net.HttpStatusCode.OK)]
    public async Task<IActionResult> GetJobs(DateTime? from, DateTime? to)
    {
        var identity = (ClaimsIdentity)User.Identity;
        List<ShowJobDto> jobs;
        var query = _jobRepository.GetAllIncluding(x => x.WorkOrder.Quote,
            x => x.WorkOrder.Quote.Property.Addresses,
            x => x.Engineer).Where(x => x.JobStatus != JobStatus.Pending);
        if (from != null && to != null)
        {
            jobs = await query.Where(x => x.JobDate >= from).Where(x => x.JobDate <= to)
                .ProjectTo<ShowJobDto>(ObjectMapper).OrderBy(x => x.TimeFrom).ToListAsync();
            return Ok(jobs);
        }

        jobs = await query.ProjectTo<ShowJobDto>(ObjectMapper).OrderBy(x => x.TimeFrom).ToListAsync();
        return Ok(jobs);
    }
[授权]
[HttpGet]
[产品响应类型(typeof(ShowJobDto),(int)System.Net.HttpStatusCode.OK)]
公共异步任务GetJobs(DateTime?from,DateTime?to)
{
var identity=(ClaimsIdentity)User.identity;
列出工作;
var query=\u jobRepository.GetAllIncluding(x=>x.WorkOrder.Quote,
x=>x.WorkOrder.Quote.Property.Addresses,
x=>x.Engineer),其中(x=>x.JobStatus!=JobStatus.Pending);
if(from!=null&&to!=null)
{
jobs=等待查询。其中(x=>x.JobDate>=from)。其中(x=>x.JobDate x.TimeFrom)。toListSync();
返回Ok(作业);
}
jobs=wait query.ProjectTo(ObjectMapper.OrderBy(x=>x.TimeFrom.toListSync();
返回Ok(作业);
}
我是邮递员,我像这样传递比尔代币

但当我在这里设置断点时,
var identity=(ClaimsIdentity)User.identity


我什么都没有。我的问题在哪里?

我使用以下方法来授权我的一个应用程序中的用户。 因此,我相信您可以对此代码进行一些更改,并获得所需的:

首先,您需要获取标题并从中剥离承载器

string authHeaderValue = Request.Headers["Authorization"];
然后,您需要使用ClaimsPrincipal验证您的令牌,它是System.Security.Claims的一部分

这是一个简单的课堂演示:

public ClaimsPrincipal GetClaims(string token)
{
    var handler = new JwtSecurityTokenHandler();
    var validations = new TokenValidationParameters
    {
         ValidateIssuerSigningKey = true,
         IssuerSigningKey = SIGNING_KEY,
         ValidateIssuer = false,
         ValidateAudience = false
    };

    return handler.ValidateToken(token, validations, out var tokenSecure);
}
请注意,ValidateToken是System.IdentityModel.Tokens.Jwt的一部分

下面是如何从代币中除去持票人

var tokenClaims = GetClaims(authHeaderValue.Substring("Bearer ".Length).Trim());
然后,您可以在您的令牌中查找用户标识或任何您需要的内容:

var userId = tokenClaims.Claims.Where(c => c.Type == ClaimTypes.NameIdentifier).FirstOrDefault().Value;
在我的例子中,我将userId存储在NameIdentifier中。因此,请根据您的设置进行更改

还有一件事。在测试应用程序时,请确保您的令牌未过期

希望能有帮助