API access on behalf of your clients (web flow) - jimper/googleads-dotnet-lib GitHub Wiki

This guide will walk you through how to setup OAuth2 for API access on behalf of your clients using web flow.

Step 1 - Creating OAuth2 credentials

Follow the steps for the product you're using to generate a client ID and secret, then come back to this page.

Step 2 - Setting up the client library

Adding OAuth2 support for your application (single login)

If your application manages only one account (or a hierarchy of accounts all linked under a single master MCC), then you don’t need to build OAuth2 flow into your application. You can instead use a utility named OAuth2TokenGenerator.exe to generate the necessary OAuth2 configuration. Refer to this wiki article for generating OAuth2 configuration using OAuth2TokenGenerator.

Adding OAuth2 support for your application (multiple logins)

If you manage multiple unrelated accounts, then you need to build OAuth2 sign-in flow into your application as part of adding OAuth2 support for your application. This involves three steps:

  1. Configure the following keys in your application’s web.config.
<add key="AuthorizationMethod" value="OAuth2" />
<add key="OAuth2ClientId" value="INSERT_OAUTH2_CLIENT_ID_HERE" />
<add key="OAuth2ClientSecret" value="INSERT_OAUTH2_CLIENT_SECRET_HERE" />
<add key="OAuth2Mode" value="APPLICATION" />
  1. Write an OAuth2 callback page and register it as a valid OAuth2 callback URL.

If you are using web flow for OAuth2, then you need to add a page to your web application to handle OAuth2 callbacks. The URL of this page should be added to "Redirect URIs" on the Google Developers Console page. You should also provide this URL as the value for the OAuth2RedirectUri setting in your application’s web.config.

This page should be able to handle two cases:

  • If any other page in your website detects that the user hasn't authorized your application to make API calls, then it needs to redirect the user to this page. The page needs to construct an Authorization Url and redirect the user to the Google OAuth2 server.
  • Once the user has authorized your application, Google OAuth2 servers will redirect the user back to this page. The page needs to use the OAuth2 authorizationCode to obtain an access token and optionally a refresh token. Then it needs to redirect the user back to the page the user originally came from. The page should also have an appropriate mechanism to share the Access and Refresh tokens between multiple pages (e.g. session, persistent store like database, etc.)

OAuth2 provides a parameter named State to allow you to distinguish between the two flows. The following code snippet uses this parameter to distinguish between the two use cases. When your app calls the callback page, the State parameter won't be set. The State parameter will be set when the Google OAuth2 servers call your callback page. Also, we will use Session to pass the parameters between the different pages.

protected void Page_Load(object sender, EventArgs e) {
  // Create an AdWordsAppConfig object with the default settings in
  // App.config.
  AdWordsAppConfig config = new AdWordsAppConfig();
  if (config.AuthorizationMethod == AdWordsAuthorizationMethod.OAuth2) {
    if (config.OAuth2Mode == OAuth2Flow.APPLICATION &&
        string.IsNullOrEmpty(config.OAuth2RefreshToken)) {
      DoAuth2Configuration(config);
    }
  }
}

private void DoAuth2Configuration(AdWordsAppConfig config) {
  // Since we use this page for OAuth callback also, we set the callback
  // url as the current page. For a non-web application, this will be null.
  config.OAuth2RedirectUri = Request.Url.GetLeftPart(UriPartial.Path);

  // Create an OAuth2 object for handling OAuth2 flow.
  OAuth2ProviderForApplications oAuth =
      new OAuth2ProviderForApplications(config);

  if (Request.Params["state"] == null) {
    // This is the first time this page is being loaded.
    // Set the state variable to any value that helps you recognize
    // when this url will be called by the OAuth2 server.
    oAuth.State = "callback";

    // Create an authorization url and redirect the user to that page.
    Response.Redirect(oAuth.GetAuthorizationUrl());
  } else if (Request.Params["state"] == "callback") {
    // This page was loaded because OAuth server did a callback.
    // Retrieve the authorization code from the url and use it to fetch
    // the access token. This call will also fetch the refresh token if
    // your mode is offline.
    oAuth.FetchAccessAndRefreshTokens(Request.Params["code"]);

    // Save the OAuth2 provider for future use. If you wish to save only
    // the values and restore the object later, then save
    // oAuth.RefreshToken, oAuth.AccessToken, oAuth.UpdatedOn and
    // oAuth.ExpiresIn.
    //
    // You can later restore the values as
    // AdWordsUser user = new AdWordsUser();
    // user.Config.OAuth2Mode = OAuth2Flow.APPLICATION;
    // OAuth2ProviderForApplications oAuth =
    //     (user.OAuthProvider as OAuth2ProviderForApplications);
    // oAuth.RefreshToken = xxx;
    // oAuth.AccessToken = xxx;
    // oAuth.UpdatedOn = xxx;
    // oAuth.ExpiresIn = xxx;
    //
    // Note that only oAuth.RefreshToken is mandatory. If you leave
    // oAuth.AccessToken as empty, or if oAuth.UpdatedOn + oAuth.ExpiresIn
    // is in the past, the access token will be refreshed by the library.
    // You can listen to this event as
    //
    // oAuth.OnOAuthTokensObtained += delegate(AdsOAuthProvider provider) {
    //    OAuth2ProviderForApplications oAuth =
    //        (provider as OAuth2ProviderForApplications);
    //    // Save oAuth.RefreshToken, oAuth.AccessToken, oAuth.UpdatedOn and
    //    // oAuth.ExpiresIn.
    //};
    Session["OAuthProvider"] = oAuth;
    // Redirect the user to the main page.
    Response.Redirect("Default.aspx");
  } else {
    throw new Exception("Unknown state for OAuth callback.");
  }
}
  1. Configure your AdsUser object to use OAuth2. The code snippet to do this is shown below.
private void ConfigureUserForOAuth() {
  AdWordsAppConfig config = (user.Config as AdWordsAppConfig);
  if (config.AuthorizationMethod == AdWordsAuthorizationMethod.OAuth2) {
    user.OAuthProvider =
        (OAuth2ProviderForApplications) Session["OAuthProvider"];
    if (user.OAuthProvider == null) {
      Response.SendRedirect("OAuthLogin.aspx");
    }
  } else {
    throw new Exception("Authorization mode is not OAuth.");
  }
}

You can now make calls to Ads API as usual.