Bearer error = Invalid_token 401 Unauthorized

1.9k views Asked by At
 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;

The above code is giving me the token taking user credentials as input.

Whenever I try to access the below code using Postman, it is giving me Bearer error ="invalid_token" and 401 unauthorized.

 [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);            
        } 

In the header, I am giving Authorization = Bearer + token(token generated from above API).

I don't understand why it is giving me an invalid bearer token and 401.

I have seen a lot of examples, whenever a token has been given in the header, the client should able to access the respective API.

1

There are 1 answers

0
rajquest On

In IdentityServer had to add claim "aud" to the jwt Token. In Order to do that enable option.audience that matches ApiResource under .AddJwtBearer("Bearer", options => options.Audience="invoice" and set ApiResource

Reference Link 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" }
    }        
};
   }