承载错误 = Invalid_token 401 未经授权

LOK*_*321 5 asp.net-web-api2 postman bearer-token asp.net-core-mvc asp.net-core-1.1

 var identity = new GenericIdentity(user.Username, "Token");
            var claims = new List<Claim>();
            claims.AddRange(identity.Claims);
            foreach (RoleType r in roles)
            {
                claims.Add(new Claim("role", r.ToString()));
            }
            claims.Add(new Claim(JwtRegisteredClaimNames.Jti, tokenUid));
            claims.Add(new Claim(JwtRegisteredClaimNames.Iat,
                    ServiceHelper.ToUnixEpochDate(_jwtOptions.IssuedAt).ToString(), ClaimValueTypes.Integer64));

            var jwt = new JwtSecurityToken(
                issuer: _jwtOptions.Issuer,
                audience: _jwtOptions.Audience,
                claims: claims,
                notBefore: _jwtOptions.NotBefore,
                expires: _jwtOptions.Expiration,
                signingCredentials: _jwtOptions.SigningCredentials);

            var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt);

            var authToken = new AuthToken();
            authToken.TokenValue = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(encodedJwt));
            authToken.ExpirationInSeconds = (int)_jwtOptions.ValidFor.TotalSeconds;

            return authToken;
Run Code Online (Sandbox Code Playgroud)

上面的代码为我提供了以用户凭据作为输入的令牌。

每当我尝试使用 Postman 访问以下代码时,都会出现不记名错误 ="invalid_token" 和 401 未经授权。

 [HttpPost("addStudent")]
        [Authorize(Roles = "Director,Student")] 
        public IActionResult Post([FromBody]Student studentFields)
        {            
            if (s == null)
            {
                var student = _studentService.CreateStudent(studentFields);
                return createResponse(201, new
                {
                    studentInfo = student
                });
            }                          
            _logger.LogInformation("Student already added:{0}", s);
            return createErrorResponse("student already added", 404);            
        } 
Run Code Online (Sandbox Code Playgroud)

在标头中,我给出 Authorization = Bearer + token(从上述 API 生成的令牌)。

我不明白为什么它给我一个无效的不记名令牌和 401。

我见过很多例子,只要标头中给出了令牌,客户端就应该能够访问相应的 API。

raj*_*est 0

在 IdentityServer 中,必须将声明“aud”添加到 jwt 令牌中。为了做到这一点,启用与 .AddJwtBearer("Bearer", options => options.Audience="invoice" 下的 ApiResource 匹配的 option.audience 并设置 ApiResource

参考链接https://identityserver4.readthedocs.io/en/latest/topics/resources.html#refresources

public static readonly IEnumerable<ApiResource> GetApiResources()
{
return new List<ApiResource>
{
    new ApiResource("invoice", "Invoice API")
    {
        Scopes = { "invoice.read", "invoice.pay", "manage" }
    }        
};
   }
Run Code Online (Sandbox Code Playgroud)