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
google_ads_config.rbfile, insert your client ID and secret.
c.client_id = INSERT_OAUTH2_CLIENT_ID_HERE c.client_secret = INSERT_OAUTH2_CLIENT_SECRET_HERE
In a terminal, navigate to the OAuth2 example.
googleauthlibrary 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)
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.
In your callback method, use
user_authorizer.get_credentials_from_codeto 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.