OpenID Connect OAuth 2.0 Token Enforcement Policy | MuleSoft Documentation
# OpenID Connect OAuth 2.0 Token Enforcement Policy
**Policy Name** | OpenID Connect OAuth 2.0 Token Enforcement  
---|---  
Allows access only to authorized client applications  
Security  
**First Flex Gateway version available**  
**Returned Status Codes** | 400 - Invalid token  
401 - Unauthorized access or error when connecting to the authorization server  
403 - Forbidden, invalid client application credentials  
500 - Bad response from authorization server  
## Summary
The OpenID Connect Access Token Enforcement policy restricts access to a protected resource to only those HTTP requests that provide a valid Oauth2 token belonging to a client application with API access. The policy does not generate tokens but only validates them.
This policy is available only to an organization that is configured to use the OpenID Connect dynamic client registration as a client-management solution.
## Configuring Policy Parameters
### Flex Gateway Local Mode
In Local Mode, you apply the policy to your API via declarative configuration files. Refer to the following policy definition and table of parameters:
```
- policyRef:
  name: openidconnect-access-token-enforcement-flex
 config:
  authenticationTimeout: <int> // OPTIONAL, default: 10000
  scopes: <string> // OPTIONAL, default: ""
  secureTrustStore: <bool> // OPTIONAL, default: false
  scopeValidationCriteria: <string> // OPTIONAL, default: "AND"
  exposeHeaders: <bool> // OPTIONAL, default: false
  skipClientIdValidation: <bool> // OPTIONAL, default: true
  maxFederationExpirationTime: <int> // OPTIONAL, default: -1
  maxCacheSize: <int> // OPTIONAL, default: 1000
```

Parameter | Required or Optional | Default Value | Description  
---|---|---|---  
`authenticationTimeout`  
An empty string |  A space-separated list of supported scopes: `read` `write`  
`secureTrustStore`  
`scopeValidationCriteria` |  Determines if the token must contain all defined scopes or just one  
`exposeHeaders` |  In a proxy scenario, this specifies whether headers must be exposed in the request to the backend. User properties returned by the federation server are prefixed with 'X-AGW-' and sent as headers to the backend. See Leveraging Token Validation Endpoint Information for more information about this parameter.  
`skipClientIdValidation` |  Skips the client application’s API contract validation. If `true`, Step 4 of the diagram in the How This Policy Works section is skipped.  
`maxFederationExpirationTime` |  Max Expiration time in seconds. See Token Caching for more information about this parameter.  
`maxCacheSize` |  Amount of tokens to be cached. See Token Caching for more information about this parameter.  
#### Resource Configuration Example
```
- policyRef:
  name: openidconnect-access-token-enforcement-flex
 config:
  authenticationTimeout: 10000
  scopes: read write
  secureTrustStore: false
  scopeValidationCriteria: OR
  exposeHeaders: true
  skipClientIdValidation: false
```

### Managed Flex Gateway and Flex Gateway Connected Mode
When you apply the policy to your API instance from the UI, the following parameters are displayed:
Element | Description | Example  
---|---|---  
Displays a space-separated list of supported scopes. | READ, WRITE, READ and WRITE  
Scope Validation Criteria | Determines if the token must contain all defined scopes or just one. The values are `Contains all scopes` and `Contains any scope`. | If the 'Contains all scopes' value is selected, the tokens with the scopes `READ` and `WRITE` are accepted. If the 'Contains any scopes' value is selected, the tokens with the scopes `READ, WRITE, and READ AND WRITE` are accepted.  
Expose Headers | In a proxy scenario, specifies whether headers must be exposed in the request to the backend. User properties returned by the federation server are prefixed with 'X-AGW-' and sent as headers to the backend.  
Skip Client Id Validation | Skips the client application’s API contract validation. | If selected, Step 4 of the diagram in the How This Policy Works section is skipped.  
Authentication request timeout | Sets the maximum time, in milliseconds, to wait for a response when authenticating with the Access Token validation endpoint.  
## How This Policy Works
The following diagram illustrates the OpenID Connect Access Token Enforcement policy workflow:
As shown in the diagram:
  1. The user first sends an HTTP request to the API protected by the policy.
  2. The policy extracts the token from the request and sends it to the validation endpoint to verify the integrity of the token.
  3. The token validation endpoint returns token metadata, including the client ID of the client application.
  4. Using a local database updated with contracts previously obtained from Anypoint Platform, the policy verifies whether the client ID has access to the API.
  5. If all the validations are successfully completed, the request is allowed to reach the backend.


### Leveraging Token Validation Endpoint Information
When a token validation endpoint successfully validates a token, certain information, such as configurable fields from OpenID Connect, are returned to the policy.
The following example illustrates the token validation response from the authorization server:
```
{
  "uid":"john.doe",
  "mail":"john.doe@example.com"
  "token_type":"Bearer",
  "exp": 1516239022
  "alias" : ["Jhon", "Jhonny", "Mr Doe"],
  "address" : {
    "city": "london",
    "road": “abbey road"
  }
}
```

The fields returned by the OAuth provider are processed by the policy, propagated throughout the flow, and finally exposed to the backend if the application requesting the access uses an HTTP requester.
### Token Caching in Local Mode
After the system validates a token, that token is cached (by default), until it expires, thereby improving the performance of the policy. In certain cases, such as in the case of revoked tokens, you might want to minimize or even disable caching.
The validation endpoint sends multiple properties to the policy, including the expiration time of the token. If the expiration information is not available, tokens are not cached.
To control the time taken to cache the tokens, before you attempt revalidating against the token validation endpoint, configure the following parameter in your declarative configuration file:
```
 - policyRef:
   name: openidconnect-access-token-enforcement-flex
  config:
   ...
   maxFederationExpirationTime: <expiration time in seconds>
```

Setting this property caches the token for the specified amount of time or until the tokens expire, whichever occurs first. If you have enabled this property and the validation endpoint does not send the expiration information, tokens are not cached.
To control the number of tokens that can be cached simultaneously, configure the following parameter in your declarative configuration file.
```
 - policyRef:
   name: openidconnect-access-token-enforcement-flex
  config:
   ...
   maxCacheSize: <amount of tokens to be cached; default value is 1.000; specify 0 to disable caching>
```

### Token Validation Endpoint Authentication
To complete validating the provided token, the policy sends a request to the validation endpoint. The policy then obtains the credentials from the client provider configuration in access management, per the Token Introspection Client section of the OAuth 2.0 Authorization Framework specification. These credentials are sent in the request body, as specified in the Client Authentication section of the OAuth 2.0 Authorization Framework specification.
Other authentication methods for the token validation endpoint are currently not supported.
## Configuring the Expose Headers Option
If you configured the `Expose Headers` option in the policy and if the application (for example, out-of-the-box proxies) uses the HTTP requester, the properties are redirected to the backend as headers.
For each field, the original request to the protected resource is enriched with the HTTP headers using the format: X-AGW- + <key>=<value>. For the example response from the previous section, the following headers are added:
```
X-AGW-uid=john.doe
X-AGW-mail=john.doe@example.com
X-AGW-token_type=Bearer
```
### Token Validation Endpoint Authentication
To complete validating the provided token, the policy sends a request to the validation endpoint. The policy then obtains the credentials from the client provider configuration in access management, per the Token Introspection Client section of the OAuth 2.0 Authorization Framework specification. These credentials are sent in the request body, as specified in the Client Authentication section of the OAuth 2.0 Authorization Framework specification.
Other authentication methods for the token validation endpoint are currently not supported.
## Configuring the Expose Headers Option
If you configured the `Expose Headers` option in the policy and if the application (for example, out-of-the-box proxies) uses the HTTP requester, the properties are redirected to the backend as headers.
For each field, the original request to the protected resource is enriched with the HTTP headers using the format: X-AGW- + <key>=<value>. For the example response from the previous section, the following headers are added:
```
X-AGW-uid=john.doe
X-AGW-mail=john.doe@example.com
X-AGW-token_type=Bearer
```

The propagated properties do not include the `scope`, and `exp` objects and arrays.
For further processing within the flow, the original unparsed response from the validation endpoint is made available. The information is stored in an authentication object.
For example, if a `mail` field is returned to the policy, you can access the value of the field by using the following DataWeave 2.0 expression:
`#[authentication.properties.userProperties.mail]`
You can obtain the client ID of the OAuth2 token by using the following DataWeave 2.0 expression:
`#[authentication.principal]`
## FAQs
**The OpenID Connect Access Token Enforcement policy does not appear in the list of policies to apply to the API.**
If the policy does not appear in the policies list, ensure that you have configured the OpenID client provider in Access Management. For information, see Configure OpenID Connect Client Management. If you are using multiple IdPs, verify that the OpenID connect client is properly configured in the API.
**Can I generate OAuth 2.0 tokens with the policy?**
No. The policy only validates the tokens.
**How are the OAuth tokens cached?**
OAuth 2.0 tokens are cached only in memory and are never written to disk.
**Can I configure the Rate-Limiting SLA policy after I configure the OpenID Connect Access Token Enforcement policy?**
Yes, you can. Apply the Rate-Limiting SLA policy after the OpenID Connect Access Token Enforcement policy and provide a `Client ID Expression` value using the following DataWeave 2.0 expression:
`#[authentication.principal]`
Because the identity of the requester is already validated by the OpenID Connect Access Token Enforcement policy, you can leave the `Client Secret Expression` field empty.