Google's OpenIDConnect return a Base64 token that cannot be parsed

怎甘沉沦 提交于 2019-12-20 04:37:22

问题


As exercise to understand OpenIDConnect, I am trying to authenticate in my web app with Google following this guide.

The problem is I cannot read the token that Google sends to my application>

var bytes = Convert.FromBase64String(codeEx.Id_token);
var token = Encoding.ASCII.GetString(bytes);

It fails in the first line saying: "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."

The doc states: "An ID token is a cryptographically signed JSON object encoded in base 64. "

For obvious reasons I cannot put the token here. I have tried:

  • The input is not a valid Base-64 string as it contains a non-base 64 character
  • Add '=' until the length is multiple of 4.
  • All together.

I get the code exchange response, and deserialize it with the NewtonSoft.Json library:

  var http = new HttpClient(handler);
  HttpResponseMessage result = await http.PostAsync("https://www.googleapis.com/oauth2/v3/token", postData);
  var json = JObject.Parse(await result.Content.ReadAsStringAsync());

  if (json.Property("error") != null)
      throw new Exception(json.Property("error").Value.ToString() + ":" + json.Property("error_description").Value.ToString());

  var codeEx = json.ToObject<CodeExchangeResponse>();

I don´t know if there is any potential issue with the encoding. I can see several ´-´and ´_´in the token.

Any idea about how to read the token?


回答1:


Use base64url decoding (instead of plain base64) after deserialization of the compact representation of the token as in:

var http = new HttpClient(handler);
var result = await http.PostAsync("https://www.googleapis.com/oauth2/v3/token", postData);
var json = JObject.Parse(await result.Content.ReadAsStringAsync());
var payload = json.id_token.split('.')[1];
payload = payload.Replace('-', '+').Replace('_', '/');
var base64 = payload.PadRight(payload.Length + (4 - payload.Length % 4) % 4, '=');
var token = Convert.FromBase64String(base64);



回答2:


From this post:

“id_token” is encoded in a format called JSON Web Token (JWT). JWT is the concatenation of “header”, “body”, “signature” by periods (.).

So you need to split id_token on . and decode just the 2nd segment:

var http = new HttpClient(handler);
var result = await http.PostAsync("https://www.googleapis.com/oauth2/v3/token", postData);
var json = JObject.Parse(await result.Content.ReadAsStringAsync());
var token = Convert.FromBase64String(json.id_token.split('.')[1]);


来源:https://stackoverflow.com/questions/28548920/googles-openidconnect-return-a-base64-token-that-cannot-be-parsed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!