Search code examples
c#asp.net-coregoogle-apigoogle-drive-apigoogle-oauth

How to refresh token in .net google api v3?


I managed to get the access_token and refresh_token on front end and now its stored in a database, On the backend .netcore application I create googlecredential with

var cred=googleCredential.fromAccessToken(access_token);

but this one doesn't refresh on its own and I have no idea how to refresh this. I can send a post request to their rest api and refresh it but I need to know when "creds" has expired to send that refresh request. PS know that the tokens are in a database so using anything but .fromaccesstoken is not an option.

EDIT: Complete code can not be shared but here's how the application's flow is going. On a reactJS application I get the authorization code via react-google-login module

<GoogleLogin
                  
                  clientId="xxx"
                  buttonText="Login"
                  onSuccess={this.responseGoogle}
                  onFailure={this.responseGoogle}
                  cookiePolicy={"single_host_origin"}
                  scope="https://www.googleapis.com/auth/drive.readonly"
                  accessType="offline"
                  prompt="consent"
                  responseType="code"
                />

this returns an authorization code as the only response body, this response is then used with another endpoint to exchange for refresh and access token at front end, these tokens are sent to a backend endpoint which stores them in a db. Now the server side can create a googlecredential object via

this.googleCredentials=GoogleCredential.FromAccessToken(this.googleAccessToken);

Only problem being this doesnt handle the refreshing on its own so you have to somehow implement it.


Solution

  • Since I can't find another way to refresh when GoogleCredentials object is created via fromtoken(ACCESS_TOKEN) what I've done is sending a post request with the refresh token that I have to the rest endpoint at the backend and get a new access_token. Another problem faced was finding out when the access token was expired for which no solution could be found. But it returns a 401 exception at creating the drive folders via drive service in my case

    var res = await this.driveService.Files.Create(folder).ExecuteAsync()

    here res will raise an exception and I just put it in a try block and got the new access token via http request in catch and ran the statement again (hint: recursion)

    Hope this helps anyone, but better proposed solutions will be welcomed. Please understand that this is going to be a backend solution reading refreshtoken from database.