# OAuth for Data Plan Agent API

## Related Documents

OAuth 2.0 is standardized as [RFC 6749](https://tools.ietf.org/html/rfc6749). A
detailed document is available at https://oauth.net/2. HTTP Basic Authentication
is defined in
[section 2 of RFC 2617](https://tools.ietf.org/html/rfc2617#section-2).

## Overview

Usually, in order to provide third-party applications access to restricted
resources such as data plan and wallet details, the end user (resource owner)
needs to share its credentials with the third party. This creates several
problems and limitations such as credential storage, password authentication,
broad access to the end user's resources, and password leak, etc. The OAuth2.0
addresses these issues by introducing an authorization layer and thereby
securing and limiting the access to the protected resources of the end user.

Instead of using the end user's credentials to access protected resources such
as data plan details, the GTAF obtains an access token. The access tokens are
issued to GTAF on behalf of GTAF's credentials. The GTAF then uses the access
token to access the data plan details hosted by the DPA.

The following figure provides high-level flow of information:

![](https://developers.google.com/static/mobile-data-plan/v6_1/images/abstract_oauth_flow.jpg)
**Figure 1. Abstract OAuth Flow.**

### Access Tokens

Access tokens are the credentials used by the GTAF to access data plan details
from the carrier's DPA. An access token is a string representing an
authorization issued to the GTAF. The string is usually opaque to the GTAF.
Tokens represent specific scopes and durations of access, granted by the end
user to the carrier, and enforced by the DPA and carrier's OAuth server.

The access token provides an abstraction layer, replacing different
authorization constructs (e.g., username and password) with a single token
understood by the DPA. This abstraction enables issuing access tokens more
restrictive than the authorization grant used to obtain them, as well as
removing the DPA's need to understand a wide range of authentication methods.

Access tokens can have different formats, structures, and methods of utilization
(e.g., cryptographic properties) based on the carrier's security requirements.
GTAF only supports bearer type access tokens defined in
\[[RFC6750](https://tools.ietf.org/html/rfc6750)\].

### Client Authentication

The GTAF works as a "confidential client" and is capable of keeping passwords
safe. The GTAF currently supports only HTTP Basic authentication to authenticate
with the DPA. The client identifier is encoded using the
"application/x-www-form-urlencoded" encoding algorithm, and the encoded value is
used as the username; the password is encoded using the same algorithm and used
as the password.

Confidential clients such as GTAF, which are issued client credentials,
authenticates with the carrier's OAuth server while making requests to the token
endpoint. The client authentication is used for: \\

- Recovering from a compromised client by disabling the client or changing its credentials, thus preventing an attacker from abusing stolen refresh tokens. Changing a single set of client credentials is significantly faster than revoking an entire set of refresh tokens.
- Implementing authentication management best practices, which require periodic credential rotation.

The GTAF uses "client_id" request parameter to identify itself when sending
requests to the token endpoint.

Of particular importance is the ability to rotate client credentials. The OAuth
server must be able to support two simultaneous pairs of credentials during
rotation, and must have the ability to disable credentials. In a typical
credential rotation:

1. The carrier creates new credentials on the OAuth server and delivers the credentials to their Technical Account Manager in a secure manner.
2. Google tests the new credential and changes the GTAF configuration to use the new credential.
3. Google notifies the carrier that the old credentials may be disabled.
4. The carrier disables the credentials and notifies Google
5. Google verifies the old credentials are no longer operational

The OAuth server must be able to support the above rotation process.

### Token Endpoint

The token endpoint is used by the GTAF to obtain an access token by presenting
its authorization grant or refresh token. The token endpoint is used with every
authorization grant except for the implicit grant type (since an access token is
issued directly).

The following are some points to be considered while configuring a token
endpoint:

- The location of the token endpoint should be provided in the service documentation.
- The endpoint URI may include an "application/x-www-form-urlencoded" formatted query component which must be retained when adding additional query parameters. The endpoint URI must not include a fragment component.
- Since requests to the token endpoint result in the transmission of clear-text credentials (in the HTTP request and response), the carrier's OAuth server must use TLS for sending requests to the token endpoint.
- The GTAF uses the HTTP "POST" method when making request for access token.
- Parameters sent without a value must be treated as omitted from the request. The OAuth server must ignore unrecognized request parameters. Request and response parameters must not be included more than once.
- GTAF only supports bearer type access tokens.

### Access Token Scope

The authorization and token endpoints allow the client to specify the scope of
the access request using the "scope" request parameter. In turn, the
authorization server uses the "scope" response parameter to inform the client of
the scope of the access token issued.

The value of the scope parameter is expressed as a list of space-delimited,
case-sensitive strings. The strings are defined by the authorization server. If
the value contains multiple space-delimited strings, their order does not
matter, and each string adds an additional access range to the requested scope.

     scope = scope-token *( SP scope-token )
     scope-token = 1*( %x21 / %x23-5B / %x5D-7E )

GTAF does not require the scope to be implemented, but does support this
feature. For more information, refer to
[Section 3.3](https://tools.ietf.org/html/rfc6749#section-3.3) of
[RFC 6749](https://tools.ietf.org/html/rfc6749).

### Issuing an Access Token

If the access token request sent by the GTAF is valid and authorized, the OAuth
server issues an access token and optional refresh token. If the request fails
client authentication or is invalid, the OAuth server returns an error response
as described in the following section.

#### Successful Response

When the GTAF sends a request, the OAuth server issues an access token and
optional refresh token, and constructs the response by adding the following
parameters to the entity-body of the HTTP response with a 200 (OK) status code:
\\

- **access_token:** REQUIRED. The access token issued by the OAuth server. GTAF expects the token endpoint to return a bearer token.
- **expires_in:** REQUIRED. The lifetime of access token in seconds. For example, the value "3600" denotes that the access token will expire in one hour from the time the response was generated. If omitted, the OAuth server should provide the expiration time via other means or document the default value.
- **token_type:** REQUIRED. The type of the token issued. For more information on different types of tokens, refer to[Section 7.1](https://tools.ietf.org/html/rfc6749#section-7.1) of [RFC 6749](https://tools.ietf.org/html/rfc6749). The value is case insensitive. GTAF only supports bearer tokens at the time of this writing.
- **refresh_token:** OPTIONAL. The refresh token, which can be used to obtain new access tokens using the same authorization grant.
- **scope:** OPTIONAL, if implemented and identical to the scope requested by the GTAF; otherwise, required.

The parameters are included in the entity-body of the HTTP response using the
"application/json". The parameters are serialized into a JavaScript Object
Notation (JSON) structure by adding each parameter at the highest structure
level. Parameter names and string values are included as JSON strings. Numerical
values are included as JSON numbers. The order of parameters does not matter and
can vary.

The authorization server MUST include the HTTP "Cache-Control" response header
field with a value of "no-store" in any response containing tokens, credentials,
or other sensitive information, as well as the "Pragma" response header field
with a value of "no-cache".   

<br />


For example:

         HTTP/1.1 200 OK
         Content-Type: application/json;charset=UTF-8
         Cache-Control: no-store
         Pragma: no-cache

         {
           "access_token":"2YotnFZFEjr1zCsicMWpAA",
           "token_type":"Bearer",
           "expires_in":3600,
           "refresh_token":"tGzv3JOkF0XG5Qx2TlKWIA",
           "example_parameter":"example_value"
         }

```

```

Following are some important points to consider:

- The GTAF ignores unrecognized value names in the response.
- The sizes of tokens and other values received from the OAuth server are left undefined.
- The GTAF should avoid making assumptions about value sizes. The OAuth server should document the size of any value it issues.

#### Error Response

If an authorization request fails because of any reason such as missing,
invalid, or mismatching redirection URI, or if the client identifier is missing
or invalid, the OAuth server should respond with an HTTP 400 (Bad Request)
status code (unless specified otherwise) and should include at least one of the
parameters listed in the Error Response and Codes section.

### Authorization Grant in GTAF

An authorization grant is a credential representing the end user's authorization
(to access its protected resources such as data balance information) used by the
GTAF to obtain an access token.

The GTAF uses the **client_credentials** grant type. In the
**client_credentials** grant type, GTAF requests a token using an HTTP POST
request and HTTP Basic Authentication. All requests are sent over TLS (i.e.,
HTTPS), and GTAF cannot integrate with an OAuth server without a valid TLS
certificate. GTAF is capable of passing a configurable token scope and will pass
an empty scope if one is not configured.

GTAF expects that an access token is returned along with an "expires_in" value
(time to live). The expires_in value should be at least 900 seconds, and should
not be more than a few hours. Requesting a new token must not cause existing
tokens to expire early.

For more details about various grant types, see
[section 1.3](https://tools.ietf.org/html/rfc6749#section-1.3) of
[RFC 6749](https://tools.ietf.org/html/rfc6749).

# Example Request and Response

Suppose that the GTAF has the following configuration for an OAuth server:

    URL: https://www.example.com/gettoken/
    Client ID: gtaf
    Client secret: password
    Scope: dpa

**Note:** The client secret for a real DPA must be much more secure than the one
shown in example.

To produce the authorization string, the client ID, ':', and password are
concatenated and base64-encoded. This can be replicated in a command line
interface as follows:

    $ echo -n gtaf:password | base64
    Z3RhZjpwYXNzd29yZA==

GTAF then makes an HTTPS POST request to the OAuth server using these
credentials, the client_credentials grant type, and the configured scope. For
the example, GTAF's request looks similar to the request generated by:

    $ curl -H 'Authorization: Basic Z3RhZjpwYXNzd29yZA==' -X POST \
    -d 'grant_type=client_credentials&scope=dpa' 'https://www.example.com/gettoken/'

The headers used by GTAF will not match those sent by curl, although the
authorization header will be identical.

GTAF expects a response in the form:

    {
    "access_token":"<token>",
    "token_type": "Bearer",
    "expires_in":<expiration time>
    }

Following is an example of a valid response:

    {
    "access_token":"YXRudWhhZXVoLGFodWFoaGF1aG9zaHVvYWV1Cg",
    "token_type": "Bearer",
    "expires_in":3600
    }

**Note:** The response must be valid JSON.

## Error Response and Codes

If an authorization request from GTAF fails due to any of the reasons stated in
the Error Response section, the OAuth server must respond with an HTTP 400 (Bad
Request) status code (unless specified otherwise) and include one of the
following parameters with the response:

For example: \\

         HTTP/1.1 400 Bad Request
         Content-Type: application/json;charset=UTF-8
         Cache-Control: no-store
         Pragma: no-cache

         {
           "error":"invalid_request"
         }

GTAF expects the OAuth server to support the following error responses:

|---|---|---|
| **Error Code** | **Response** | **Reason** |
| HTTP 400 | invalid_request | The request is missing a required parameter, includes an unsupported parameter value (other than grant type), repeats a parameter, includes multiple credentials, utilizes more than one mechanism for authenticating with the GTAF, or is otherwise malformed. |
| HTTP 401 | invalid_client | Client authentication failed (e.g., unknown client, no client authentication included, or unsupported authentication method). The OAuth server may return an HTTP 401 (Unauthorized) status code to indicate which HTTP authentication schemes are supported. If the client attempted to authenticate via the "Authorization" request header field, the OAuth server must respond with an HTTP 401 (Unauthorized) status code and include the "WWW-Authenticate" response header field matching the authentication scheme used by the client. |
| HTTP 500 | OAuth server failure |   |

For details of other responses which can be used for debugging, refer
to [section 5.2](https://tools.ietf.org/html/rfc6749#section-5.2) of
[RFC 6749](https://tools.ietf.org/html/rfc6749).