'Jwt token Errorcode IDX12709

I generate a jwt token and after I try to Read it again, i get followed error message: IDX12709: CanReadToken() returned false. JWT is not well formed: '[PII of type 'System.String' is hidden

GenerateToken:

private string GenerateJwtToken(string username)
{
   var tokenHandler = new JwtSecurityTokenHandler();
   var key = Encoding.ASCII.GetBytes("$x3H*aG*?yKfh]Z/");
   var tokenDescriptor = new SecurityTokenDescriptor
   {
      Subject = new ClaimsIdentity(new[] { new Claim("username", username) }),
      Expires = DateTime.UtcNow.AddMinutes(30),
      SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
   };
   var token = tokenHandler.CreateToken(tokenDescriptor);
   return tokenHandler.WriteToken(token);
}

and the Fetch Header:

headers: {
   'Content-type': 'application/json',
   'Authorization': `Bearer ${sessionStorage.getItem("token")}`,
},

Here I read the token: "(backslash)"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6ImRldl9lZCIsIm5iZiI6MTY0MzQwMTc2OSwiZXhwIjoxNjQzNDAzNTY5LCJpYXQiOjE2NDM0MDE3Njl9.EjE9Va6v7XwQka4UH0y_2dC1eqpfUWAGs2Ipoq9LoGE(backslash)""

public async Task Invoke(HttpContext context, IAuthService authService)
{
   string token = string token = context.Request.Headers["Authorization"].FirstOrDefault()?.Split(" ").Last();
//...

private void attachUserToContext(HttpContext context, IAuthService authService, string token)
{
   try
   {
      var tokenHandler = new JwtSecurityTokenHandler();
      var key = Encoding.ASCII.GetBytes("$x3H*aG*?yKfh]Z/");
      tokenHandler.ValidateToken(token, new TokenValidationParameters //<- IDX12709
      {
         ValidateIssuerSigningKey = true,
         IssuerSigningKey = new SymmetricSecurityKey(key),
         ValidateIssuer = false,
         ValidateAudience = false,
         ClockSkew = TimeSpan.Zero
      }, out SecurityToken validatedToken);
      var jwtToken = (JwtSecurityToken)validatedToken;
      var userId = int.Parse(jwtToken.Claims.First(x => x.Type == "username").Value);
      context.Items["User"] = userId;
      }
      catch
      {
         // do nothing if jwt validation fails
         // user is not attached to context so request won't have access to secure routes
      }
}


Solution 1:[1]

like @jps said, it was because of the quotation mark.

new fetch call:

'Authorization': 'Bearer ' + token.replace(/"/g, ""),

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Feisser