Send Docs Feedback

OAuthV2 policy

What

OAuthV2 is a multi-faceted policy for performing OAuth 2.0 grant type operations. This is the primary policy used to configure OAuth 2.0 endpoints on Apigee Edge.

If you want to learn more about OAuth on Apigee Edge, see the OAuth home page. It provides links to resources, samples, videos, and more. See the advanced OAuth sample on GitHub for a good demonstration of how this policy is used in a working application. 

Where

Place this policy on custom API proxy flows to generate access tokens, refresh tokens, authorization codes, to perform token validation, and other operations. For example, you might put this policy on an API proxy endpoint called /authorizationcode for apps to request authorization codes. Likewise, you might put this policy on an API proxy endpoint called /token to generate an access token when that endpoint is called.

ProxyEndpoint TargetEndpoint
    PreFlow Flow PostFlow PreFlow Flow PostFlow    
Request ?              
              ? Response
    PostFlow Flow PreFlow PostFlow Flow PreFlow    

Samples

VerifyAccessToken

This OAuthV2 policy configuration (with the VerifyAccessToken operation) verifies that an access token submitted to Apigee Edge is valid. When this policy operation is triggered, Edge looks for a valid access token in the request. If the access token is valid, the request is allowed to proceed. If invalid, all processing stops and an error is returned in the response. 

<OAuthV2 async="false" continueOnError="false" enabled="true" name="OAuth-v20-2">
    <DisplayName>OAuth v2.0 2</DisplayName>
    <Operation>VerifyAccessToken</Operation>
    <AccessTokenPrefix>Bearer</AccessTokenPrefix> <!-- Optional, default is Bearer -->
</OAuthV2>

Note that only bearer (access) tokens are supported. MAC tokens are not supported.

Apps must pass the access token in the Authorization HTTP request header. For example:

$ curl -H "Authorization: Bearer ylSkZIjbdWybfsUQe9BqP0LH5Z" http://{org_name}-test.apigee.net/weather/forecastrss?w=12797282

Generating access tokens

For examples showing how to request access tokens for each of the supported grant types, see Requesting access tokens and authorization codes. The topic includes examples of these operations:

  • Authorization code
  • Client credentials
  • Implicit
  • Password
  • Refresh Token
  • Authorization code

Generate authorization code

For examples showing how to request authorization codes, see Requesting access tokens and authorization codes.

Refresh an access token

For examples showing how to request access tokens using a refresh token, see Requesting access tokens and authorization codes.

Generate an access token on the response flow

Sometimes you may need to generate an access token in the response flow. For example, you may do this in response to some custom validation done in a backend service. In this example, the use case requires both an access token and a refresh token, ruling out the implicit grant type. In this case, we'll use the password grant type to generate the token. As you'll see, the trick to making this work is to pass in an Authorization request header with a JavaScript policy.

First, let's look at the sample policy:

<OAuthV2 enabled="true" continueOnError="false" async="false" name="generateAccessToken">
    <Operation>GenerateAccessToken</Operation>
    <AppEndUser>Doe</AppEndUser>
    <UserName>jdoe</UserName>
    <PassWord>jdoe</PassWord>
    <GrantType>grant_type</GrantType>
    <ClientId>a_valid_client_id</ClientId>
    <SupportedGrantTypes>
        <GrantType>password</GrantType>
    </SupportedGrantTypes>
</OAuthV2>

If you put this policy on the response flow, it will fail with a 401 UnAuthorized error even though the correct login parameters are specified in the policy. To solve this problem, you need to set an Authorization request header. 

The Authorization header must contain a Basic access scheme with the Base64-encoded client_id:client_secret.

You can add this header with a JavaScript policy placed just before the OAuthV2 policy, like this. The "local_clientid" and "local_secret" variables must be previously set and available in the flow:

var client_id = context.getVariable("local_clientid");
var client_secret = context.getVariable("local_secret");
context.setVariable("request.header.Authorization","Basic "+CryptoJS.enc.Base64.stringify(CryptoJS.enc.Latin1
                                      .parse(client_id + ':' + client_secret)));

See also "Encoding basic authentication credentials". 

Element reference

The policy reference describes the elements and attributes of the OAuthV2 policy.

The way you configure this policy, and the elements you need to specify, depend on which operation you want the policy to perform. For example, if you are implementing the authorization code grant type, then you will require four separate OAuthV2 policies to perform authorization code generation, access code generation, access code validation, and refresh token generation. This reference lists all of the elements that can be used with this policy.

If you want to see configurations for specific grant type use cases, refer to the OAuth home page for a list of grant type implementations. In particular, see the advanced OAuth sample on GitHub for a good demonstration of how this policy is used in a working application. 

The sample policy shown below is one of many possible configurations. This sample shows an OAuthV2 policy configured for the GenerateAccessToken operation. It includes required and optional elements. Refer to the element descriptions in this section for details.

<OAuthV2 name="GenerateAccessToken">
  <Operation>GenerateAccessToken</Operation>
  <ExpiresIn>1000</ExpiresIn>
  <GenerateResponse />
  <SupportedGrantTypes>
   <GrantType>authorization_code</GrantType>
  </SupportedGrantTypes>
  <GrantType>request.queryparam.grant_type</GrantType>
  <Code>request.queryparam.code</Code>
  <ClientId>request.queryparam.client_id</ClientId>
  <RedirectUri>request.queryparam.redirect_uri</RedirectUri>
  <Scope>request.queryparam.scope</Scope>
</OAuthV2>
    

<OAuthV2> attributes

<OAuthV2 async="false" continueOnError="false" enabled="true" name="MyOAuthPolicy">

The following attributes are common to all policy parent elements.

Attribute Description Default Presence
name

The internal name of the policy. Characters you can use in the name are restricted to: A-Z0-9._\-$ %. However, the Edge management UI enforces additional restrictions, such as automatically removing characters that are not alphanumeric.

Optionally, use the <DisplayName> element to label the policy in the management UI proxy editor with a different, natural-language name.

N/A Required
continueOnError

Set to false to return an error when a policy fails. This is expected behavior for most policies.

Set to true to have flow execution continue even after a policy fails.

false Optional
enabled

Set to true to enforce the policy.

Set to false to "turn off" the policy. The policy will not be enforced even if it remains attached to a flow.

true Optional
async

Note: This attribute does not make the policy execute asynchronously.

When set to true, policy execution is offloaded to a different thread, leaving the main thread free to handle additional requests. When the offline processing is complete, the main thread comes back and finishes handling the message flow. In some cases, setting async to true improves API proxy performance. However, overusing async can hurt performance with too much thread switching.

To use asynchronous behavior in API proxies, see JavaScript callouts.

false Optional

<DisplayName> element

Use in addition to the name attribute to label the policy in the management UI proxy editor with a different, natural-language name.

<DisplayName>Policy Display Name</DisplayName>
Default:

N/A

If you omit this element, the the value of the policy's name attribute is used.

Presence: Optional
Type: String

 

<AccessToken> element

<AccessToken>request.header.access_token</AccessToken>

By default, VerifyAccessToken expects the access token to be sent in an Authorization header. You can change that default using this element. For example request.queryparam.access_token indicates that the access token should be present as a query parameter.

If presented in the header, it must be an Authorization header and be sent as a Bearer token. For example:

-H "Authorization: Bearer Rft3dqrs56Blirls56a"

Currently, Bearer is the only supported prefix.

Default:

request.header.access_token

Presence:

Optional

Type: String
Valid values:

A valid access token

Used with operations:
  • VerifyAccessToken

<AccessTokenPrefix> element

<AccessTokenPrefix>Bearer</AccessTokenPrefix>

By default, VerifyAccessToken expects the access token to be sent in an Authorization header as a Bearer token. For example:

-H "Authorization: Bearer Rft3dqrs56Blirls56a"

Currently, Bearer is the only supported prefix.

Default:

Bearer

Presence:

Optional

Type: String
Valid values:

Bearer

Used with operations:
  • VerifyAccessToken

 

<AppEndUser> element

<AppEndUser>request.queryparam.app_enduser</AppEndUser>

In cases where the app end user ID must be sent to the authorization server, this element lets you specify where Edge should look for the end user ID. For example, it could be sent as a query parameter or in an HTTP header.

For example request.queryparam.app_enduser indicates that the AppEndUser should be present as a query parameter, as, for example, ?app_enduser=ntesla@theramin.com. To require the AppEndUser in an HTTP header, for example, set this value to request.header.app_enduser.

Providing this setting enables you to include an app end user ID in the access token. This feature is useful if you want to be able to retrieve or revoke OAuth 2.0 access tokens by end user ID. For more information, see Enable retrieval and revocation of OAuth 2.0 access tokens by end user ID, app id, or both.

Default:

N/A

Presence:

Optional

Type: String
Valid values:

Any flow variable accessible to the policy at runtime.

Used with grant types:
  • authorization_code
  • implicit
  • password
  • client_credentials

<Attributes/Attribute>

<Attributes>
    <Attribute name=”attr_name1” ref=”flow.variable” display="true|false">value1</Attribute>
    <Attribute name=”attr_name2” ref=”flow.variable” display="true|false">value2</Attribute>
</Attributes>

Use this element to add custom attributes to an access token or authorization code. For example, you may wish to embed a user ID or session identifier in an access token that can be extracted and checked at runtime.

This element takes a value from a flow variable or a default value which is specified in the policy. If both are specified, the value specified in the flow variable is taken. The optional display attribute can be set to true to false. If set to true, the attribute will not be shown in the response. Default value is false.

For more information on using this element, see Customizing tokens and auth codes.

Default:

N/A

Presence:

Optional

Valid values:
  • name -The attribute name
  • ref - The value of the attribute. Can come from a flow variable.
  • display - (Optional) If set to true, the attribute will not be shown in the response. Default value is false.
Used with grant types:
  • authorization_code
  • implicit
  • password
  • client_credentials
  • Can also be used with the GenerateAuthorizationCode operation.

<ClientId> element

<ClientId>request.queryparam.client_id</ClientId>

In several cases, the client app must send the client ID to the authorization server. This element lets you specify where Edge should look for the client ID. For example, it could be sent as a query parameter or in an HTTP header.

The variable request.queryparam.client_id indicates that the client_id should be present as a query parameter, as, for example, ?client_id=AfGlvs9. To require the ClientId in an HTTP header, for example, set this value to request.header.client_id. See also Requesting access tokens and authorization codes.

Default:

request.formparam.client_id (a x-www-form-urlencoded and specified in the request body)

Presence:

Optional

Type: String
Valid values: Any flow variable accessible to the policy at runtime
Used with grant types:
  • authorization_code
  • password
  • implicit
  • client_credentials

Can also be used with the GenerateAuthorizationCode operation.

<Code> element

<Code>request.queryparam.code</Code>

In the authorization grant type flow, the client must submit an authorization code to the authorization server (Apigee Edge). This element lets you specify where Edge should look for the authorization code. For example, it could be sent as a query parameter, HTTP header, or form parameter (the default).

The variable, request.queryparam.auth_code indicates that the authorization code should be present as a query parameter, as, for example, ?auth_code=AfGlvs9. To require the authorization code in an HTTP header, for example, set this value to request.header.auth_code. See also Requesting access tokens and authorization codes.

Default:

request.formparam.code (a x-www-form-urlencoded and specified in the request body)

Presence:

optional

Type: String
Valid values: Any flow variable accessible to the policy at runtime
Used with grant types: authorization_code

<ExpiresIn> element

<ExpiresIn>10000</ExpiresIn> 

Enforces the expiry time of access tokens, refresh tokens, and authorization codes in milliseconds. The expiry time value is a system generated value plus the <ExpiresIn> value. If <ExpiresIn> is set to -1, the token or code is given an infinite lifetime. If <ExpiresIn> is not specified, the system applies a default value configured at the system level. Contact Apigee Support for more information about default system settings.

The expiry time can also be set at runtime using a reference to a flow variable. The flow variable can be retrieved from a header, query parameter, or form parameter (default). Or, it can be a hard-coded value. 

For example request.queryparam.expires_in indicates that the expiry value should be present as a query parameter, as, for example, ?expires_in=360000. To require the value to come from an HTTP header, for example, set this value to request.header.expires_in

The following stanza specifies a flow variable and a default value as well. Note that the flow variable value takes precedence over the specified default value.

<ExpiresIn ref="flow.variable">
    {default_value}
</ExpiresIn>

Default:

If not specified, the system applies a default value configured at the system level.

Presence:

Optional

Type: Integer
Valid values: Any integer, including -1 (which indicates an infinite expiry time).
Used with grant types:
  • authorization_code
  • implicit
  • password
  • client_credentials
  • refresh_token

Also used with GenerateAuthorizationCode operation.

<ExternalAccessToken> element

<ExternalAccessToken>request.queryparam.external_access_token</ExternalAccessToken>

Tells Apigee Edge where to find an external access token (an access token not generated by Apigee Edge).

The variable request.queryparam.external_access_token indicates that the external access token should be present as a query parameter, as, for example, ?external_access_token=12345678. To require the external access token in an HTTP header, for example, set this value to request.header.external_access_token. See also Using third-party OAuth tokens.

<ExternalAuthorization> element

<ExternalAuthorization>true</ExternalAuthorization>

If this element is false or not present, then Edge validates the client_id and client_secret normally against the Apigee Edge authorization store. Use this element when you want to work with third-party OAuth tokens. For details on using this element, see Using third-party OAuth tokens.

Default:

false

Presence:

Optional

Type: Boolean
Valid values: true or false
Used with grant types:
  • authorization_code
  • password
  • client_credentials

 

<GenerateResponse> element

<GenerateResponse enabled='true'/>

If set to true, the policy generates and returns a response. If false, no response is sent. Instead, a set of flow variables are populated with values related to the policy's function. For example, a flow variable called oauthv2authcode.OAuthV2-GenerateAuthorizationCode.code gets populated with the newly minted auth code.

Default:

false

Presence:

Optional

Type: string
Valid values: true or false
Used with grant types:
  • implicit
  • password
  • client_credentials
  • refresh_token
  • Also can be used with the GenerateAuthorizationCode operation.

 

<GenerateErrorResponse> element

<GenerateErrorResponse enabled='true'/>

If set to true, the policy generates and returns a response if the ContinueOnError attribute is set to true. If false (the default), no response is sent. Instead, a set of flow variables are populated with values related to the policy's function. 

Default:

false

Presence:

Optional

Type: string
Valid values: true or false
Used with grant types:
  • implicit
  • password
  • client_credentials
  • refresh_token
  • Also can be used with the GenerateAuthorizationCode operation.

<GrantType>

<GrantType>request.queryparam.grant_type</GrantType>

Tells the policy where to find the grant type parameter that is passed in a request. Per the OAuth 2.0 specification, the grant type must be supplied with requests for access tokens and authorization codes. The variable can be a header, query parameter, or form parameter (default). Or, it can be a hard-coded value. 

For example request.queryparam.grant_type indicates that the Password should be present as a query parameter, as, for example, ?grant_type=password. To require the grant type in an HTTP header, for example, set this value to request.header.grant_type. See also Requesting access tokens and authorization codes.

Default:

request.formparam.grant_type (a x-www-form-urlencoded and specified in the request body)

Presence:

Optional

Type: string
Valid values: A variable, as explained above, or a hard-coded grant type of: client_credentials, implicit, authorization_code, or password
Used with grant types:
  • authorization_code
  • password
  • implicit
  • client_credentials
  • refresh_token

<Operation> element

<Operation>GenerateAuthorizationCode</Operation>

The OAuth 2.0 operation executed by the policy. See also the Grant type and operations reference below.

Default:

If <Operation> is not specified, Edge looks at the list of <SupportedGrantTypes>. Only operations on those grant types will be successful. In other words, you can omit <Operation> if you specify a <GrantType> in the <SupportedGrantTypes> list. If neither <Operation> nor <SupportedGrantTypes> are specified, the default grant type is authorization_code. That is, authorization_code grant type requests will succeed, but all others will fail.

Presence:

Optional

Type: String
Valid values:

<PassWord> element

<PassWord>request.queryparam.password</PassWord>

In cases where the app user's password must be sent to the authorization server, this element lets you specify where Edge should look for the password. For example, it could be sent as a query parameter, in an HTTP header, or a form parameter (default).

For example request.queryparam.password indicates that the password should be present as a query parameter, as, for example, ?password=changeit. To require the password in an HTTP header, for example, set this value to request.header.password. See also Requesting access tokens and authorization codes.

Default:

request.formparam.password (a x-www-form-urlencoded and specified in the request body)

Presence:

Optional

Type: String
Valid values: Any flow variable available to the the policy at runtime.
Used with grant types: password

<RedirectUri> element

<RedirectUri>request.queryparam.redirect_uri</RedirectUri>

Specifies where Edge should look for the redirect_uri parameter in the request.

About redirection URIs

Redirection URIs are used with the authorization code and implicit grant types. The redirect URI tells the authorization server (Edge) where to send an authorization code (for the auth code grant type) or access token (for the implicit grant type). It's important to understand when this parameter is required, when it is optional, and how it is used:

  • (required) If a Callback URL is registered with the developer app that is associated with the request's client keys, and if the request_uri is present in the request, then the two must match exactly. If they do not match, an error is returned. For information on registering developer apps on Edge and specifying a Callback URL, see Register apps.
  • (optional) If a Callback URL is registered, and the request_uri is missing from the request, then Edge redirects to the registered Callback URL.
  • (required) If a Callback URL is not registered, then the request_uri is required. Note that in this case, Edge will accept ANY URL. This case can present a security issue, and therefore should only be used with trusted client apps. If client apps are not trusted, then the best practice is to always require the registration of a Callback URL.

You can send this parameter in a query parameter or in a header. The variable request.queryparam.redirect_uri indicates that the RedirectUri should be present as a query parameter, as, for example, ?redirect_uri=login.myapp.com. To require the RedirectUri in an HTTP header, for example, set this value to request.header.redirect_uri. See also Requesting access tokens and authorization codes.

Default:

request.formparam.redirect_uri (a x-www-form-urlencoded and specified in the request body)

Presence:

Optional

Type: String
Valid values: Any flow variable accessible in the policy at runtime
Used with grant types:
  • authorization_code
  • implicit

Also used with the GenerateAuthorizationCode operation.

<RefreshToken> element

<RefreshToken>request.queryparam.refreshtoken</RefreshToken>

When requesting an access token using a refresh token, you must supply the refresh token in the request. This element lets you specify where Edge should look for the refresh token. For example, it could be sent as a query parameter, HTTP header, or form parameter (the default).

The variable request.queryparam.refreshtoken indicates that the refresh token should be present as a query parameter, as, for example, ?refresh_token=login.myapp.com. To require the RedirectUri in an HTTP header, for example, set this value to request.header.refresh_token. See also Requesting access tokens and authorization codes.

Default:

request.formparam.refresh_token (a x-www-form-urlencoded and specified in the request body)

Presence:

Optional

Type: String
Valid values: Any flow variable accessible in the policy at runtime
Used with grant types:
  • refresh_token

<RefreshTokenExpiresIn> element

<RefreshTokenExpiresIn>1000</RefreshTokenExpiresIn>

Enforces the expiry time of refresh tokens in milliseconds. The expiry time value is a system generated value plus the <RefreshTokenExpiresIn> value. If <RefreshTokenExpiresIn> is set to -1, the refresh token is given an infinite lifetime. If <RefreshTokenExpiresIn> is not specified, the system applies a default value configured at the system level. Contact Apigee Support for more information about default system settings.

The expiry time can also be set at runtime using a reference to a flow variable. The flow variable can be retrieved from a header, query parameter, or form parameter (default). Or, it can be a hard-coded value. 

For example request.queryparam.expires_in indicates that the expiry value should be present as a query parameter, as, for example, ?expires_in=360000. To require the value to come from an HTTP header, for example, set this value to request.header.expires_in

The following stanza specifies a flow variable and a default value as well. Note that the flow variable value takes precedence over the specified default value.

<RefreshTokenExpiresIn ref="flow.variable">
    {default_value}
</RefreshTokenExpiresIn>

Default:

If not specified, the system applies a default value configured at the system level.

Presence:

Optional

Type: Integer
Valid values:

Any integer, including -1 (which indicates an infinite expiry time).

Used with grant types:
  • authorization_code
  • password
  • refresh_token

<ResponseType> element

<ResponseType>request.queryparam.response_type</ResponseType>

This element informs Edge which grant type the client app is requesting. It is used only with the authorization code and implicit grant type flows. 

By default, Edge looks for the response type value in a response_type query parameter. If you wish to override this default behavior, use the <ResponseType> element to configure a flow variable containing the response type value. For example, if you set this element to request.header.response_type, Edge looks for the response type to be passed in the request header.  See also Requesting access tokens and authorization codes.

Default:

request.formparam.response_type (a x-www-form-urlencoded and specified in the request body)

Presence:

Optional. Use this element if you wish to override the default behavior. 

Type: String
Valid values: Either code (for the authorization code grant type) or token (for the implicit grant type)
Used with grant types:
  • implicit
  • Also used with the GenerateAuthorizationCode operation.

<ReuseRefreshToken> element

<ReuseRefreshToken>true</ReuseRefreshToken>

When set to true, the existing refresh token is reused until it expires. If false, a new refresh token is issued by Apigee Edge when a valid refresh token is presented.

Default:

false

Presence:

optional

Type: boolean
Valid values:

true or false

Used with grant type:
  • refresh_token

<Scope> element

<Scope>request.queryparam.scope</Scope>

If this element is present in an of the GenerateAccessToken or GenerateAuthorizationCode policies, it is used to specify which scopes to grant the token or code. These values are typically passed to the policy in the request from a client app. You can configure the element to take a flow variable, giving you the option to choose how the scopes are passed in a request. In the following example, request.queryparam.scope indicates that the scope should be present as a query parameter, as, for example, ?scope=READ. To require the scope in an HTTP header, for example, set this value to request.header.scope.

If this element appears in a "VerifyAccessToken" policy, then it is used to specify which scopes the policy should enforce. In this type of policy, the value must be a "hard coded" scope name -- you can't use variables. For example:

<Scope>A B</Scope>

 See also Working with scopes and Requesting access tokens and authorization codes.

Default:

No scope

Presence:

Optional

Type: String
Valid values:

If used with Generate* policies, a flow variable. 

If used with VerifyAccessToken, a space-separated list of scope names (strings).

Used with grant types:
  • authorization_code
  • implicit
  • password
  • client_credentials
  • Can also be used with the GenerateAuthorizationCode and VerifyAccessToken operations.

<State> element

<State>request.queryparam.state</State>

In cases where the client app must send the state information to the authorization server, this element lets you specify where Edge should look for the state values. For example, it could be sent as a query parameter or in an HTTP header. The state value is typically used as a security measure to prevent CSRF attacks.

For example request.queryparam.state indicates that the state should be present as a query parameter, as, for example, ?state=HjoiuKJH32. To require the state in an HTTP header, for example, set this value to request.header.state. See also See also Requesting access tokens and authorization codes.

Default:

No state

Presence:

Optional

Type: String
Valid values: Any flow variable accessible to the policy at runtime
Used with grant types:
  • All
  • Can also be used with the GenerateAuthorizationCode operation

<StoreToken> element

 <StoreToken>true</StoreToken> 

Set this element to true when the <ExternalAuthorization> element is true. The <StoreToken> element tells Apigee Edge to store the external access token. Otherwise, it will not be persisted.

Default:

false

Presence:

Optional

Type: Boolean
Valid values: true or false
Used with grant types:
  • authorization_code
  • password
  • client_credentials

<SupportedGrantTypes>/<GrantType> element

<SupportedGrantTypes>
    <GrantType>authorization_code</GrantType>
    <GrantType>client_credentials</GrantType>
    <GrantType>implicit</GrantType>
    <GrantType>password</GrantType>
</SupportedGrantTypes>

Specifies the grant types supported by an OAuth token endpoint on Apigee Edge. An endpoint may support multiple grant types (that is, a single endpoint can be configured to distribute access tokens for multiple grant types.) For more on endpoints, see Understanding OAuth endpoints. The grant type is passed in token requests in a grant_type parameter.

If no supported grant types are specified, then the only allowed grant types are authorization_code and implicit. See also the <GrantType> element (which is a higher-level element that is used to specify where Apigee Edge should look for the grant_type parameter that is passed in a client request. Edge will make sure that the value of the grant_type parameter matches one of the supported grant types). 

Default:

authorization _code and implicit

Presence:

Required

Type: String
Valid values:
  • client_credentials
  • authorization_code
  • password
  • implicit

<Tokens>/<Token> element

Used with the ValidateToken and InvalidateToken operations. See also Approving and revoking access tokens. The <Token> element identifies the flow variable that defines the source of the token to be revoked. If developers are expected to submit access tokens as query parameters named access_token, for example, use request.queryparam.access_token.

<UserName> element

<UserName>request.queryparam.user_name</UserName>

In cases where the app user name must be sent to the authorization server, this element lets you specify where Edge should look for the end user name. For example, it could be sent as a query parameter or in an HTTP header.

For example request.queryparam.username indicates that the username should be present as a query parameter, as, for example, ?username=joe. To require the UserName in an HTTP header, for example, set this value to request.header.username. See also Requesting access tokens and authorization codes.

Default:

request.formparam.password (a x-www-form-urlencoded and specified in the request body)

Presence:

Optional

Type: String
Valid values: Any variable setting.
Used with grant types: password

Verifying access tokens

Once a token endpoint is set up for an API proxy, a corresponding OAuthV2 policy that specifies the VerifyAccessToken operation is attached to the Flow that exposes the protected resource.

For example, to ensure that all requests to an API are authorized, the following policy enforces access token verification:

<OAuthV2 name="VerifyOAuthAccessToken">
  <Operation>VerifyAccessToken</Operation>
</OAuthV2>

The policy is attached to the API resource to be protected. To ensure that all requests to an API are verified, attach the policy to the ProxyEndpoint request PreFlow, as follows:

<PreFlow>
  <Request>
    <Step><Name>VerifyOAuthAccessToken</Name></Step>
  </Request>
</PreFlow>

The following optional elements can be used to override the default settings for the VerifyAccessToken operation.

Name Description
Scope

A space-delimited list of scopes. Verification will succeed if at least one of the scopes listed is present in the access token. For example, the following policy will check the access token to ensure that it contains at least one of the scopes listed. If READ or WRITE is present, verification will succeed.

<OAuthV2 name="ValidateOauthScopePolicy">
  <Operation>VerifyAccessToken</Operation>
  <Scope>READ WRITE</Scope>
</OAuthV2>
AccessToken The variable where the access token is expected to be located. For example request.queryparam.accesstoken. By default, the access token is expected to be presented by the app in the Authorization HTTP header,  according to the OAuth 2.0 specification. Use this setting if the access token is expected to be presented in a non-standard location, such as a query parameter, or an HTTP header with a name other than Authorization.

See also Verifying access tokens and Requesting access tokens and authorization codes.

Specifying request variable locations

For each grant type, the policy makes assumptions about the location or required information in request messages. These assumptions are based on the the OAuth 2.0 specification. If your apps need to deviate from the OAuth 2.0 specification, then you can specify the expected locations for each parameter. For example, when handling an authorization code, you can specify the location of the authorization code, the client ID, the redirect URI, and the scope. These can be specified as HTTP headers, query parameters, or form parameters.

The example below demonstrates how you can specify the location of required authorization code parameters as HTTP headers:

  ...
  <GrantType>request.header.grant_type</GrantType>
  <Code>request.header.code</Code>
  <ClientId>request.header.client_id</ClientId>
  <RedirectUri>request.header.redirect_uri</RedirectUri>
  <Scope>request.header.scope</Scope>
  ...

Or, if necessary to support your client app base, you can mix and match headers and query parameters:

  ...
  <GrantType>request.header.grant_type</GrantType>
  <Code>request.header.code</Code>
  <ClientId>request.queryparam.client_id</ClientId>
  <RedirectUri>request.queryparam.redirect_uri</RedirectUri>
  <Scope>request.queryparam.scope</Scope>
  ...

Only one location can be configured per parameter.

Flow variables

The flow variables defined in this table are populated when the respective OAuth policies are executed, and hence are available to other policies or applications executing in the API proxy flow.

VerifyAccessToken operation

These variables are set when the VerifyAccessToken policy operation executes.

API product variables will be populated automatically if the API products are configured with valid environment, proxies, and API resources (derived from the proxy.pathsuffix). Explicitly setting flow.resource.name variable is not required.

Where the API products are not configured with valid environments and API proxies, then flow.resource.name must explicitly be set to populate API product variables in the flow.

For details on product configuration, see Using the Edge management API to Publish APIs.

Variables Description
organization_name The name of the organization where the proxy is executing.
developer.id The ID of the developer associated with the registered client app.
developer.app.name The name of the developer associated with the registered client app.
client_id The client ID of the registered client app.
grant_type The grant type associated with the request.
token_type The token type associated with the request.
access_token The access token that is being verified.
accesstoken.{custom_attribute} A named custom attribute in the access token.
issued_at The date the access token was issued.
expires_in The expiration time for the access token.
status The status of the access token (e.g., approved or revoked).
scope The scope (if any) associated with the access token.
apiproduct.<custom_attribute_name> A named custom attribute of the API product associated with the registered client app.
apiproduct.name The name of the API product associated with the registered client app.
   
App-specific variables  
app.name  
app.id  
app.accessType  
app.callbackUrl  
app.status  
app.scopes  
app.appFamily  
app.apiproducts  
app.appParentStatus  
app.appType  
app.appParentId  
app.created_by  
app.created_at  
app.last_modified_at  
app.last_modified_by  
app.{custom_attributes}  
   
Developer-specific variables Note : If the app.appType is "Company" ,then company attributes are populated and if app.appType is "Developer", then developer attributes are populated.
developer.id  
developer.userName  
developer.firstName  
developer.lastName  
developer.email  
developer.status  
developer.apps  
developer.created_by  
developer.created_at  
developer.last_modified_at  
developer.last_modified_by  
developer.{custom_attributes}  
   
Company-specific variables Note : If the app.appType is "Company" ,then company attributes are populated and if app.appType is "Developer", then developer attributes are populated.
company.id  
company.displayName  
company.apps  
company.appOwnerStatus  
company.created_by  
company.created_at  
company.last_modified_at  
company.last_modified_by  
company.{custom_attributes}  

GenerateAuthorizationCode operation

These variables are set when the GenerateAuthorizationCode policy operation executes successfully:

Variable Description
oauthv2authcode.{policy_name}.code The authorization code generated when the policy executes.
oauthv2authcode.{policy_name}.redirect_uri The redirect URI associated with the registered client app.
oauthv2authcode.{policy_name}.scope The optional OAuth scope passed in the client request.
oauthv2authcode.{policy_name}.client_id The client ID passed in the client request.

 

GenerateAccessToken

These variables are set when the GenerateAccessToken policy operation executes successfully for the authorization code, password, and client credentials grant type flows:

Variable Description
oauthv2accesstoken.{policy_name}.access_token The access token generated when the policy executes.
oauthv2accesstoken.{policy_name}.token_type Will be set to accesstoken.
oauthv2accesstoken.{policy_name}.expires_in The expiry value for the token. See the <ExpiresIn> element for details.
oauthv2accesstoken.{policy_name}.refresh_token The refresh token generated when the policy executes.
oauthv2accesstoken.{policy_name}.refresh_token_expires_in The lifespan of the refresh token, in seconds.
oauthv2accesstoken.{policy_name}.refresh_token_issued_at This time value is the string representation of the corresponding 32-bit timestamp quantity. For example, 'Wed, 21 Aug 2013 19:16:47 UTC' corresponds to the timestamp value of 1377112607413.
oauthv2accesstoken.{policy_name}.refresh_token_status Set to approved or revoked.

 

GenerateAccessTokenImplicitGrant

These variables are set when the GenerateAccessTokenImplicit policy operation executes successfully for the implicit grant type flow:

Variable Description
oauthv2accesstoken.{policy_name}.access_token The access token generated when the policy executes.
oauthv2accesstoken.{policy_name}.expires_in The expiry value for the token. See the <ExpiresIn> element for details.

RefreshAccessToken operation

These variables are set when the RefreshAccessToken policy operation executes successfully:

Variable Description
oauthv2accesstoken.{policy_name}.access_token The access token generated when the policy executes.
oauthv2accesstoken.{policy_name}.token_type Will be set to accesstoken.
oauthv2accesstoken.{policy_name}.expires_in The expiry value for the token. See the <ExpiresIn> element for details.
oauthv2accesstoken.{policy_name}.refresh_token The refresh token generated when the policy executes.
oauthv2accesstoken.{policy_name}.refresh_token_expires_in The lifespan of the refresh token, in seconds.
oauthv2accesstoken.{policy_name}.refresh_token_issued_at This time value is the string representation of the corresponding 32-bit timestamp quantity. For example, 'Wed, 21 Aug 2013 19:16:47 UTC' corresponds to the timestamp value of 1377112607413.
oauthv2accesstoken.{policy_name}.refresh_token_status Set to approved or revoked.

 

GenerateErrorResponse

These variables are set when the GenerateErrorResponse element is true. 

Variable Description
oauthV2.{policy-name}.failed Set to true if the policy failed. 
oauthv2.{policy_name}.{fault_name} The name of the fault. For example, invalid_request
oauthv2.{policy_name}.{fault_cause} The fault reason. For example: Token Expired

Error codes

The default format for error codes returned by Policies is:

{
  "code" : " {ErrorCode} ",
  "message" : " {Error message} ",
  "contexts" : [ ]
}

The OAuthV2 Policy type defines the following error codes.

For OAuth-related HTTP error codes, see OAuth HTTP status code reference.

Error Code Message
FailedToResolveOAuthConfig Failed to resolve oauth config {0}
OperationRequired Operation required
InvalidOperation Operation {0} is invalid
InsufficientScope Required scope(s) : {0}
FailedToResolveClientId Failed to resolve client id variable {0}
FailedToResolveAccessToken Failed to resolve access token variable {0}
FailedToResolveRefreshToken Failed to resolve refresh token variable {0}
FailedToResolveToken Failed to resolve token variable {0}
FailedToResolveAuthorizationCode Failed to resolve authorization code variable {0}
ExpiresInNotApplicableForOperation ExpiresIn element is not valid for operation {0}
RefreshTokenExpiresInNotApplicableForOperation RefreshToken ExpiresIn element is not valid for operation {0}
InvalidValueForExpiresIn Invalid value for ExpiresIn element for operation {0}
InvalidValueForRefreshTokenExpiresIn Invalid value for Refresh Token ExpiresIn element for operation {0}
InvalidGrantType Invalid grant type: {0}
GrantTypesNotApplicableForOperation Grant types are not applicable for operation {0}
UnSupportedGrantType Unsupported Grant Type: {0}
InvalidParameter Invalid required paramater: {0}
MissingParameter Missing required paramater: {0}
SpecifyValueOrRefApiKey Specify Api Key as value or ref in stepDefinition {0}
SpecifyAPIProduct Specify the API Product to get details {0}
FailedToFetchApiProduct Failed to fetch api product for key {0}
FailedToResolveAPIKey Failed to resolve API Key variable {0}
FailedToResolveAPIProduct Failed to resolve API product variable {0}
InvalidTokenType Valid token types : {0}, Invalid token type {1} in stepDefinition {2}
TokenValueRequired Token value is required in stepDefinition {0}
FailedToResolveRealm Failed to resolve realm {0}
When verifying an access token, if you happen to see this error: "Invalid API call as no apiproduct match found", go to this Apigee Community article for details on the cause of this error and steps to correct it. 

Policy schema

Each policy type is defined by an XML schema (.xsd). For reference, policy schemas are available on GitHub.

Working with the default OAuth configuration

Each organization (even a free trial org) on Apigee Edge is provisioned with an OAuth token endpoint. The endpoint is preconfigured with policies in the API proxy called oauth. You can begin using the token endpoint as soon as you create an account on Apigee Edge. For details, see Understanding OAuth endpoints.

Related topics

 

Help or comments?