I have a problem with decoding from base64

26 Views Asked by At

In my client application I try to decode a JWT, but it keeps giving me this error

System.FormatException: 'The input is not a valid Base-64 string as it contains a non-base 64 character, more than two padding characters, or an illegal character among the padding characters.'

I am trying to decode like this:

 //token = eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE3MTExODcyODcsImlzcyI6IlRlc3QuY29tIiwiYXVkIjoiVGVzdC5jb20ifQ.pgzHJVC-iuvPaMuYzFNwPREFQsUVsLlKia11AM3ai1Y
 string[] tokens = token.Split('.');

// first tokenPart = eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9 and works
// second tokenPart = eyJleHAiOjE3MTExODcyODcsImlzcyI6IlRlc3QuY29tIiwiYXVkIjoiVGVzdC5jb20ifQ and fails

 foreach (string tokenPart in tokens) 
 {
     string decodedString = System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(tokenPart));
 }

The error appears for the second tokenPart, an example of this is

eyJleHAiOjE3MTExODQ3MDUsImlzcyI6IlRlc3QuY29tIiwiYXVkIjoiVGVzdC5jb20ifQ

When I tried to decode the same string online here it works without problems, the result of the decoding is this:

{"exp":1711179891,"iss":"Test.com","aud":"Test.com"}

I found How do I decode a base64 encoded string? and tried all the answers, but nothing helped me.

The string was produced in my web application like this

  public string GenerateJSONWebToken(int userID, string key, string issuer)
  {
      SymmetricSecurityKey securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(key));
      SigningCredentials credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);

      JwtSecurityToken token = new JwtSecurityToken(
          issuer,
          issuer, 
          null,
          expires: DateTime.Now.AddSeconds(10),
          signingCredentials: credentials);

      return new JwtSecurityTokenHandler().WriteToken(token);
  }
0

There are 0 best solutions below