How to set up smartphones and PCs. Informational portal
  • home
  • Operating Systems
  • OAuth VKontakte: use for personal gain. OAuth: describing the protocol in a simple and understandable language

OAuth VKontakte: use for personal gain. OAuth: describing the protocol in a simple and understandable language


  1. Opening the built-in browser with the authorization page
  2. The user is asked to confirm the grant of rights
  3. If the user agrees, the browser will redirect to the stub page in the fragment (after #) whose URL is added access token
  4. The application intercepts the redirect and receives access token from page address
This option requires raising a browser window in the application, but does not require a server side and an additional server-to-server call to exchange authorization code on the access token.
Example
Open a browser with an authorization page:
> GET /oauth/authorize?response_type=token&client_id=464119 HTTP/1.1 > Host: connect.mail.ru

After the user grants the rights, a redirect occurs to the standard stub page, for Mail.Ru this is connect.mail.ru/oauth/success.html:
< HTTP/1.1 302 Found < Location: http://connect.mail.ru/oauth/success.html#access_token=FJQbwq9&token_type=bearer& expires_in=86400&refresh_token=yaeFa0gu

The application must intercept the last redirect, get from the address access_token and use it to access protected resources.

Login and password authorization

Authorization by login and password is a simple POST request, which returns access token. This scheme is nothing new, but is included in the standard for generality and is recommended only when other authorization options are not available.
Example
> POST /oauth/token HTTP/1.1 > Host: connect.mail.ru > Content-Type: application/x-www-form-urlencoded > > grant_ty [email protected] corp.mail.ru& password=qwerty< HTTP/1.1 200 OK < Content-Type: application/json < < { < "access_token":"SlAV32hkKG", < "token_type":"bearer", < "expires_in":86400, < "refresh_token":"8xLOxBtZp8", < }
Description in specification

Restoring a previous authorization

Usually, access token has a limited shelf life. This can be useful, for example, if it is transmitted over open channels. To avoid forcing the user to log in after the expiration date access token"and, in all the above options, in addition to access token"u can come back again refresh token. It can be obtained access token using an HTTP request, similar to login and password authorization.
Example
> POST /oauth/token HTTP/1.1 > Host: connect.mail.ru > Content-Type: application/x-www-form-urlencoded > > grant_type=refresh_token&client_id=31337&client_secret=deadbeef&refresh_token=8xLOxBtZp8< HTTP/1.1 200 OK < Content-Type: application/json < < { < "access_token":"Uu8oor1i", < "token_type":"bearer", < "expires_in":86400, < "refresh_token":"ohWo1ohr", < }

A popular protocol that allows social services to integrate with each other and provides a secure way to exchange personal information. OAuth can link 2 services together, each of which has its own user base - these are what I call "social" in this case. When you start working with OAuth, the first impression is that the protocol is very complicated and redundant. In this article, I will try to explain the basics of OAuth in human terms.

Cross authorization example

Let's go back to 2005 and imagine that we are writing a social network. It has a form for importing contacts from the GMail address book. What do you need to access your GMail contacts? Of course, the login and password from the box. But if we ask them to enter them on our site, the user will suspect something is wrong. Where is the guarantee that we do not save entered passwords on the server? Therefore, we want the password to be entered only on the GMail website, and after that access to contacts through the GMail API was provided to our social network (perhaps temporarily). Let's agree on terms.
  • consumer: consumer; script for processing the contact import form in a social network.
  • Service Provider: data provider; GMail containing address book data of interest to the Consumer.
  • user: A user who has an account with both the Consumer and the Service Provider.
  • protected resource: personal data; contacts from the address book on GMail (i.e. Service Provider resources).
  • Provider API: A GMail API that allows any script to get contacts from the GMail address book.
OAuth task- make sure that the User has the opportunity to work on the Consumer service (in the social network) with the protected data of the Service Provider (GMail), entering the password for this data exclusively on the Service Provider and remaining on the Consumer's website. Not so difficult, right?

How is OAuth different from OpenID?

OAuth is often referred to as a "robot protocol", as opposed to OpenID, a "user protocol". Don't confuse them!
  1. OpenID is a protocol for accelerated registration. OpenID allows the user to get an account on any service without entering a password if he is already registered somewhere else on the Internet. (And then you can enter the service without entering a password, being authorized "somewhere".) For example, if you have a Yandex account, you can use it to "log in" to any service that supports OpenID authorization.
  2. OAuth is a protocol for authorized access to a third party API. OAuth allows a Consumer script to gain limited API access to a third-party Service Provider's data if the User gives the go-ahead. Those. it is a means to access the API.

Police analogy

Imagine that you are a member of the Criminal Investigation Department looking for ends in a 1973 WebMoney theft case. Let's agree on terms:
  • OAuth Consumer: Criminal investigation.
  • user: Officer of the Criminal Investigation Department.
  • Service Provider: Card index of the archive of crimes.
  1. OpenID: an employee of the Criminal Investigation Department (User) comes to the Card Index (Service Provider), presents a credential (Authorization) at the entrance and sorts through the cards on the spot in search of information.
  2. OAuth: an employee of the Criminal Investigation Department (User) calls the Card Index (Service Provider) directly from work (Consumer). He reports his last name; if he is recognized (Authorization), he asks for a list of all crimes for the year 1973 (API call).
As you can see, OpenID and OAuth are different things. OpenID allows you to access certain resources right on the spot. OAuth provides getting some information from a remote service via an API.

Outline of this article

Before moving on to the main part, let's see exactly how we will move.
  1. Let's consider the problems that arise during the "manual" implementation of cross-authorization.
  2. Let's talk about what an "application" is and who a Consumer is.
  3. Let's touch on the basics of cryptography.
  4. Let's denote the demo application that we will write in this article.
  5. Let's decide on a test OAuth server on which we will experiment.
  6. Let's go through all the steps of the OAuth protocol and provide the script sources.

About the invention of bicycles

A good way to understand something is to do it yourself, stepping on all the rakes along the way. Now we will reinvent the wheel: we will try to imagine how we would solve the problem of interaction between a Consumer and a Service Provider without any standardized protocols.

First, let's write the GMail contact import form itself: Next, we'll ask the GMail developers to make it so that when a user navigates to the /auth.php URI, he will be given an authorization form (in our cycling world, GMail is written in PHP). After successfully entering the password, the user should be redirected to the site whose URL is specified in the retpath parameter. Also, some secret key must be passed in the URL, which can already be used to access the GMail API.

So, after entering the password, the user will return to our site at the following address: And we will turn to the GMail API from the /import.php script, pass the key Y49xdN0Zo2B5v0RR to it and load the contacts: Well, let's now count the rake (because the bumps it will be too late to count).

The first rake: substitution of the return address retpath

Well, of course, you guessed that the attacker will first place a link on his site and force you to click on it. As a result, he will receive the secret key returned by GMail, and hence your contacts:

The second rake: "eavesdropping" of the secret key

Suppose we somehow protected retpath, and now it can only point to our site. But the problem with the secret parameter remains. The secret can be peeped from behind or intercepted by listening to WiFi traffic. Or your site will someday have an XSS vulnerability that allows you to "pull" the secret key. If set to secret, an attacker will be able to read your address book. So, you need to secure the secret from being intercepted (ideally, don't pass it through the URL at all).

Third rake: too many redirects

If each API call requires a different secret, then we will have to organize as many redirects to the Service Provider site as we have calls. With intensive use of the API, this works very slowly, and inconveniently in order ...

Rake Four: Poor Consumer Identification

GMail, of course, wants to know who is using its API. Allow access to some sites and deny access to others ... So, when forming a request in the form of importing contacts, the Consumer (website) must be “presented” to the Service Provider (GMail). In our case, this function is partially performed by retpath (the site name in it), but this method is not universal, because the "presentation" mechanism must also be involved when calling API methods.

Foundation of OAuth

It is noteworthy that there are still many "underwater rakes". I will not describe them here, because this rake lies in the Mariana Trench (deep, 10920 m). It would take a dozen pages to describe vulnerabilities. So I'll jump straight to the description of OAuth, where all the problems have already been solved.

Application = Consumer + API access

When working with OAuth, it is important that the term Consumer is not limited to the meaning of "website". Consumer is some Appendix, and where it is located is not so important. Examples of Consumers from real life: But you can't cook porridge from OAuth alone. Indeed, all that OAuth gives is the ability to log in to a remote service (Service Provider) and make authorized requests to the API. It does not matter how this API is arranged: it can be pure SOAP, REST approach, etc. The main thing is that each API method accepts special parameters as input, passed according to the OAuth protocol.

Token = Key + Secret

One of the principles of OAuth is that no private keys should be passed in public in requests (we discussed why in the example above). Therefore, the protocol operates with the concept of Token. The token is very similar to a login + password pair: the login is open information, and the password is known only to the transmitting and receiving side. In terms of OAuth, the login analog is called Key, and the password analog is Secret. The situation when the Secret is known only to the sender and recipient, but no one else, is called Shared Secret.

So, if the Consumer and the Provider somehow agree among themselves on the Shared Secret, they can openly exchange the corresponding keys (Key) in the URL without fear that interception of these keys will be dangerous. But how to protect URL with Key from forgery?

Message = Document + Digital Signature

"Digital signature" sounds scary, but it's actually pretty obvious. When you sign a document with a pen, you certify that this document was written by you and not by someone else. Your signature is, as it were, “added” to the document and goes with it in “one set”.

Similarly, a digital signature is added to some block of data, certifying that the person who generated this data is not impersonating another. A digital signature does not encrypt a document, it only guarantees its authenticity! Signing allows the same Shared Secret, which is known to the recipient and sender, but no one else.

How it works? Let our $sharedSecret = 529AeGWg, and we whisper it in the ear of the receiving party. We want to transmit the message "My phone is 1234567" with guaranteed protection against falsification by an attacker.

  1. Consumer adds a digital signature to the message, in general $transfer = $message . "-" . md5($message . $sharedSecret); // $transfer = "My phone is 1234567" . "-" . md5("My phone is 1234567" . "529AeGWg")
  2. The Service Provider takes the data, splits it back into 2 parts - $message and $signature - and does exactly the same operation: $signatureToMatch = md5($message . $sharedSecret); // $signatureToMatch = md5("My phone is 1234567" . "529AeGWg"); Then it remains only to compare the resulting $signatureToMatch value with what was in the received $signature data and report a fake if the values ​​did not match.

Demonstration of how OAuth works with a simple application

To get a feel for OAuth, we need two things:
  1. Script that implements the client part of the protocol. I wrote just such a small PHP script (zip archive link). This is a widget that can be inserted into PHP sites.
  2. An OAuth test server where we can experiment. For this purpose, it is convenient to use RuTwit: there is a page http://rutvit.ru/apps/new , which allows you to add a test application in 30 seconds. (By the way, the return URL in the form can be omitted - we still pass it from the test script.)
Looking at the code of the demo script and reading the explanations later in the article, you can understand the details of the protocol.

You can embed this widget on any PHP site by simply copying its code and tweaking the layout. All tweets from the RuTwit service marked with the specified hash tag are displayed, and it is also possible to add new tweets (this is where OAuth comes into play). The widget uses the RuTwit API and OAuth authorization, which, by the way, are the same as the Twitter API standard. You can run this script on your test server. To do this, you need to perform three steps:

  1. Download the script code and deploy it to any convenient directory on the web server.
  2. Register a new test application with the OAuth server.
  3. After registering the application, replace the OA_CONSUMER_KEY and OA_CONSUMER_SECRET parameters in the script with the values ​​received from the server.

Application registration and settings

Let's talk about where applications come from and how the Service Provider finds out about them. Everything is quite simple: Service Provider has a special application registration form that anyone can use. Here is an example of such a form:


After registering the application, you are given 5 parameters that are required to work with OAuth. Here's what they might look like:


Here Consumer key and Consumer secret are a kind of "login + password" of your application (remember the above conversation about tokens? this is just one of them). Let me remind you that a Consumer secret is a Shared Secret, known only to the sender and recipient, but to no one else. The remaining 3 values ​​specify service URLs, the meaning of which we will now consider.

OAuth = Fetch Request Token + Redirect to Authorization + Fetch Access Token + Call API

In the GMail example, we used 2 types of remote calls: a) redirect through the browser; b) accessing the API from within the script.

And we uncovered a number of security issues, which suggests that there should be more challenges. This is what happens in OAuth: more intermediate requests are added from the Consumer script to the Provider, operating with tokens. Let's take a look at them.

  1. Form submission processing. It's not part of OAuth, but part of our application. Before accessing the API of the Provider, we must receive an order for this action from the user. Here is an example of such an order:
  2. Fetch Request Token (internal request).
    • The Consumer script calls Request token URL Provider: for example, api.rutvit.ru/oauth/request_token . The request transmits the Consumer key - "application login", and the request itself is signed using the Consumer secret - "application password", which protects it from forgery.
    • In response, the Provider generates and returns a garbage-filled token called the Request Token. We will still need it, so we need to save it somewhere - for example, in the $S_REQUEST_TOK session variable.
  3. Redirect to Authorization (via browser redirect). Now our application has a unique Request Token. It is required to obtain permission from the user to use this token, i.e. ask him authorize Request Token.
    • Consumer redirects the browser to a specific Authorize URL Provider: for example, api.rutvit.ru/oauth/authorize . The Request Token Key is passed in the parameters.
    • The Provider displays an authorization form for its user and, if he is authorized, redirects the browser back. Where exactly? And we specify this in the oauth_callback parameter.
  4. Fetch Access Token (internal request). So, the browser has returned to our application after a series of redirects. This means that the authorization on the Provider was successful, and the Request Token is allowed to work. However, in OAuth, for security purposes, each token has its own, strictly limited purpose. For example, the Request Token is used only to receive confirmation from the user, and nothing else. To access resources, we need to get a new token - Access Token - or, as they say, "exchange Request Token for Access Token".
    • Consumer refers to Access token URL- for example, api.rutvit.ru/oauth/access_token , - and asks to give him an Access Token instead of his Request Token. The request is digitally signed based on the Request Token secret.
    • The Provider generates and returns an Access Token filled with garbage. It also marks in its tables that API access is allowed for this Access Token. Our application must keep the Access Token if it is going to use the API in the future.
  5. Call API (internal request). Well, now we have an Access Token, and we can pass its key when calling API methods.
    • The Consumer generates a request to the Provider's API (for example, using a POST request according to the REST ideology). The request passes the Access Token Key, and it is signed using the Shared Secret of this token.
    • The Provider handles the API call and returns data to the application.

End of script: widget output

The end of the script should be clear and without detailed explanations.
Listing 14: End of script: widget output
// end case ) ) // Get all available tweets. $text = file_get_contents("http://api.rutvit.ru/search.xml?rpp=5&q=" . urlencode("#" . TAG)); $TWEETS = new SimpleXMLElement($text); // Shortcut for displaying a message with recoding and quoting. function e($text, $quote = 1) ( $text = iconv("utf-8", ENCODING, $text); echo $quote? htmlspecialchars($text) : $text; ) ?>
status as $tweet) (?>
user->screen_name)?>: text_formatted, 0)?>
?action=form_is_sent" style="margin: 1em 0 0 0">

Useful links on OAuth

  • rutvit
Add tags

As a result, a client application using the AdWords API can access an AdWords account without the user's email address and password.

Create OAuth2 Credentials

To create an OAuth2 credential, follow these steps:

Application type definition

First, you need to define application type the one you want to create. There are two types of apps in the AdWords API:

  • application to be installed(recommended);
  • web application.

Use the table below to determine the type of application you need.

What to choose Situation
Installed application(recommended)
  • You manage all your AdWords accounts with one top-level manager account.
  • Are you just getting started or want to get started quickly.
  • Your application will work with one set of AdWords accounts with multiple users.
Web application
  • You want to authenticate to give different users different access rights to your AdWords account data.
  • You need to create multiple sets of credentials, for example, to manage third-party accounts.
  • Your app requires callback URLs that are not supported in the apps you install.
Attention!Even if you are developing a web application, you can still choose which application to install. The main difference is whether you need to call back after the token is issued. For example, if you use one top-level manager account to manage all of your AdWords accounts, the application you install must be registered, even if the client application is available online. Note.are discussed below. If you do not require the features of a service account, we strongly recommend that you use the authorization process for the installed or web application.

Create a client ID and passcode

Once you've identified your application type, click the appropriate tab below and follow the instructions to create a client ID and passcode.

Installed application

  1. open
  2. Create project Create.
  3. Create Credentials, and then - OAuth Client ID.
  4. Save
  5. In chapter Application type select Other types and provide the required information.
  6. Click Create.
  7. identifier and The secret key
Web application
  1. open
  2. From the drop-down menu of projects, select Create project, then specify the name of the project and, if necessary, change its ID, then click the button Create.
  3. On the Credentials page, select Create Credentials, and then - OAuth Client ID.
  4. You may be prompted for a product name. In this case, press Customize Access Request Window, enter the requested information and click Save to return to the Credentials screen.
  5. In chapter Application type select Web application. Follow the instructions to provide JavaScript sources and/or redirect URIs.
  6. Click Create.
  7. On the page that appears, copy identifier and The secret key client - you will need them when setting up the client library.

Follow the instructions below to configure the use of OAuth2 credentials with your language's client library.

Note.If you choose not to use one of our client libraries, you will need to implement the processes for or yourself.

OAuth2 Playground

An alternative way to generate OAuth2 credentials is to use OAuth2 Playground. Combined with the Google API Console, this system allows you to create OAuth2 tokens yourself.

The OAuth2 Playground system is intended for those users who need access to accounts only for one manager account or AdWords user. If you need to prompt for credentials for multiple users, then it's better to use the client libraries as described above.

Setting

Warning.To use OAuth2 Playground, you need to create client ID for . it the only one application type that works with OAuth2 Playground. Read more in the section above.

How to get client ID and secret key

  1. open
  2. Select an existing project from the drop-down menu or create a new one.
  3. On the Credentials page, select Create Credentials, and then - OAuth Client ID.
  4. In chapter Application type select Web application.
  5. In the section, add the following line: https://site/oauthplayground
  6. Click Create.
  7. write down identifier and The secret key clients listed on the page that appears. You will need them in the next step.

How to create tokens

Warning.The Google account you're signed into in your browser determines which AdWords accounts you can access using the generated OAuth2 credentials. It may be best to complete these steps in incognito mode or without signing in to your Google account. It is likely that you will need to use credentials that are not related to the account you were in when you received the client ID and secret key.

How to remove OAuth2 Playground from Client ID

Because you already have refresh token, you no longer need to use OAuth2 Playground as the allowed redirect URI. To remove this system from the list, follow these steps:

  1. Go to .
  2. Select your project from the dropdown menu.
  3. On the Credentials page, select the client ID name.
  4. Remove https://site/oauthplayground in the field Allowed Redirect URIs. Please note that you must leave at least one The redirect URI.
  5. Click Save.

So you have OAuth credentials. You can now query the AdWords API and use it for the required client library.

OAuth2 Service Accounts

This section describes how to access the AdWords API using service accounts.

A service account is an account that belongs to an application and not to an individual end user. Service accounts provide interaction between a web application and a Google service. Your application calls API on behalf of a service account without direct user involvement.

The AdWords API allows service account access through G Suite domains.

The service account implements an OAuth2 process that uses a key file that is available only to your application instead of authorizing the user.

Using service accounts provides two significant benefits:

  • Authorization of application access to the Google API is carried out at the setup stage. This avoids the hassle of requiring user intervention or caching tokens on other OAuth2 flows.
  • Impersonation of other users in the application, if necessary, is done as part of the OAuth2 assertion process.
Note. If you are not using special domain features, such as impersonation, it is highly recommended to use a process for . Within the processes for OAuth2 installable and web applications, user participation is required only once, at the time of granting access to the account.

Alternative to service accounts

Service accounts are widely used to provide programmatic access to APIs via the OAuth2 protocol without user intervention.

However, setting up these accounts to work with the AdWords API is not easy. An easier alternative is with a persistent refresh token. This approach allows the application to request new access tokens at any time.

As part of this process, you need to set up application authorization through the client library as described above. This only needs to be done once, as Google OAuth2 refresh tokens never expire.

Requirements

  • A G Suite domain that you own, such as mydomain.com or mybusiness.com.
  • AdWords API developer token and preferably a test account.
  • for the language being used.

Configuring access for a client account

First, you need to create a service account key in the Google API Console.

  1. Sign in to your G Suite account, open .
  2. From the drop-down menu of projects, select Create project, then enter the required information and click the button Create. The new project will appear in the active list.
  3. From the menu in the top left corner, select IAM and administration, and then - Service Accounts in the menu on the left.
  4. Click Create a service account at the top of the page.
  5. Specify the name of the service account.
  6. Check box Create a new private key and select JSON key type.
  7. Check box Enable Data Access Delegation in G Suite Domain and enter the product name for the access request window.
  8. Click Create. The download of the JSON key file will start. Save the file in a safe place where only you have access.
  9. On the page Service Accounts a new service account will appear.
Note. Because user impersonation can be controlled only at the domain level, in order to use service accounts and the approval process with Google OAuth2 services, you need your own domain registered with G Suite. All domain users using a service account with the appropriate permissions can impersonate any domain user.

Security issues

Because G Suite is managed at the domain level, you need to securely protect the key file that allows authorized accounts to access Google services. This is especially important because we provide a service account with the ability to impersonate any user in the domain.

It is also recommended that each service account be granted access to only one Google API. To do this, use the field scope, which is described in the next section. This preventive measure allows you to limit the amount of data that is open to unauthorized access in the event of a compromise of the key file.

How to provide impersonation capabilities

To give your service account impersonation capabilities, follow these steps:

You can now access your AdWords account using your service account as part of the OAuth2 approval process.

Setting up the client library

Select a language for instructions on setting up the client library.

Note.If you choose not to use one of our client libraries, you will need to implement the process yourself.

Optimizing OAuth2 Requests

If your application does not use credential sharing, this can significantly increase the number of queries sent to Google. As a result, our servers may impose restrictions on such an application, which will slow down its performance.

This section describes how to optimize OAuth2 credential management so that your application interacts more effectively with the AdWords API.

Attention!Under the term credentials this refers to the entire set of attributes of an OAuth2 credential, including the access token and its expiration date.

Credential Distribution Strategies

Distributing credentials across API requests improves performance and avoids overhead and errors due to constraint violations.

The strategy for distributing credentials depends on the structure of the application.

In multithreaded applications, each thread's session must use the same credentials.

In multi-process and distributed applications, some infrastructure must be implemented to pass credentials between processes. In addition, thread blocking and race conditions must be avoided.

In an application that is both multi-process/distributed and multi-threaded, each process needs to combine both strategies.

The following are strategies for authenticating a single AdWords account, such as the top manager account in a hierarchy.

It then describes how to adapt these strategies for .

Multithreaded Applications

In multi-threaded applications, credentials must be available to different threads. Credential updates should be done synchronously to avoid race conditions.

This diagram shows the threads that submit requests to the AdWords API at runtime. A shared pool of sessions (users) is used. Note that each session must use the same credential object. In response to each API request, the thread receives the corresponding session (user). If an access token needs to be refreshed, it must be done synchronously to avoid race conditions. In other words, the credential object must be thread-safe.

Client libraries make it easy to pass credentials between threads. Each client library has a session (or user) object with credentials that it reuses throughout its life cycle. To use credentials across sessions, you must apply them when you create each session. In all client libraries, credentials are a thread-safe object that is synchronously updated when the access token expires.

For example, in the Java client library, you need to create a singleton Credential class and use it for all sessions.

Multi-process and distributed applications

In multi-process and distributed applications, the allocation of credentials must be done continuously. To avoid a race condition where multiple servers try to update credentials at the same time (leading to an excessive number of update requests), we recommend that you force the update and provide updated credentials to all processes and servers.

For example, a single task or service might update credentials periodically and pass them to the data store, where they will be used by different servers.

The diagram shows the periodic updating of credentials and writing their properties to the data store. All servers then receive credentials before making a request to the API.

Update task

The update task periodically updates the credentials and sends them to the data store. This task should not wait for the current credentials to expire, as this will cause the application to fail for some time due to lack of valid credentials.

The best alternative is a periodic forced refresh, which replaces the credentials in the data store with new ones each time. The update task should run well before the current credentials expire to allow enough time in case a transient error occurs. You can start by running an update every 15 minutes.

Note.If the credential access token expires while an API request is being processed, the request will still succeed. For example, if you've created a long-running query and there's less than a minute left to access, the results will still be returned.

Data store

The datastore is used to provide credentials to different processes and servers.

To do this, you can use an existing data store or create a specialized one through which servers will receive credentials. Possible solutions include cache servers (such as Memcached or Infinispan) and NoSQL data stores (such as MongoDB).

The main purpose of a data warehouse is to provide a reliable interface for all servers accessing the API. Its work needs to be optimized for fast data reading: servers and processes will read credentials more often than they are updated.

Remember that credentials must be stored securely.

When saving credentials, you must save the expiry_time property (current time + expires_in) and refresh_token along with the access_token property. The expiry_time property (token expiration) is calculated using the following formula: access_token renewal request time + expires_in time (token expiration date).

Server Pool

Each server in the pool gets the newest credentials from the data store before sending a request. As long as the update task runs successfully, the credentials will be valid. However, if an update task or datastore fails, there must be a fallback mechanism.

If the server or process is unable to obtain credentials from the datastore, or if the credentials have expired, the server must update its credentials so that the application continues to work with the API until the problem is resolved.

In multi-threaded processes, you must use the same strategy for distributing credentials between threads.

Multiple Account Authentication

The credentials created for the AdWords manager account can be used to access all sub-accounts. Users with a single manager account usually only need to create credentials for a top-level manager account to authorize the app for all of their AdWords sub accounts.

In other cases, the app needs access to AdWords accounts that are not related to each other in the manager account hierarchy. This situation requires you to create and maintain multiple credentials for different accounts, such as for each AdWords client account you have access to, or for each top-level manager account in independent hierarchies.

You can follow these strategies for and for applications with minimal modifications. When using shared storage, the credentials must be indexed by the customerId of the account to ensure that the credentials are associated with the required account. In addition, the update task should update them in time. After connecting a new account, you may need to start it.

Finally, in multi-threaded applications, you should distribute the credential object only among the threads running in the account it is associated with.

How OAuth2 works

Note. The AdWords API does not yet support simultaneous sign-in with a data request (hybrid) or delegation of authority at the domain level (2LO).

Scope

An access token can provide varying degrees of access to data. The mutable scope parameter defines the set of resources and operations to which the token provides access. When requesting an access token, your application sends one or more values ​​to the scope parameter.

Below are the current and legacy scope for the AdWords API.

offline access

A client application using the AdWords API typically requests offline access. This can happen if an application needs to run batch jobs when a user is browsing your site without an Internet connection.

Installed apps use offline access by default.

HTTP request header

The HTTP header in each request to the AdWords API server must include the following form:

Authorization: Bearer THE_ACCESS_TOKEN

POST … HTTP/1.1 Host: … Authorization: Bearer 1/fFAGRNJru1FTz70BzhT3Zg Content-Type: text/xml;charset=UTF-8 Content-Length: …

Access tokens and refreshes

In most cases, the refresh token needs to be stored in a secure location as it may be needed later. Read more about requesting access tokens and refresh in the following guides:

When does an access token expire?

The access token has an expiration date, which depends on the value of expires_in . An expired access token can be refreshed with a refresh token, however our client libraries do this automatically.

Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 3.0 License , and code samples are licensed under the Apache 2.0 License . For details, see our . Java is a registered trademark of Oracle and/or its affiliates.

Updated September 24, 2018

Top Related Articles