google ads api —— OAuth

参考:

Using OAuth 2.0 to Access Google APIs          

 

Obtaining OAuth 2.0 access tokens

The following steps show how your application interacts with Google‘s OAuth 2.0 server to obtain a user‘s consent to perform an API request on the user‘s behalf. Your application must have that consent before it can execute a Google API request that requires user authorization.

The list below quickly summarizes these steps:

  1. Your application identifies the permissions it needs.
  2. Your application redirects the user to Google along with the list of requested permissions.
  3. The user decides whether to grant the permissions to your application.
  4. Your application finds out what the user decided.
  5. If the user granted the requested permissions, your application retrieves tokens needed to make API requests on the user‘s behalf.

 

Step 1: Set authorization parameters

Your first step is to create the authorization request. That request sets parameters that identify your application and define the permissions that the user will be asked to grant to your application.

  • If you use a Google client library for OAuth 2.0 authentication and authorization, you create and configure an object that defines these parameters.
  • If you call the Google OAuth 2.0 endpoint directly, you‘ll generate a URL and set the parameters on that URL.

The tabs below define the supported authorization parameters for web server applications. The language-specific examples also show how to use a client library or authorization library to configure an object that sets those parameters.

 

Google‘s OAuth 2.0 endpoint is at https://accounts.google.com/o/oauth2/v2/auth. This endpoint is accessible only over HTTPS. Plain HTTP connections are refused.

The Google authorization server supports the following query string parameters for web server applications:

Parameters
client_id Required

The client ID for your application. You can find this value in the API Console Credentials page.

redirect_uri Required

Determines where the API server redirects the user after the user completes the authorization flow. The value must exactly match one of the authorized redirect URIs for the OAuth 2.0 client, which you configured in your client‘s API Console Credentials page. If this value doesn‘t match an authorized redirect URI for the provided client_id you will get a redirect_uri_mismatch error.

Note that the http or https scheme, case, and trailing slash (‘/‘) must all match.

response_type Required

Determines whether the Google OAuth 2.0 endpoint returns an authorization code.

Set the parameter value to code for web server applications.

scope Required

A space-delimited list of scopes that identify the resources that your application could access on the user‘s behalf. These values inform the consent screen that Google displays to the user.

Scopes enable your application to only request access to the resources that it needs while also enabling users to control the amount of access that they grant to your application. Thus, there is an inverse relationship between the number of scopes requested and the likelihood of obtaining user consent.

We recommend that your application request access to authorization scopes in context whenever possible. By requesting access to user data in context, via incremental authorization, you help users to more easily understand why your application needs the access it is requesting.

access_type Recommended

Indicates whether your application can refresh access tokens when the user is not present at the browser. Valid parameter values are online, which is the default value, and offline.

Set the value to offline if your application needs to refresh access tokens when the user is not present at the browser. This is the method of refreshing access tokens described later in this document. This value instructs the Google authorization server to return a refresh token and an access token the first time that your application exchanges an authorization code for tokens.

state Recommended

Specifies any string value that your application uses to maintain state between your authorization request and the authorization server‘s response. The server returns the exact value that you send as a name=value pair in the URL query component (?) of the redirect_uri after the user consents to or denies your application‘s access request.

You can use this parameter for several purposes, such as directing the user to the correct resource in your application, sending nonces, and mitigating cross-site request forgery. Since your redirect_uri can be guessed, using a state value can increase your assurance that an incoming connection is the result of an authentication request. If you generate a random string or encode the hash of a cookie or another value that captures the client‘s state, you can validate the response to additionally ensure that the request and response originated in the same browser, providing protection against attacks such as cross-site request forgery. See the OpenID Connect documentation for an example of how to create and confirm a state token.

include_granted_scopes Optional

Enables applications to use incremental authorization to request access to additional scopes in context. If you set this parameter‘s value to true and the authorization request is granted, then the new access token will also cover any scopes to which the user previously granted the application access. See the incremental authorization section for examples.

login_hint Optional

If your application knows which user is trying to authenticate, it can use this parameter to provide a hint to the Google Authentication Server. The server uses the hint to simplify the login flow either by prefilling the email field in the sign-in form or by selecting the appropriate multi-login session.

Set the parameter value to an email address or sub identifier, which is equivalent to the user‘s Google ID.

prompt Optional

A space-delimited, case-sensitive list of prompts to present the user. If you don‘t specify this parameter, the user will be prompted only the first time your project requests access. See Prompting re-consent for more information.

Possible values are:

none Do not display any authentication or consent screens. Must not be specified with other values.
consent Prompt the user for consent.
select_account Prompt the user to select an account.

 

Step 2: Redirect to Google‘s OAuth 2.0 server

Redirect the user to Google‘s OAuth 2.0 server to initiate the authentication and authorization process. Typically, this occurs when your application first needs to access the user‘s data. In the case of incremental authorization, this step also occurs when your application first needs to access additional resources that it does not yet have permission to access.

 

Sample redirect to Google‘s authorization server

An example URL is shown below, with line breaks and spaces for readability.

https://accounts.google.com/o/oauth2/v2/auth?
 scope=https%3A//www.googleapis.com/auth/drive.metadata.readonly&
 access_type=offline&
 include_granted_scopes=true&
 response_type=code&
 state=state_parameter_passthrough_value&
 redirect_uri=https%3A//oauth2.example.com/code&
 client_id=client_id

After you create the request URL, redirect the user to it.

Google‘s OAuth 2.0 server authenticates the user and obtains consent from the user for your application to access the requested scopes. The response is sent back to your application using the redirect URL you specified.

 

Step 3: Google prompts user for consent

In this step, the user decides whether to grant your application the requested access. At this stage, Google displays a consent window that shows the name of your application and the Google API services that it is requesting permission to access with the user‘s authorization credentials and a summary of the scopes of access to be granted. The user can then consent to grant access to one or more scopes requested by your application or refuse the request.

Your application doesn‘t need to do anything at this stage as it waits for the response from Google‘s OAuth 2.0 server indicating whether any access was granted. That response is explained in the following step.

Errors

Requests to Google‘s OAuth 2.0 authorization endpoint may display user-facing error messages instead of the expected authentication and authorization flows. Common error codes and suggested resolutions are listed below.

admin_policy_enforced

The Google Account is unable to authorize one or more scopes requested due to the policies of their Google Workspace administrator. See the Google Workspace Admin help article Control which third-party & internal apps access Google Workspace data for more information about how an administrator may restrict access to all scopes or sensitive and restricted scopes until access is explicitly granted to your OAuth client ID.

disallowed_useragent

The authorization endpoint is displayed inside an embedded user-agent disallowed by Google‘s OAuth 2.0 Policies.

org_internal

The OAuth client ID in the request is part of a project limiting access to Google Accounts in a specific Google Cloud Organization. For more information about this configuration option see the User type section in the Setting up your OAuth consent screen help article.

redirect_uri_mismatch

The redirect_uri passed in the authorization request does not match an authorized redirect URI for the OAuth client ID. Review authorized redirect URIs in the Google API Console Credentials page.

 

Step 4: Handle the OAuth 2.0 server response

The OAuth 2.0 server responds to your application‘s access request by using the URL specified in the request.

If the user approves the access request, then the response contains an authorization code. If the user does not approve the request, the response contains an error message. The authorization code or error message that is returned to the web server appears on the query string, as shown below:

An error response:

 
 
https://oauth2.example.com/auth?error=access_denied

An authorization code response:

 
 
https://oauth2.example.com/auth?code=4/P7q7W91a-oMsCeLvIaQm6bTrgtp7

Important: If your response endpoint renders an HTML page, any resources on that page will be able to see the authorization code in the URL. Scripts can read the URL directly, and the URL in the Referer HTTP header may be sent to any or all resources on the page.

Carefully consider whether you want to send authorization credentials to all resources on that page (especially third-party scripts such as social plugins and analytics). To avoid this issue, we recommend that the server first handle the request, then redirect to another URL that doesn‘t include the response parameters.

Sample OAuth 2.0 server response

You can test this flow by clicking on the following sample URL, which requests read-only access to view metadata for files in your Google Drive:

 
 
https://accounts.google.com/o/oauth2/v2/auth?
 scope=https%3A//www.googleapis.com/auth/drive.metadata.readonly&
 access_type=offline&
 include_granted_scopes=true&
 response_type=code&
 state=state_parameter_passthrough_value&
 redirect_uri=https%3A//oauth2.example.com/code&
 client_id=client_id

After completing the OAuth 2.0 flow, you should be redirected to http://localhost/oauth2callback, which will likely yield a 404 NOT FOUND error unless your local machine serves a file at that address. The next step provides more detail about the information returned in the URI when the user is redirected back to your application.

 

Step 5: Exchange authorization code for refresh and access tokens

After the web server receives the authorization code, it can exchange the authorization code for an access token.

To exchange an authorization code for an access token, call the https://oauth2.googleapis.com/token endpoint and set the following parameters:

Fields
client_id The client ID obtained from the API Console Credentials page.
client_secret The client secret obtained from the API Console Credentials page.
code The authorization code returned from the initial request.
grant_type As defined in the OAuth 2.0 specification, this field‘s value must be set to authorization_code.
redirect_uri One of the redirect URIs listed for your project in the API Console Credentials page for the given client_id.

The following snippet shows a sample request:

 
 
POST /token HTTP/1.1
Host: oauth2.googleapis.com
Content-Type: application/x-www-form-urlencoded

code=4/P7q7W91a-oMsCeLvIaQm6bTrgtp7&
client_id=your_client_id&
client_secret=your_client_secret&
redirect_uri=https%3A//oauth2.example.com/code&
grant_type=authorization_code

Google responds to this request by returning a JSON object that contains a short-lived access token and a refresh token. Note that the refresh token is only returned if your application set the access_type parameter to offline in the initial request to Google‘s authorization server.

The response contains the following fields:

Fields
access_token The token that your application sends to authorize a Google API request.
expires_in The remaining lifetime of the access token in seconds.
refresh_token A token that you can use to obtain a new access token. Refresh tokens are valid until the user revokes access. Again, this field is only present in this response if you set the access_type parameter to offline in the initial request to Google‘s authorization server.
scope The scopes of access granted by the access_token expressed as a list of space-delimited, case-sensitive strings.
token_type The type of token returned. At this time, this field‘s value is always set to Bearer.

Important: Your application should store both tokens in a secure, long-lived location that is accessible between different invocations of your application. The refresh token enables your application to obtain a new access token if the one that you have expires. As such, if your application loses the refresh token, the user will need to repeat the OAuth 2.0 consent flow so that your application can obtain a new refresh token.

The following snippet shows a sample response:

 
{
  "access_token": "1/fFAGRNJru1FTz70BzhT3Zg",
  "expires_in": 3920,
  "token_type": "Bearer",
  "scope": "https://www.googleapis.com/auth/drive.metadata.readonly",
  "refresh_token": "1//xEoDL4iW3cxlI7yDbSRFYNG01kVKM2C-259HOF2aQbI"
}

Note: Your application should ignore any unrecognized fields included in the response.

 

 

Calling Google APIs

After your application obtains an access token, you can use the token to make calls to a Google API on behalf of a given user account if the scope(s) of access required by the API have been granted. To do this, include the access token in a request to the API by including either an access_token query parameter or an Authorization HTTP header Bearer value. When possible, the HTTP header is preferable, because query strings tend to be visible in server logs. In most cases you can use a client library to set up your calls to Google APIs (for example, when calling the Drive Files API).

You can try out all the Google APIs and view their scopes at the OAuth 2.0 Playground.

HTTP GET examples

A call to the drive.files endpoint (the Drive Files API) using the Authorization: Bearer HTTP header might look like the following. Note that you need to specify your own access token:

 

 
 
GET /drive/v2/files HTTP/1.1
Host: www.googleapis.com
Authorization: Bearer access_token

Here is a call to the same API for the authenticated user using the access_token query string parameter:

 
 
GET https://www.googleapis.com/drive/v2/files?access_token=access_token

curl examples

You can test these commands with the curl command-line application. Here‘s an example that uses the HTTP header option (preferred):

 
curl -H "Authorization: Bearer access_token" https://www.googleapis.com/drive/v2/files

Or, alternatively, the query string parameter option:

 
curl https://www.googleapis.com/drive/v2/files?access_token=access_token

 

Complete example

The following example prints a JSON-formatted list of files in a user‘s Google Drive after the user authenticates and gives consent for the application to access the user‘s Drive metadata.

This Python example uses the Flask framework and the Requests library to demonstrate the OAuth 2.0 web flow. We recommend using the Google API Client Library for Python for this flow. (The example in the Python tab does use the client library.)

 

 

import json

import flask
import requests


app
= flask.Flask(__name__)

CLIENT_ID
=‘123456789.apps.googleusercontent.com‘
CLIENT_SECRET
=‘abc123‘  # Read from a file or environmental variable in a real app
SCOPE
=‘https://www.googleapis.com/auth/drive.metadata.readonly‘
REDIRECT_URI
=‘http://example.com/oauth2callback‘


@app.route(‘/‘)
def index():
 
if‘credentials‘notin flask.session:
   
return flask.redirect(flask.url_for(‘oauth2callback‘))
  credentials
= json.loads(flask.session[‘credentials‘])
 
if credentials[‘expires_in‘]<=0:
   
return flask.redirect(flask.url_for(‘oauth2callback‘))
 
else:
    headers
={‘Authorization‘:‘Bearer {}‘.format(credentials[‘access_token‘])}
    req_uri
=‘https://www.googleapis.com/drive/v2/files‘
    r
= requests.get(req_uri, headers=headers)
   
return r.text


@app.route(‘/oauth2callback‘)
def oauth2callback():
 
if‘code‘notin flask.request.args:
    auth_uri
=(‘https://accounts.google.com/o/oauth2/v2/auth?response_type=code‘
               
‘&client_id={}&redirect_uri={}&scope={}‘).format(CLIENT_ID, REDIRECT_URI, SCOPE)
   
return flask.redirect(auth_uri)
 
else:
    auth_code
= flask.request.args.get(‘code‘)
    data
={‘code‘: auth_code,
           
‘client_id‘: CLIENT_ID,
           
‘client_secret‘: CLIENT_SECRET,
           
‘redirect_uri‘: REDIRECT_URI,
           
‘grant_type‘:‘authorization_code‘}
    r
= requests.post(‘https://oauth2.googleapis.com/token‘, data=data)
    flask
.session[‘credentials‘]= r.text
   
return flask.redirect(flask.url_for(‘index‘))


if __name__ ==‘__main__‘:
 
import uuid
  app
.secret_key = str(uuid.uuid4())
  app
.debug =False
  app
.run()

Redirect URI validation rules

Google applies the following validation rules to redirect URIs in order to help developers keep their applications secure. Your redirect URIs must adhere to these rules. See RFC 3986 section 3 for the definition of domain, host, path, query, scheme and userinfo, mentioned below.

 

Validation rules
Scheme

URIs must use the HTTPS scheme, not plain HTTP.

Host

Hosts cannot be raw IP addresses. Localhost IP addresses are exempted from this rule.

Domain
  • Host TLDs (Top Level Domains) must belong to the public suffix list.
  • Host domains cannot be “googleusercontent.com”.
  • URIs cannot contain URL shortener domains (e.g. goo.gl) unless the app owns the domain. Furthermore, if an app that owns a shortener domain chooses to redirect to that domain, that redirect URI must either contain “/google-callback/” in its path or end with “/google-callback”.
Userinfo

Redirect URIs cannot contain the userinfo subcomponent.

Path

Redirect URIs cannot contain a path traversal (also called directory backtracking), which is represented by an “/..” or “\..” or their URL encoding.

Query

Redirect URIs cannot contain open redirects.

Characters URIs cannot contain certain characters including:
  • Wildcard characters (‘*‘)
  • Non-printable ASCII characters
  • Invalid percent encodings (any percent encoding that does not follow URL-encoding form of a percent sign followed by two hexadecimal digits)
  • Null characters (an encoded NULL character, e.g., %00, %C0%80)

 

Incremental authorization

In the OAuth 2.0 protocol, your app requests authorization to access resources, which are identified by scopes. It is considered a best user-experience practice to request authorization for resources at the time you need them. To enable that practice, Google‘s authorization server supports incremental authorization. This feature lets you request scopes as they are needed and, if the user grants permission for the new scope, returns an authorization code that may be exchanged for a token containing all scopes the user has granted the project.

For example, an app that lets people sample music tracks and create mixes might need very few resources at sign-in time, perhaps nothing more than the name of the person signing in. However, saving a completed mix would require access to their Google Drive. Most people would find it natural if they only were asked for access to their Google Drive at the time the app actually needed it.

In this case, at sign-in time the app might request the openid and profile scopes to perform basic sign-in, and then later request the https://www.googleapis.com/auth/drive.file scope at the time of the first request to save a mix.

To implement incremental authorization, you complete the normal flow for requesting an access token but make sure that the authorization request includes previously granted scopes. This approach allows your app to avoid having to manage multiple access tokens.

The following rules apply to an access token obtained from an incremental authorization:

  • The token can be used to access resources corresponding to any of the scopes rolled into the new, combined authorization.
  • When you use the refresh token for the combined authorization to obtain an access token, the access token represents the combined authorization and can be used for any of the scope values included in the response.
  • The combined authorization includes all scopes that the user granted to the API project even if the grants were requested from different clients. For example, if a user granted access to one scope using an application‘s desktop client and then granted another scope to the same application via a mobile client, the combined authorization would include both scopes.
  • If you revoke a token that represents a combined authorization, access to all of that authorization‘s scopes on behalf of the associated user are revoked simultaneously.

Caution: choosing to include granted scopes will automatically add scopes previously granted by the user to your authorization request. A warning or error page may be displayed if your app is not currently approved to request all scopes that may be returned in the response. See Unverified apps for more information.

 

The language-specific code samples in Step 1: Set authorization parameters and the sample HTTP/REST redirect URL in Step 2: Redirect to Google‘s OAuth 2.0 server all use incremental authorization. The code samples below also show the code that you need to add to use incremental authorization.

GET https://accounts.google.com/o/oauth2/v2/auth?
  client_id=your_client_id&
  response_type=code&
  state=state_parameter_passthrough_value&
  scope=https%3A//www.googleapis.com/auth/drive.file&
  redirect_uri=https%3A//oauth2.example.com/code&
  prompt=consent&
  include_granted_scopes=true

Refreshing an access token (offline access)

Access tokens periodically expire and become invalid credentials for a related API request. You can refresh an access token without prompting the user for permission (including when the user is not present) if you requested offline access to the scopes associated with the token.

  • If you use a Google API Client Library, the client object refreshes the access token as needed as long as you configure that object for offline access.
  • If you are not using a client library, you need to set the access_type HTTP query parameter to offline when redirecting the user to Google‘s OAuth 2.0 server. In that case, Google‘s authorization server returns a refresh token when you exchange an authorization code for an access token. Then, if the access token expires (or at any other time), you can use a refresh token to obtain a new access token.

Requesting offline access is a requirement for any application that needs to access a Google API when the user is not present. For example, an app that performs backup services or executes actions at predetermined times needs to be able to refresh its access token when the user is not present. The default style of access is called online.

 

Server-side web applications, installed applications, and devices all obtain refresh tokens during the authorization process. Refresh tokens are not typically used in client-side (JavaScript) web applications.

To refresh an access token, your application sends an HTTPS POST request to Google‘s authorization server (https://oauth2.googleapis.com/token) that includes the following parameters:

Fields
client_id The client ID obtained from the API Console.
client_secret The client secret obtained from the API Console.
grant_type As defined in the OAuth 2.0 specification, this field‘s value must be set to refresh_token.
refresh_token The refresh token returned from the authorization code exchange.

The following snippet shows a sample request:

 
 
POST /token HTTP/1.1
Host: oauth2.googleapis.com
Content-Type: application/x-www-form-urlencoded

client_id=your_client_id&
client_secret=your_client_secret&
refresh_token=refresh_token&
grant_type=refresh_token

As long as the user has not revoked the access granted to the application, the token server returns a JSON object that contains a new access token. The following snippet shows a sample response:

 
{
 
"access_token":"1/fFAGRNJru1FTz70BzhT3Zg",
 
"expires_in":3920,
 
"scope":"https://www.googleapis.com/auth/drive.metadata.readonly",
 
"token_type":"Bearer"
}

 

Note that there are limits on the number of refresh tokens that will be issued; one limit per client/user combination, and another per user across all clients. You should save refresh tokens in long-term storage and continue to use them as long as they remain valid. If your application requests too many refresh tokens, it may run into these limits, in which case older refresh tokens will stop working.

 

Revoking a token

In some cases a user may wish to revoke access given to an application. A user can revoke access by visiting Account Settings. See the Remove site or app access section of the Third-party sites & apps with access to your account support document for more information.

It is also possible for an application to programmatically revoke the access given to it. Programmatic revocation is important in instances where a user unsubscribes, removes an application, or the API resources required by an app have significantly changed. In other words, part of the removal process can include an API request to ensure the permissions previously granted to the application are removed.

To programmatically revoke a token, your application makes a request to https://oauth2.googleapis.com/revoke and includes the token as a parameter:

 
curl -d -X -POST --header "Content-type:application/x-www-form-urlencoded"         https://oauth2.googleapis.com/revoke?token={token}

The token can be an access token or a refresh token. If the token is an access token and it has a corresponding refresh token, the refresh token will also be revoked.

If the revocation is successfully processed, then the HTTP status code of the response is 200. For error conditions, an HTTP status code 400 is returned along with an error code.

 

Note: Following a successful revocation response, it might take some time before the revocation has full effect.

 

 

 

After your application obtains an access token, you can use the token to make calls to a Google API on behalf of a given user account if the scope(s) of access required by the API have been granted. To do this, include the access token in a request to the API by including either an access_token query parameter or an Authorization HTTP header Bearer value. When possible, the HTTP header is preferable, because query strings tend to be visible in server logs. In most cases you can use a client library to set up your calls to Google APIs (for example, when calling the Drive Files API).

You can try out all the Google APIs and view their scopes at the OAuth 2.0 Playground.

HTTP GET examples

A call to the drive.files endpoint (the Drive Files API) using the Authorization: Bearer HTTP header might look like the following. Note that you need to specify your own access token:

 

 
 
GET /drive/v2/files HTTP/1.1
Host: www.googleapis.com
Authorization: Bearer access_token

Here is a call to the same API for the authenticated user using the access_token query string parameter:

 
 
GET https://www.googleapis.com/drive/v2/files?access_token=access_token

curl examples

You can test these commands with the curl command-line application. Here‘s an example that uses the HTTP header option (preferred):

 
curl -H "Authorization: Bearer access_token" https://www.googleapis.com/drive/v2/files

Or, alternatively, the query string parameter option:

 
curl https://www.googleapis.com/drive/v2/files?access_token=access_token

Complete example

google ads api —— OAuth

上一篇:.NET Core WebAPI post参数传递时后端的接收方式


下一篇:PHPCMS v9 超级安全防范教程!