OAuth2 Provider Module 1.2 Reference | MuleSoft Documentation
# OAuth2 Provider Module 1.2 Reference
The OAuth2 Provider module allows a Mule runtime engine (Mule) app to be configured as an Authentication Manager in an OAuth2 dance. With this role, the application will be able to authenticate previously registered clients, grant tokens, validate tokens, or register and delete clients, all during the execution of a flow.
## Configurations
### Default Configuration
OAuth2 Provider module configuration
#### Parameters
Name | Type | Description | Default Value | Required  
---|---|---|---|---  
The name for this configuration. Connectors reference the configuration with this name.  
**Provider Name** |  The provider name supplied to customers of the API. This is used for some responses of the OAuth2 API.  
**Listener Config** |  The name of an HTTP Listener Config to reference, which handles the token and authorization endpoints.  
**Client Validation Rate Limiter** |  Period Rate Limiter |  The rate limiter used to control access to certain operations. If none is specified, PeriodRateLimiter is used as the default.  
**Client Store** |  Object Store |  A store that allows retrieving client configuration information, like their secret. If no client store is provided, a default in memory object store is configured.  
**Resource Owner Security Provider** |  The security provider used to authenticate resource owners. Not needed if only the CLIENT_CREDENTIALS grant type is used. Refer to an example with Spring module in migrating the OAuth2 provider documentation.  
**Client Security Provider** |  The security provider used to authenticate clients. Not needed if only public clients or private clients with secrets are used  
**Token Generator Strategy** |  TokenGeneratorStrategy |  The strategy used to generate access tokens. Should reference a class that implements TokenGeneratorStrategy.  
**Supported Grant Types** |  Enumeration, list of:
  * AUTHORIZATION_CODE
  * IMPLICIT
  * RESOURCE_OWNER_PASSWORD_CREDENTIALS
  * CLIENT_CREDENTIALS

|  The comma-separated grant types this provider supports. If none specified, only the authorization code grant type is supported. |  AUTHORIZATION_CODE  
A comma-separated list of supported scopes.  
**Default Scopes** |  A comma-separated list of the default scopes a client should have if none is defined.  
**Token Config** |  Token Configuration |  Information for configuring token related behavior.  
**Authorization Config** |  Authorization Config |  Information for configuring authorization handling behavior  
Array of Client |  A list of clients.  
**Expiration Policy** |  Expiration Policy |  Configures the minimum amount of time that a dynamic configuration instance can remain idle before Mule considers it eligible for expiration. This does not mean that the platform expires the instance at the exact moment that it becomes eligible. Mule purges the instances as appropriate.  
## Operations
  *   *   *   * Validate Token


### Create Client
`<oauth2-provider:create-client>`
Creates a new client and saves it in the configured client store.
```
<oauth2-provider:create-client
	doc:name="Create client"
	config-ref="OAuth2_Provider_Config"
	clientId="#[payload.clientId]"
	secret="#[payload.clientSecret]"
	clientName="#[payload.clientName]"
	description="#[payload.clientDescription]"
	principal="#[payload.clientPrincipal]"
	redirectUris="#[payload.redirectUris]"
	authorizedGrantTypes="#[payload.authorizedGrantTypes]"
	scopes="#[payload.scopes]"
	type="PUBLIC"
	failIfPresent="false"/>
```

#### Parameters
Name | Type | Description | Default Value | Required  
---|---|---|---|---  
**Configuration** |  The name of a globally defined OAuth Provider configuration to use for token validation.  
The ID to assign to the created client.  
Enumeration, one of:
  * CONFIDENTIAL
  * PUBLIC

|  The type of the client. Allowed values are PUBLIC: Clients incapable of maintaining the confidentiality of their credentials, or CONFIDENTIAL: Clients capable of maintaining the confidentiality of their credentials.  
**Client Name** |  A friendly name for the client.  
**Description** |  A brief description of the client.  
An optional principal to use when the ID can’t be used with the security provider.  
**Redirect Uris** |  Array of String |  An expression that resolves to a list of redirect URIs used for when the client makes requests to the OAuth Provider.  
**Authorized Grant Types** |  Array of Enumeration, one of:
  * AUTHORIZATION_CODE
  * REFRESH_TOKEN
  * TOKEN
  * PASSWORD
  * CLIENT_CREDENTIALS

|  An expression that resolves to a list of the authorized grant types that the client can use to request a token.  
Array of String |  An expression that resolves to a list of supported scopes by the client. If none are provided, the default scopes of the General Configuration are used.  
**Fail If Present** |  Defines what to do if a client with the same ID is already registered. If `true`, an error is raised. Otherwise, the client is updated.  
### For Configurations
Default Configuration
#### Throws
  * OAUTH2-PROVIDER:CLIENT_ALREADY_EXISTS - If a client already exists with the same client ID, and **Fail If Present** is set to `true`.
  * OAUTH2-PROVIDER:INVALID_CONFIGURATION - If the provided parameters are not valid, such as having **Authorized Grant Types** of AUTHORIZATION_CODE but without a redirect URI.


### Delete Client
`<oauth2-provider:delete-client>`
Deletes a client from the store.
#### Parameters
Name | Type | Description | Default Value | Required  
---|---|---|---|---  
**Configuration** |  The name of a globally defined OAuth Provider configuration to use for token validation.  
The ID of the client to be deleted.  
### For Configurations
Default Configuration
#### Throws
OAUTH2-PROVIDER:NO_SUCH_CLIENT - The client to be deleted does not exist.
### Revoke Token
`<oauth2-provider:revoke-token>`
Revokes an access token or refresh token, invalidating the related refresh token or access token as well. If client credentials need to be validated, use the validateClient credential before revoking the token.
#### Parameters
Name | Type | Description | Default Value | Required  
---|---|---|---|---  
**Configuration** |  The name of a globally defined OAuth Provider configuration to use for token validation.  
The token to revoke, it can be an access token or a refresh token.  
### For Configurations
Default Configuration
#### Throws
OAUTH2-PROVIDER:INVALID_TOKEN - The token to be revoked is not valid.
### Validate Token
`<oauth2-provider:validate-token>`
Checks that a valid access token is provided. Validates that the given token was granted and is in a valid state. Also, if defined, checks that the token scopes or resource owner roles match the provided ones.
If the provided token is valid, the operation sets the payload as a JSON with the following information:
  * expires_in:
Time remaining for the token to be considered invalid, in seconds.
  * scope:
Space separated scopes associated with the token.
  * client_id:
ID of the client that requested this token.
  * username:
Username of the resource owner that authorized this token to be requested.


To preserve the payload set before executing the operation, you can use the `target` and `targetValue` attributes to set the JSON information in a variable instead of overwriting the payload.
Validate Token parameters:
#### Parameters
Name | Type | Description | Default Value | Required  
---|---|---|---|---  
**Configuration** |  The name of the configuration to use.  
**Access Token** |  #[(attributes.headers['authorization'] splitBy ' ')[1]]  
Array of String |  An expression that resolves to a list of scopes to enforce when validating the token.  
**Resource Owner Roles** |  Array of String |  The resource owner roles to enforce when validating the token. This is an expression that resolves to a list of resource owner roles to enforce when validating the token.  
**Target Variable** |  The name of a variable to store the operation’s output.  
**Target Value** |  An expression to evaluate against the operation’s output and store the expression outcome in the target variable  
#### Output
### For Configurations
Default Configuration
#### Throws
OAUTH2-PROVIDER:TOKEN_UNAUTHORIZED - The token being validated is not valid.
## Types
### Token Configuration
Configuration related to token handling and the token endpoint.
Field | Type | Description | Default Value | Required  
---|---|---|---|---  
Endpoint to call when wanting to request a new token  
**Token Store** |  Object Store |  ObjectStore configuration information for storing token related data  
**Refresh Token Strategy** |  One of:
  * No Refresh Token
  * Single Refresh Token
  * Multiple Refresh Tokens

|  The refresh token strategy to use. By default no refresh token should be generated  
The time in seconds before an access token code expires.  
**Token Ttl Time Unit** |  Enumeration, one of:
  * NANOSECONDS
  * MICROSECONDS
  * MILLISECONDS
  * SECONDS
  * MINUTES
  * HOURS
|  The refresh token strategy to use. By default no refresh token should be generated  
The time in seconds before an access token code expires.  
**Token Ttl Time Unit** |  Enumeration, one of:
  * NANOSECONDS
  * MICROSECONDS
  * MILLISECONDS
  * SECONDS
  * MINUTES
  * HOURS

|  The time unit for the token ttl.  
### Authorization Config
Configuration related to authorization code handling and the authorization endpoint.
Field | Type | Description | Default Value | Required  
---|---|---|---|---  
**Login Page** |  Relative file path to the web page for the resource owner to provide its credentials. Keep in mind that if the default page is not used, you need to handle any external files referenced in the configured HTML. They are not handled by the OAuth provider. For example, if the login page HTML references an external `.css` style file, an endpoint that provides that file must exist. See HTTP Load Static Resource. |  www-static/auth.html  
The URL relative path to the authorization endpoint in the HTTP server for listening to authorization requests.  
**Authorization Code Store** |  Object Store |  A reference to a globally defined object store or a definition of a private object store. It’s used to store generated authorization codes. |  A persistent object store created from the ObjectStoreManager with an entry TTL of 600 SECONDS.  
### Client
All registered clients are authorized to request tokens. The list can be modified in runtime by the Create Client and Delete Client operations.
```
<oauth2-provider:clients>
  <oauth2-provider:client
		clientId="clientId1"
		clientName="someClient"
		secret="clientSecret1"
		principal="clusr"
		description="Some test client"
		type="CONFIDENTIAL">
    <oauth2-provider:client-redirect-uris>
      <oauth2-provider:client-redirect-uri
      	value="http://fake/redirect"/>
    </oauth2-provider:client-redirect-uris>
    <oauth2-provider:client-authorized-grant-types>
      <oauth2-provider:client-authorized-grant-type
      	value="AUTHORIZATION_CODE"/>
    </oauth2-provider:client-authorized-grant-types>
    <oauth2-provider:client-scopes>
      <oauth2-provider:client-scope value="USER"/>
    </oauth2-provider:client-scopes>
  </oauth2-provider:client>
</oauth2-provider:clients>
```

Each registered client has an entry with the following information:
Field | Type | Description | Default Value | Required  
---|---|---|---|---  
A unique ID that will used to reference the client  
An optional principal to use when the ID can’t be used with the security provider. For some security providers, the clientId can’t be used for the client username. In those cases, the client’s principal is used for authentication.  
**Client Name** |  The name of the client  
**Description** |  A short description for the client  
A client secret used to authenticate the client. Only required if **Type** is CONFIDENTIAL.  
**Client Redirect Uris** |  Array of String |  List of registered redirect URIs to use to respond to the client once the request is processed. Most requests allow the definition of new redirection URIs so these are not always taken into account. See also New Value Handling. `<oauth2-provider:client-scope value="USER"/>`  
**Client Authorized Grant Types** |  Array of Enumeration, one of:
  * AUTHORIZATION_CODE
  * REFRESH_TOKEN
  * TOKEN
  * PASSWORD
  * CLIENT_CREDENTIALS

|  The grant types that define which OAuth flows this client will be able to be successfully execute to get a token. See also New Value Handling.  
**Client Scopes** |  Array of String |  The scopes that will match this client. If a request is received with a matching client ID but with different scopes, it will not be processed. See also New Value Handling.  
Enumeration, one of:
  * CONFIDENTIAL
  * PUBLIC

|  The client type defines if the client is able to maintain confidentiality for its credentials. Allowed values are `PUBLIC`, where clients do not maintain the confidentiality of their credentials, or `CONFIDENTIAL`, where clients maintain the confidentiality of their credentials.  
For client redirect URIs, client authorized grant types, or client scopes, give each new value a new XML tag:
`<oauth2-provider:client-redirect-uri value="http://fake/redirect"/>`
`<oauth2-provider:client-authorized-grant-type value="AUTHORIZATION_CODE"/>`
### Expiration Policy
Field | Type | Description | Default Value | Required  
---|---|---|---|---  
**Max Idle Time** |  A scalar time value for the maximum amount of time a dynamic configuration instance should be allowed to be idle before it’s considered eligible for expiration  
Enumeration, one of:
  * NANOSECONDS
  * MICROSECONDS
  * MILLISECONDS
  * SECONDS
  * MINUTES
  * HOURS

|  A time unit that qualifies the maxIdleTime attribute  
### No Refresh Token
No refresh token is granted with every access token. As a consequence, when a refresh token request comes, it is always rejected.
Field | Type | Description | Default Value | Required  
---|---|---|---|---  
**Token Generator Strategy** |  TokenGeneratorStrategy  
### Single Refresh Token
For every new access token that is granted, a single refresh token is associated with it. That same refresh token can be used every time the access token is refreshed.
Field | Type | Description | Default Value | Required  
---|---|---|---|---  
**Object Store** |  Object Store |  A reference to a globally defined object store or a definition of a private object store for storing generated refresh tokens. The object store must be different from the access token object store. |  A persistent object store created from the ObjectStoreManager with an entry TTL of 86400 seconds.  
### Multiple Refresh Tokens
A new refresh token is generated every time a refresh token request is executed. After that, the previous refresh token is invalidated.
Field | Type | Description | Default Value | Required  
---|---|---|---|---  
**Object Store** |  Object Store |  A reference to a globally defined object store, or a definition of a private object store that stores the generated refresh tokens. The object store must be different from the access token object store. |  A persistent object store created from the ObjectStoreManager with an entry TTL of 86400 seconds.  
### Period Rate Limiter
Period Rate Limiter handles rate limiting based on a time period.
You can configure a mechanism to prevent the continuous client validation when it’s using invalid credentials.
Field | Type | Description | Default Value | Required  
---|---|---|---|---  
The time to wait before resetting the rate limiter. That means that during time intervals of _duration_ length, every time a client validation fails, it will be added to the failure count.  
**Duration Time Unit** |  Enumeration, one of:
  * NANOSECONDS
  * MICROSECONDS
  * MILLISECONDS
  * SECONDS
  * MINUTES
  * HOURS

  
**Maximum Failure Count** |  Maximum number of failures allowed within the period before preemptively rejecting requests.  
## OAuth Dance
Because the OAuth dance is done through HTTP, the OAuth2 Provider makes use of the Mule HTTP Connector.
As a consequence, apart from the definition of an OAuth2 provider configuration, the Mule application must also have an HTTP Listener configuration to be used by the provider.
Once configured, the provider works as follows:
Two HTTP endpoints are created for listening to Authentication Code and Token request as stated by the OAuth2 definition. Those work independently from the Mule application and respond via HTTP.
The provider defines an operation: Validate Token that can check if a token is authorized. That operation can be added anywhere in a flow to control its execution. If the token is indeed authorized, the flow continues executing, setting token information in the payload; otherwise, a `TOKEN_UNAUTHORIZED` error is raised. You need to add the operation to the parts of the application that require token authorization.
Since token validation is almost always used together with an HTTP Listener, in case it fails, the Listener’s response mechanism can handle the error and properly respond to the requester. Additional logic can be added for handling that type of error.
Lastly, additional operations are provided to add or delete clients and to revoke tokens if needed.
## Security Providers
As seen in the General Configuration, two security providers should be defined in the app to be later referenced by the OAuth2 Configuration element.
One way of doing this is using the Spring Framework, defining both security providers, and then using the Spring Module to add the providers to the Mule Security Manager:
```
<spring:security-manager>
  <spring:delegate-security-provider
  	name="clientSecurityProvider"
    delegate-ref="clientAuthenticationManager"/>
  <spring:delegate-security-provider
  	name="resourceOwnerSecurityProvider"
		delegate-ref="resourceOwnerAuthenticationManager"/>
</spring:security-manager>
```
## General Configuration
```
<oauth2-provider:config
	name="OAuth2Provider"
	listenerConfig="httpListenerConfig"
	resourceOwnerSecurityProvider="resourceOwnerSecurityProvider"
	clientSecurityProvider="clientSecurityProvider"
	supportedGrantTypes="AUTHORIZATION_CODE"
	scopes="USER,ADMIN"
	defaultScopes="USER"
	clientStore="clientObjectStore">
   <oauth2-provider:client-validation-rate-limiter>
    <oauth2-provider:period-rate-limiter
    	duration="600"
       durationTimeUnit="SECONDS"
       maximumFailureCount="5"/>
   </oauth2-provider:client-validation-rate-limiter>
   <oauth2-provider:token-config
   	path="/token"
		tokenStore="tokenObjectStore"
		tokenTtl="86400"
		tokenTtlTimeUnit="SECONDS">
    <oauth2-provider:refresh-token-strategy>
      <oauth2-single-refresh-token
      	objectStore="refreshTokenObjectStore"/>
    </oauth2-provider:refresh-token-strategy>
   </oauth2-provider:token-config>
   <oauth2-provider:authorization-config
   	loginPage="static/auth.html"
		path="/authorize"
		objectStore="authorizationCodeObjectStore"/>
   <oauth2-provider:clients>
     <oauth2-provider:client
     	clientId="clientId1"
			clientName="someClient"
			secret="clientSecret1"
			principal="clusr"
			description="Some test client"
			type="CONFIDENTIAL">
       <oauth2-provider:client-redirect-uris>
         <oauth2-provider:client-redirect-uri
         	value="http://fake/redirect"/>
       </oauth2-provider:client-redirect-uris>
       <oauth2-provider:client-authorized-grant-types>
         <oauth2-provider:client-authorized-grant-type
         	value="AUTHORIZATION_CODE"/>
       </oauth2-provider:client-authorized-grant-types>
       <oauth2-provider:client-scopes>
         <oauth2-provider:client-scope value="USER"/>
       </oauth2-provider:client-scopes>
     </oauth2-provider:client>
   </oauth2-provider:clients>
 </oauth2-provider:config>
```

## See Also
MuleSoft Help Center