title: Google Calendar API Authentication .NET browser window
body: <p>I am using the latest version of the Google .NET Client API (v1.81). I am trying to connect to the Calendar Service using the following code</p>
  
  <pre><code>    var calendarService = new CalendarService(new BaseClientService.Initializer
      {
          HttpClientInitializer = GetCredential(),
          ApplicationName = "MyApp"
      });
  
      public UserCredential GetCredential()
      {
          UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
              new ClientSecrets { ClientId = _clientId, ClientSecret = _clientSecret },
              new[] { CalendarService.Scope.Calendar }.ToList(), "user", CancellationToken.None,
              new FileDataStore("Drive.Auth.Store")).Result;
  
          return credential;
      }
  </code></pre>
  
  <p>When I do this it opens a new Browser Window and asks for me to authenticate. I have previously authenticated and the key is stored and retrieved via FileDataStore.</p>
  
  <p>Why would it be asking me to authenticate again? The problem is because this code needs to run in a background service so it can't open browser tabs. </p>
  
  <p>Another issue I now am getting, when I try and authorise it opens up a new browser window, I select my credentials but the login page then tells me</p>
  
  <p>"The redirect URI in the request: <code>http://localhost:51773/authorize/</code> did not match a registered redirect URI"</p>
  
  <p>Why is it trying to use the Authorize url and not the AuthCallbackController. It also seems to randomly change the port number of the redirect uri making registering it impossible.</p>
  
  <p>The ultimate question probably is, if I have a web app and I want the users to sign in using their credentials via the web page and then reuse those credentials at a later date in a background task on the server, how do I go about that? I couldn't find any relevant sample app to show how. It appears the FileDataStore does not store the credentials so they can be reused. I have also implemented my own DataStore which saves them in the database which doesn't seem to work either. </p>
  
  <p>Digging further into this it appears I need offline_access. I have implemented this the same as <a href="https://stackoverflow.com/questions/22094599/google-analytics-oauth-with-accesstype-offline-in-c-sharp">Google Analytics OAuth with AccessType = Offline in C#</a> but it still prompts. How to I reuse the offline_access refresh token?</p>