Search code examples
c#.net-coreblazorgoogle-oauthasp.net-core-8

Google OAuth Token Exchange Not working in .net


Ok, so I am trying to set up OAuth to Google in my .net web app (Blazor).

I have the first part set up and working of requesting an authorization code.

However, once I have the Auth Code, then I am supposed to exchange it for a token and refresh token.

To do this, I am using the Google .net Auth libraries. I found a sample for it and try it, but the only result I ever get back is: Error:"invalid_grant", Description:"Bad Request", Uri:""

I have searched on this and found this. I have checked all of the issues possible, and none of them apply to my test. IE, the clock is not off, the user (me) has not revoked access, the password has not changed recently, etc etc.

It seems to me that this call should not be difficult, but I have spend hours trying to debug this. I am using the Official Library for this, but I suspect that something is not working correctly. This is the code:

GoogleAuthorizationCodeFlow authorizationCodeFlow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
{
    DataStore = dataStore,
    ClientSecrets = new ClientSecrets()
    {
        ClientId = clientId,
        ClientSecret = clientSecret
    }
});

try
{

    var tokenResponse = await authorizationCodeFlow.ExchangeCodeForTokenAsync(
        userId, // user for tracking the userId on our backend system
         authorizationCode,
        "https://localhost:7155/gauth", // redirect_uri can not be empty. Must be one of the redirects url listed in your project in the api console
        CancellationToken.None);
 

What should I do? Skip the .net lib and call the api directly from my own code?

The first call to get the auth code works perfectly every time, not sure why this step is so difficult.


Solution

  • GoogleAuthorizationCodeFlow is part of the google api .net client library which does not support Blazor authorization.

    Your best bet would be to drop the library and try to code the authorization yourself.