OAuth: a description of the protocol in simple and understandable language. Application registration and settings
In 2010, work began on a completely new version OAuth 2.0 protocol, which will not be backward compatible with OAuth 1.0. In October 2012, the OAuth 2.0 framework was published in RFC 6749, and the use of the token bearer in RFC 6750, both standards tracking comment requests. Additional RFCs are still being developed.
There were several prerequisites for the creation of OAuth 2.0. First of all, OAuth is quite non-trivial to use on client side. One of the goals in developing the new OAuth is to simplify the development of client applications. Secondly, despite the implementation of three methods (called flows) stated in the standard for obtaining a token (unique identifier) for authorization: for web applications, desktop clients and mobile clients, in fact, all three methods are merged into one. And thirdly, the protocol turned out to be poorly scalable. It is planned to add:
- 6 new streams.
- Assertion Flow - The client submits an assertion, such as a SAML assertion, to the authorization server in exchange for a token.
- Simplified signature.
- Short-lived tokens with long-term authorization.
- Separation of roles.
It's worth noting that although the OAuth 2.0 standard has not yet been approved, it is already used by some services. For example, Graph API social network Facebook only supports OAuth 2.0.
Difference between OAuth and OpenID
There is a misconception that OAuth is an extension of the OpenID protocol. Actually this is not true. Although OpenID and OAuth have many similarities, the latter is a standalone protocol that is in no way related to OpenID.
Timestamp and Nonce
To prevent the threat of replay requests, OAuth uses a nonce and a timestamp. The term "nonce" means that, given time used once and is a unique random string of letters and numbers that is intended to uniquely identify each signed request. Having unique identificator For each request, the service provider will be able to prevent reuse requests. This means that the client generates a unique string for each request it sends to the server, and the server keeps track of all nonces used to prevent them from being used a second time.
Using nonces can be very expensive for the server, as they require permanent storage of all received nonces. To make implementation easier, OAuth adds a timestamp to each request, which allows the server to only store the nonce for a limited time. When a request arrives with a timestamp that is earlier than the stored time, it is rejected as the server no longer has a nonce from that time.
Credentials and Tokens
OAuth uses three types of authority: client credentials (consumer key and secret or client credentials), temporary credentials (request token and secret or temporary credentials) and tokens ( access token and secret or token credentials).
Client credentials are used to authenticate the client. This allows the server to collect information about clients. Using its services, the server offers some clients special processing such as throttling free access, or provide the resource owner with more detailed information about clients trying to access their protected resources. In some cases, client credentials may not be secure and may only be used for informational purposes, such as in desktop applications.
The token is used instead of the name and password of the resource owner. The resource owner does not share its credentials with the client, but rather authorizes the server to issue the client a token - a special class of credentials that represents grant access. The client uses the token to access the protected resource without knowing the resource owner's password.
A token consists of an identifier, usually (but not always) a random set of letters and numbers that is unique and difficult to guess, and a key to protect the token from being used unauthorized persons. The token is limited in scope and duration, and can be revoked at any time by the resource owner without affecting other tokens issued to other clients.
The OAuth authorization process also uses a set of temporary credentials that are used to determine the authorization request. To accommodate different types of clients (web, desktop, mobile, etc.), temporary credentials offer added flexibility and security.
How OAuth works
How the OAuth protocol works
Let us explain the operation of the OAuth protocol using an example. Let’s say that a user (resource owner) wants to print his photos (resources) uploaded to the site “photos.example.net” (server) using the printing service “printer.example.net” (client).
- The client, using the HTTPS protocol, sends a request to the server that contains the client identifier, a timestamp, a callback address to which the token should be returned, the type of digital signature used, and the signature itself.
- The server acknowledges the request and responds to the client with an Access Token and part of the shared secret.
- The client transfers the token to the resource owner (user) and redirects it to the server for authorization.
- The server, having received a token from the user, asks him for his login and password, and if authentication is successful, asks the user to confirm the client’s access to resources (authorization), after which the user is redirected by the server to the client.
- The client passes a token to the server via TLS and requests access to resources.
- The server acknowledges the request and responds to the client with a new access token.
- Using the new token, the client contacts the server for resources.
- The server acknowledges the request and provides resources.
This example describes a flow with an authorization code (Authorization Code Flow). In addition, the OAuth 2.0 standard describes the following flows:
- Implicit Grant Flow
- Refreshing an Expired Access Token Flow
- Resource Owner Password Credentials Flow
- Client Credentials Flow
OAuth supports two methods for authenticating messages from the client: HMAC -SHA1 and RSA -SHA1 . It is possible to send messages without a signature, then “plain text” is indicated in the signature type field. But in this case, according to the specification, the connection between the client and the server must be established via SSL or TLS.
Portals using OAuth
Discussion
In July 2012, Eran Hammer, the current editor of the OAuth 2.0 standard, announced his resignation after three years of work on the new standard, and asked that his name be removed from the specifications. He has spoken about his views on his website. He later gave a presentation. .
Notes
see also
Links
Wikimedia Foundation.
![](https://i1.wp.com/habrastorage.org/storage/129e7d71/b6d0ebb0/f8f37e20/5945f6c8.png)
- 2010.
- Opening the built-in browser with the login page
- The user is asked to confirm that rights have been granted. If the user agrees, the browser is redirected to a stub page in the fragment (after #) the URL of which is added
- access token If the user agrees, the browser is redirected to a stub page in the fragment (after #) the URL of which is added The application intercepts the redirect and receives
on
ExampleOpen the browser with the login page:
> GET /oauth/authorize?response_type=token&client_id=464119 HTTP/1.1 > Host: connect.mail.ru After the user grants permissions, a redirect occurs to a standard stub page, for Mail.Ru this is:
< 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
connect.mail.ru/oauth/success.html The application must intercept the last redirect and obtain from the address access_token
and use it to access protected resources.
Authorization by login and password If the user agrees, the browser is redirected to a stub page in the fragment (after #) the URL of which is added Authorization by login and password is a simple POST request, as a result of which it returnson
. This scheme is nothing new, but is included in the standard for generality and is recommended for use only when other authorization options are not available.< HTTP/1.1 200 OK < Content-Type: application/json < < { < "access_token":"SlAV32hkKG", < "token_type":"bearer", < "expires_in":86400, < "refresh_token":"8xLOxBtZp8", < }> POST /oauth/token HTTP/1.1 > Host: connect.mail.ru > Content-Type: application/x-www-form-urlencoded > > grant_type=password&client_id=31337&client_secret=deadbeef&username=api@corp.mail.ru& password= qwerty
Description in the specification
Restoring previous authorization If the user agrees, the browser is redirected to a stub page in the fragment (after #) the URL of which is added Usually, It has limited period suitability. This can be useful, for example, if it is transmitted over open channels If the user agrees, the browser is redirected to a stub page in the fragment (after #) the URL of which is added. To avoid forcing the user to login after expiration If the user agrees, the browser is redirected to a stub page in the fragment (after #) the URL of which is added"and, in all the above options, in addition to "maybe come back again refresh token If the user agrees, the browser is redirected to a stub page in the fragment (after #) the URL of which is added. You can use it to geton
using an HTTP request, similar to authorization using a login and password.< HTTP/1.1 200 OK < Content-Type: application/json < < { < "access_token":"Uu8oor1i", < "token_type":"bearer", < "expires_in":86400, < "refresh_token":"ohWo1ohr", < }There are many ways to distribute malicious spam on VKontakte. But the pests do not sleep, more and more come into their heads interesting ideas. And it turned out to be very useful. Fraudsters have learned to use it to bypass the warning page about malicious sites.
And it all started when one day the following message appeared on my wall:
Out of curiosity, I followed the link and ended up on another phishing site. But the link itself seemed strange to me, it looked like (half the characters in ASCII):
vkontakte.ru/away.php ? to=http%3A%2F%2FApi.vKontakte.Ru%2F%2Fo%2561u%2574%…
This is where the fun begins...
Let's look at the second link in parts:What does each parameter mean:
- client_id - ID of the application that requires authorization;
- redirect_uri - the address to which the access_token will be sent (via a redirect);
- display - type of authorization window (page, popup, touch and wap).
This is the whole point of bypassing the blacklist of malicious VKontakte sites. Only an alert about the transition to api.vk.com appears. And as a result of the transition, we go straight to a phishing site that is on the black list. When you follow the link vkontakte.ru/away.php?to=vgostivk.dyndns**:
As it turned out, the application supposedly requiring authorization was hanging on the hacked user:
And the phishing site itself was designed quite interestingly. The design, as usual, was contact-style and asked to log in. I logged in using a random email and password, and I swallowed the fake just fine. What happened next was even more interesting; news from “Pavel Durov” appeared on the main page:
After clicking on the “Create personal counter” button, a wonderful progress bar followed. Then you were asked to indicate your number and send an SMS:
In theory, after successful “activation” it should have redirected to the activ.php page, but I couldn’t get there. Excerpts from JS scripts of a phishing site:
...
if (req.status == 200) (
// if the status is 200 (OK) - give a response to the user
if (req.responseText == "ok" ) (
//statusElem.innerHTML = "Everything is buzzing!";
get_activation();
}
if (req.responseText == "not" ) (statusElem.innerHTML = "Invalid activation code";}
//statusElem.innerHTML = "Server response: "+req.responseText;
...
function get_activation() (
document .location="activ.php" ;
}* This source code was highlighted with Source Code Highlighter.
Bottom line: Fraudsters use OAuth 2.0 to bypass warnings, obtain the user’s password and email, and even try to defraud sending sms(most likely using a subscription system).
As a result client application using the AdWords API can access your AdWords account without an address Email and user password.
Creating OAuth2 Credentials
To create OAuth2 credentials, follow the steps below.
Defining the Application Type
First, you need to determine application type, which you want to create. There are two types of applications in the AdWords API:
- installable application(recommended);
- web application.
Using the table below, determine desired type applications.
What to choose | Situation |
---|---|
Installable application(recommended) |
|
Web application |
|
Creating a client ID and secret code
Once you have determined your application type, click on the appropriate tab below and follow the instructions to create an ID and secret code client.
Installable application
- Open
- Create a project Create.
- Create Credentials, and then - OAuth Client ID.
- Save
- In chapter Application type select Other types and provide the required information.
- Click Create.
- identifier And The secret key
- Open
- From the projects drop-down menu, select Create a project, then specify the project name and change its ID if necessary, then click the button Create.
- On the Credentials page, select Create Credentials, and then - OAuth Client ID.
- You may be asked to provide the product name. In this case, click Customize the access request window, enter the requested information and click Save to return to the Credentials screen.
- In chapter Application type select Web application. Follow the instructions to specify JavaScript sources and/or redirect URIs.
- Click Create.
- 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 option for creating 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 designed 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 is better to use client libraries as described above.
Settings
Warning.To use OAuth2 Playground, you need to create client id For . This the only one a type of application that works with OAuth2 Playground. Read more in the section above.How to get client ID and secret key
- Open
- Select an existing project from the drop-down menu or create a new one.
- On the Credentials page, select Create Credentials, and then - OAuth Client ID.
- In chapter Application type select Web application.
- In the section add next line: https://site/oauthplayground
- Click Create.
- Write it down identifier And The secret key clients indicated on the page that appears.
You will need them in the next step.
Warning.How to create tokens From what Google accountYou're signed in to your browser, it depends on which AdWords accounts you can access using the OAuth2 credentials you create. It may be better 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 different from the account you were in when you received the Client ID and Secret Key.
How to remove OAuth2 Playground from Client ID Since you already have, you no longer need to use OAuth2 Playground as your resolved redirect URI. To remove this system from the list, follow these steps:
- Go to .
- Select your project from the drop-down menu.
- On the Credentials page, select the name of the client ID.
- Remove https://site/oauthplayground from the field Allowed redirect URIs. Please note that you must leave at least one Redirect URI.
- Click Save.
So you have your OAuth credentials. Now you can carry out AdWords requests API and use 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, not a separate one. end user. Service accounts provide interaction between a web application and a Google service. Your application calls the API on behalf of the service account without directly involving users.
The AdWords API allows service account access across G Suite domains.
The service account implements an OAuth2 process, which instead of authorizing the user uses a key file that is only accessible to your application.
Using service accounts provides two significant advantages:
- Authorizing application access to Google API carried out at the setup stage. This avoids the hassle of requiring user intervention or caching tokens in other OAuth2 flows.
- Impersonation of other users in the application, if necessary, is done as part of the OAuth2 approval process.
Alternative to service accounts
Service accounts are widely used to provide software access to the API via the OAuth2 protocol without user intervention.
However, setting up such accounts to work with the AdWords API is not easy. A simpler alternative is with a persisted refresh token. This approach allows the application to request new access tokens at any time.
As part of this process, you need to configure application authorization through the client library as described above. This only needs to be done once, since tokens expire Google updates OAuth2 is unlimited.
Requirements
- A G Suite domain you own, such as mydomain.com or mybusiness.com.
- AdWords API developer token and preferably a test account.
- for the language being used.
Setting up access for a client account
First, you need to create a service account key in the Google API Console.
- Sign in to your G Suite account, open .
- From the projects drop-down menu, select Create a project, then provide the required information and click the button Create. New project will appear in the active list.
- In the menu on the left top corner select IAM and administration, and then - Service accounts in the menu on the left.
- Click Create a service account at the top of the page.
- Enter the name of the service account.
- Check the box Create new private key and select the JSON key type.
- Check the box Enable data access delegation in your G Suite domain and provide the product name for the access request window.
- Click Create. The JSON key file will start downloading. Save the file in a safe place where only you have access.
- On the page Service accounts a new service account will appear.
Security issues
Because G Suite is managed at the domain level, you must securely protect the key file that allows authorized accounts to access Google services. This is especially important due to the fact that we provide the service account with the ability to impersonate any domain user.
In addition, it is recommended that each service account have access to only one Google API. The field is used for this scope, which is described in the next section. This preventative measure allows you to limit the amount of data open to unauthorized access in the event of a key file being compromised.
How to provide impersonation capabilities
To grant impersonation capabilities to a service account, 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 to view instructions for 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 app doesn't use credential sharing, it can significantly increase the number of requests sent to Google. As a result, our servers may impose restrictions on such an application, which will reduce the speed of its operation.
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 OAuth2 credential attributes, including the access token and its expiration date.Credential distribution strategies
Distributing credentials across API requests improves performance and also avoids overhead and errors due to constraint violations.
The credential distribution strategy depends on the application design.
IN multi-threaded applications You must use the same credentials for each thread's session.
In multi-process and distributed applications, it is necessary to implement some infrastructure for passing credentials between processes. In addition, you must ensure that threads do not block and race conditions occur.
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-level 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 must be done synchronously to avoid race conditions.
This diagram shows the threads that pass requests to the AdWords API at runtime. A shared pool of sessions (users) is used. Note that each session must use the same credentials object. In response to each API request, the thread receives the corresponding session (user). If the access token needs to be refreshed, it must be done synchronously to avoid a race condition. In other words, the credentials 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 life cycle. To use credentials across sessions, you must apply them when creating each session. In all client libraries, the credential is a thread-safe object that is synchronously updated when the access token expires.
For example, in the Java client library you would create a singleton Credential class and use it for all sessions.
Multiprocess and distributed applications
In multi-process and distributed applications, credential distribution must be ongoing. To avoid a race situation where multiple servers try to update credentials at the same time (resulting in excessive update requests), it is recommended to force the update and provide the updated credentials to all processes and servers.
For example, a single task or service might periodically update credentials and push them to a data store where they will be used by different servers.
The diagram shows the periodic updating of credentials and recording their properties in the data store. All servers then receive credentials before making a request to the API.
Update task
The update task periodically updates 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 be down for some time due to a lack of valid credentials.
The best alternative is periodic forced update, in which the credentials in the data store are replaced with new ones each time. The update task should be performed well before the current credentials expire so that there is sufficient time in the event of an issue. temporary error. You can start by performing an update every 15 minutes.
Note.If the credential's access token expires while an API request is being processed, the request will still be executed. For example, if you create a long-running query and have less than a minute left to access, results will still be returned.Data store
The data store is used to provide credentials different processes and servers.
To do this, you can use an existing data warehouse or create a specialized one through which servers will receive credentials. As possible solutions you can use caching servers (for example, Memcached or Infinispan) and NoSQL data stores (for example, MongoDB).
The main purpose of the data warehouse is to provide a reliable interface to all servers accessing the API. Its operation needs to be optimized for quick reading data: servers and processes will read credentials more often than they are updated.
Remember to keep your credentials secure.
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 date) is calculated using the following formula: access_token update request time + expires_in time (token expiration date).
Server pool
Each server in the pool obtains the latest credentials from the data store before sending the request. As long as the update task runs successfully, the credentials will be valid. However, if the update task or data store fails, there must be a fallback mechanism.
If the server or process is unable to obtain credentials from the data store, or if the credentials have expired, the server must update its credentials to allow the application to continue working with the API until the problem is resolved.
IN multithreaded processes the same strategy for distributing credentials between threads must be used.
Multiple Account Authentication
The credentials you create for your AdWords manager account can be used to access all child accounts. Users with one manager account typically only need to create credentials for the top-level manager account to authorize the application for all subordinate AdWords accounts.
In other cases, the application needs access to AdWords accounts that are not related to each other in the manager account hierarchy. In this situation, you need to create and maintain multiple credentials for different accounts, for example, for each AdWords client account to which you have access, or for each top-level manager account in independent hierarchies.
You can follow these strategies for both applications with minimal changes. Using shared storage The credentials must be indexed by the account ID customerId to ensure that the credentials are associated with the required account. In addition, the update task must update them on time. After connecting a new account, you may need to launch it.
Finally, in multi-threaded applications, you need to distribute the credentials object only among the threads running in the account to which it is associated.
How OAuth2 works
Note. AdWords API is not yet supported simultaneous entry using a data access request ( hybrid scheme) or delegation of authority at the domain level (2LO).Scope
An access token can provide varying degrees of access to data. The variable 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 is the current and legacy scope for the AdWords API.
Offline access
A client application that uses the AdWords API typically requests offline access. This can happen if your application needs to run batch jobs while the user is browsing your site without an Internet connection.
Installed apps use offline access by default.
HTTP request header
The HTTP header in every 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 and refresh tokens
In most cases, the refresh token needs to be stored in a safe place because it may be needed later. For more information about requesting access and refresh tokens, see the following guides:
When an access token expires
The access token has an expiration date that depends on the value of expires_in . An expired access token can be refreshed using a refresh token, but 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 ours. Java is a registered trademark of Oracle and/or its affiliates.
Updated September 24, 2018
If you use Mail.Ru Mail, you don’t have to worry about the security of your data. Thanks to OAuth — authorization.
In this article we want to tell the whole truth about this technology. about that, Why is it important.
What is a protocolOAuth?
According to statistics, each user has on average three mailboxes. Checking them all, especially if they are on different sites, is not very convenient.
In Mail.Ru Mail you can configure the collection of letters from mailboxes on other domains ().Why use the mail collector in MailMail.Ru
safely? Typically, when setting up the collector, you need to enter a name, mailbox address and password. To ensure secure transmission of your data, Mail.Ru Mail has long used encryption of this data by using protocols SSL OAuth. And to eliminate the need to transfer passwords, we implemented the collection of letters using . This protocol allows the program.
do not request or store logins and passwords
How it works? Let's say you decide to set up a collector of letters from Yandex mail in your mailbox OAuth Mail.Ru. Thanks to the protocol Mail.Ru mail will not request your login and password from Yandex mail, but will request.
only right of access
Just click “Add Mailbox” and Mail will have access until it is revoked by you.
But we won't know about your password.
Helpful advice! And finally, if you decide to set up a mail collector from your Mail.Ru mailbox on a third-party postal service OAuth. – make sure it uses a protocol
If not, we do not recommend that you risk the security of your data.