Contact Free trial Login

OAuth2 Provider Module Reference - Mule 4

Support Category: Select

OAuth2 Provider Module v1.0

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.

The following documentation assumes a basic knowledge of the OAuth2 authorization protocol. If you are not familiar with this protocol, see RFC-6749.

If the app behaves as the client in the OAuth2 dance, use the OAuth Module instead.

POM File Information

<dependency>
<groupId>com.mulesoft.modules</groupId>
<artifactId>mule-oauth2-provider-module</artifactId>
<version>RELEASE</version>
<classifier>mule-plugin</classifier>
</dependency>

Mule converts RELEASE to the latest version. To specify a version, view OAuth Provider Module in Anypoint Exchange and click Dependency Snippets.

Configurations


Default Configuration

OAuth2 Provider module configuration

Parameters

Name Type Description Default Value Required

Name

String

The name for this configuration. Connectors reference the configuration with this name.

x

Provider Name

String

The provider name supplied to customers of the API. This is used for some responses of the OAuth2 API.

Listener Config

String

The name of an HTTP Listener Config to reference, which handles the token and authorization endpoints.

x

Client Validation 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

String

The security provider used to authenticate resource owners. Not needed if only the CLIENT_CREDENTIALS grant type is used.

Client Security Provider

String

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

String

The comma-separated grant types this provider will support. If none specified, only the authorization code grant type will be supported.

AUTHORIZATION_CODE

Scopes

String

A comma-separated list of supported scopes.

Default Scopes

String

A comma-separated list of the default scopes a client should have if none is defined.

Token Config

Information for configuring token related behavior.

Authorization Config

Information for configuring authorization handling behavior

Clients

Array of Client

A list of clients.

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

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

String

The name of a globally defined OAuth Provider configuration to use for token validation.

x

Client Id

String

The ID to assign to the created client.

x

Type

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.

PUBLIC

Secret

String

Client Name

String

A friendly name for the client.

Description

String

A brief description of the client.

Principal

String

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.

Scopes

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

Boolean

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.

false

For Configurations

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

String

The name of a globally defined OAuth Provider configuration to use for token validation.

x

Client Id

String

The ID of the client to be deleted.

x

For Configurations

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

String

The name of a globally defined OAuth Provider configuration to use for token validation.

x

Token

String

The token to revoke, it can be an access token or a refresh token.

x

For Configurations

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

String

The name of the configuration to use.

x

Access Token

String

#[(attributes.headers['authorization'] splitBy ' ')[1]]

Scopes

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

String

The name of a variable to store the operation’s output.

Target Value

String

An expression to evaluate against the operation’s output and store the expression outcome in the target variable

#[payload]

Output

Type

String

For Configurations

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

Path

String

Endpoint to call when wanting to request a new token

/token

Token Store

Object Store

ObjectStore configuration information for storing token related data

Refresh Token Strategy

The refresh token strategy to use. By default no refresh token should be generated

Token Ttl

Number

The time in seconds before an access token code expires.

86400

Token Ttl Time Unit

Enumeration, one of:

  • NANOSECONDS

  • MICROSECONDS

  • MILLISECONDS

  • SECONDS

  • MINUTES

  • HOURS

  • DAYS

The time unit for the token ttl.

SECONDS

Authorization Config

Configuration related to authorization code handling and the authorization endpoint.

Field Type Description Default Value Required

Login Page

String

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

Path

String

The URL relative path to the authorization endpoint in the HTTP server for listening to authorization requests.

/authorize

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

Client Id

String

A unique ID that will used to reference the client

x

Principal

String

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

String

The name of the client

Description

String

A short description for the client

Secret

String

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.

Type

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.

PUBLIC

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

Number

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

Time Unit

Enumeration, one of:

  • NANOSECONDS

  • MICROSECONDS

  • MILLISECONDS

  • SECONDS

  • MINUTES

  • HOURS

  • DAYS

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.

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.

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

Duration

Number

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.

600

Duration Time Unit

Enumeration, one of:

  • NANOSECONDS

  • MICROSECONDS

  • MILLISECONDS

  • SECONDS

  • MINUTES

  • HOURS

  • DAYS

SECONDS

Maximum Failure Count

Number

Maximum number of failures allowed within the period before preemptively rejecting requests.

5

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>