Search code examples
c#oauth-2.0google-oauthgoogle-api-dotnet-client

Refresh token missing in Google Oauth response file


I'm implementing Google OAuth in ASP.Net MVC application using Google's OAuth .Net library. Below is my code.

IAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow(
  new GoogleAuthorizationCodeFlow.Initializer {
    ClientSecrets = new ClientSecrets {
        ** ClientId ** , ** ClientSecret **
      },
      DataStore = new FileDataStore( ** responsepath ** , true),
      Scopes = new [] {
        "https://www.googleapis.com/auth/userinfo.email",
        "https://www.googleapis.com/auth/gmail.send"
      },
      Prompt = "select_account"
  });

var userId = "user";
var uri = Request.Url.ToString();
var code = Request["code"];
if (code != null) {
  var token = flow.ExchangeCodeForTokenAsync(userId, code, uri.Substring(0, uri.IndexOf("?")), CancellationToken.None).Result;
  var oauthState = AuthWebUtility.ExtracRedirectFromState(flow.DataStore, userId, Request["state"]).Result;
  Response.Redirect(oauthState);
} else {
  var result = new AuthorizationCodeWebApp(flow, uri, uri).AuthorizeAsync(userId, CancellationToken.None).Result;

  if (result.RedirectUri != null) {
    Response.Redirect(result.RedirectUri);
  }
}

When user click's Google sign-in button, my page is redirected to Google authentication page. After successful authentication, my page is displayed again. When I check the responsepath, below file is created which contains access token, expiry time, etc.

Google.Apis.Auth.OAuth2.Responses.TokenResponse-user

When I run the above code locally in my visual studio debugging environment (IIS express), the above response file has "refresh_token" in it. When the same code is deployed in production environment (IIS), the "refresh_token" is missing is response file. I would like to know the reason behind it since I need refresh token for further processing.

Note: In both the cases, I revoked the application's access from my Google account before trying. So, this is not about "refresh_token" will be sent only for the first time.


Solution

  • Adding prompt=consent parameter while sending request to Google gives refresh token every time without fail.