I'm using ASP .NET Core Web API to receive Google ID token from my React client side. It works fine. Now I want to verify this ID token by sending it to Google's Oauth service en decode it to either create a new user or just send some user info to client side. I walked through these link1 link2 link3. But I'm very confused. Below what I tried, but got 400 bad request error. Any idea?
My api method
private const string GoogleApiTokenInfoUrl = "https://www.googleapis.com/oauth2/v3/tokeninfo?id_token={0}";
[HttpGet("[action]")]
public User GetUserDetails(string providerToken)
{
//verify the integrity of the ID token
//and use the user information contained in the token to establish a session or create a new account.
var httpClient = new HttpClient();
var requestUri = new Uri(string.Format(GoogleApiTokenInfoUrl, providerToken));
HttpResponseMessage httpResponseMessage;
try
{
httpResponseMessage = httpClient.GetAsync(requestUri).Result;
}
catch (Exception ex)
{
Console.WriteLine("error: " + ex);
return null;
}
if (httpResponseMessage.StatusCode != HttpStatusCode.OK)
{
Console.WriteLine("httpResponseMessage.StatusCode: " + httpResponseMessage.StatusCode);
return null;
}
var response = httpResponseMessage.Content.ReadAsStringAsync().Result;
var googleApiTokenInfo = JsonConvert.DeserializeObject<GoogleApiTokenInfo>(response);
IConfigurationRoot configuration = new ConfigurationBuilder()
.SetBasePath(AppDomain.CurrentDomain.BaseDirectory)
.AddJsonFile("appsettings.json")
.Build();
IConfigurationSection googleAuthNSection =
configuration.GetSection("Authentication:Google");
var SupportedClientsIds = googleAuthNSection["ClientId"];
if (!SupportedClientsIds.Contains(googleApiTokenInfo.aud))
{
Console.WriteLine("Google API Token Info aud field " + googleApiTokenInfo.aud + " not containing the required client id");
return null;
}
//If user does not exist, perform an insert to database
//If exist, create a session
return new User
{
Email = googleApiTokenInfo.email,
FirstName = googleApiTokenInfo.given_name,
LastName = googleApiTokenInfo.family_name,
Locale = googleApiTokenInfo.locale,
Name = googleApiTokenInfo.name,
UserId = googleApiTokenInfo.sub
};
}
Service code fragment
IConfigurationSection googleAuthNSection = configuration.GetSection("Authentication:Google");
var ClientId = googleAuthNSection["ClientId"];
var clientIds = new List<string>();
clientIds.Add(ClientId);
builder.Services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(o =>
{
o.SecurityTokenValidators.Clear();
o.SecurityTokenValidators.Add(new GoogleTokenValidator(clientIds));
});