OAuth Web Application Flow

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

Generate a client ID and secret by following the linked instructions, then come back to this page.

Step 2 - Setting up the client library

  1. In your google_ads_config.rb file, insert your client ID and secret.

    c.client_id = INSERT_OAUTH2_CLIENT_ID_HERE
    c.client_secret = INSERT_OAUTH2_CLIENT_SECRET_HERE
  2. In a terminal, navigate to the OAuth2 example.

  3. Use the googleauth library to generate an authorization URL from the client ID, client secret, scope, and callback URL as specified when setting up your cloud project.

    # Create an anti-forgery state token as described here:
    # https://developers.google.com/identity/protocols/OpenIDConnect#createxsrftoken
    state = SecureRandom.hex(16)
    user_authorizer = Google::Auth::UserAuthorizer.new(
        client_id, SCOPE, nil, callback_uri)
    authorization_url = user_authorizer.get_authorization_url(state: state)
  4. The code example prompts the user to visit a URL, but in a web application, you would likely redirect the user directly so it immediately prompts them to grant access.

    Consent screen allow

  5. In your callback method, use user_authorizer.get_credentials_from_code to get a user credentials object that contains the refresh_token. In the example, it just prints this to the console. However, in your web application, you will likely want to store the user's token along with their ID in a database. You can then retrieve their credentials the next time they sign in to your system, so they don't have to re-grant authorization each time.

Send feedback about...

Google Ads API
Google Ads API
Need help? Visit our support page.