<http:authentication >
<http:basic-authentication
username="UN" password="PW"/>
</http:authentication>
Authenticate HTTP Requests - Mule 4
Use the authentication that you configure in HTTP requests. You can use authentication when your Mule runtime (Mule) app uses the HTTP Connector to send requests to a service that requires authentication, such as the GitHub OAuth2 server described in OAuth2 - Authorization Code. In this case, your Mule app is the client. On the other hand, when you want to protect your API or app from receiving requests from unauthorized access, use an API Manager policy, such as the OAuth 2.0 Access Token Enforcement Using External Provider policy.
The HTTP request connector supports connecting a Mule client app to a service that requires any of the following types of authentication:
If the target HTTP service of your request requires that you authenticate, provide the necessary credentials in the global HTTP Request Configuration element. Mule uses the credentials you configure in the authorization header of the request.
You can also configure Transport Layer Security (TLS) to encrypt the OAuth credentials.
Even though Expression is displayed in the Authentication drop-down menu of the HTTP Global Element configuration in Anypoint Studio, it is not an authentication method and should not be used as such.
HTTP XML Authentication Setup
If you are using Anypoint Studio (Studio), you can use the Authentication field for the HTTP Request connector to select an authentication type.
The XML values for authentication in the HTTP connector are:
Authentication Type | XML Value |
---|---|
Basic Authentication |
|
NTLM Authentication |
|
Digest Authentication |
|
In addition, in Studio you can add an OAuth component’s operation to the canvas, which automatically adds the following dependency to the project’s pom.xml file:
<dependency>
<groupId>org.mule.modules</groupId>
<artifactId>mule-oauth-module</artifactId>
<version>1.1.8</version>
<classifier>mule-plugin</classifier>
</dependency>
Use of the OAuth component’s operations are discussed starting with Create the Mule Client App.
Basic Authentication
This example builds and runs an app in Studio that sends a request to the GitHub API for user information. The GitHub API accepts requests for user information on port 443 to https://api.github.com/user
.
To comply with the basic authentication requirements, the app provides the GitHub user name and password. You configure the HTTP Request Connector to provide these credentials.
This example requires that you have a GitHub account.
To call the GitHub API, first set up an HTTP Listener connector.
Basic Authentication - Studio Visual Editor
-
In Studio, create a new Mule project: File > New > Mule Project and set these parameters:
-
Project Name:
myproject
-
Runtime: Select or accept the default
Mule Server 4.1.x
or later.
-
-
In the Mule Palette, click HTTP, click the Listener operation, and drag the Listener operation to the canvas.
-
In the properties editor for the Listener, set the Path to
/
(forward slash). -
In Connector Configuration, click the green plus icon.
The HTTP Listener config dialog appears.
-
Click OK to accept the following options:
-
Name:
HTTP_Listener_config
-
Protocol:
HTTP
-
Host:
0.0.0.0
-
Port:
8081
-
-
Click OK.
-
In the properties editor, click the Advanced tab and set Allowed methods to
GET
. -
Save changes.
The error indicator disappears.
Basic Authentication - Configure an HTTP Request Connector
-
Drag an HTTP > Request operation from the Mule Palette to the Process area of the Studio flow.
-
In the properties editor for Connector Configuration, click the green plus icon.
The HTTP Request configuration dialog appears.
-
Set the following options:
-
Name:
HTTP_Request_configuration
. -
Protocol:
HTTPS
-
Host:
api.github.com
-
Port:
443
-
-
In the Authentication field, select the Basic authentication protocol.
-
In Username, type your GitHub user name.
-
In Password, type either your GitHub password or a personal access token.
-
Leave the Preemptive check box set to True (Default).
The preemptive option passes the user name and password without waiting for a prompt from the server.
-
Click OK.
-
In the properties editor, set the following options for the HTTP Request connector:
-
Method: Select GET from the drop-down.
-
Path:
/user
-
-
Save changes.
Basic Authentication - Format the Output in JSON
-
In the Mule Palette, search for "transform" and drag Core > Transform Message from the palette to the right of the Request component.
-
In the properties editor, change the output of the payload as follows:
%dw 2.0 output application/json --- payload
Basic Authentication - Run the App
-
Right-click the project name in Package Explorer, and choose Run as > Mule Application.
The console shows that the app is deployed.
-
Call the app using the following URL in a browser:
http://localhost:8081/
The GitHub API returns your user information.
{ "login":"kahn", "id":16xxx343, "avatar_url":"https://avatars.githubusercontent.com/u/16xxx343?v=3"` ... }
If the browser lists HTTP GET on resource 'https://api.github.com:443/user' failed: unauthorized (401)
, you need to use a personal access token instead of
specifying your GitHub password. If you are generating a new token, you only need the user > read:user scope.
Basic Authentication - XML Editor
<?xml version="1.0" encoding="UTF-8"?>
...
<http:listener-config name="HTTP_Listener_config"
doc:name="HTTP Listener config" >
<http:listener-connection
host="0.0.0.0"
port="8081" />
</http:listener-config>
<http:request-config name="HTTP_Request_configuration"
doc:name="HTTP Request configuration" >
<http:request-connection
protocol="HTTPS"
host="api.github.com"
port="443" >
<http:authentication >
<http:basic-authentication username="kahn" password="PW" />
</http:authentication>
</http:request-connection>
</http:request-config>
<flow name="myprojectFlow" >
<http:listener doc:name="Listener"
config-ref="HTTP_Listener_config"
path="/"
allowedMethods="GET"/>
<http:request method="GET" doc:name="Request"
config-ref="HTTP_Request_configuration"
path="/user" />
<ee:transform doc:name="Transform Message" >
<ee:message >
<ee:set-payload ><![CDATA[%dw 2.0
output application/json
---
payload
]]></ee:set-payload>
</ee:message>
</ee:transform>
</flow>
</mule>
NTLM Authentication
NT LAN Manager (NTLM) authentication replaces the authentication protocol in Microsoft LAN Manager (LANMAN), an older Microsoft product.
In this example, a GET request is sent to http://www.example.com/test
, adding an "Authorization" header with the provided username and password.
NTLM Authentication - Studio Visual Editor
-
Drag an HTTP > Request operation from the Mule Palette to the Process area of the Studio flow. This operation is known as the HTTP Request connector.
-
In the properties editor for Connector Configuration, click the green plus icon.
-
Select the Authentication tab.
-
In the Protocol dropdown menu, pick Ntlm authentication.
-
Provide your Username and Password (or references to properties that contain them), also optionally your Domain and Workstation.
NTLM Authentication - XML Editor
NTLM authentication is configured in the same way as Basic Authentication, just provide username and password in the attributes of the child element. The only difference is that the child element is differently named: "ntlm-authentication" and that you can optionally add domain and workstation attributes.
<http:request-config name="HTTP_Request_configuration"
doc:name="HTTP Request Configuration" >
<http:request-connection
host="example.com"
port="8081" >
<http:authentication >
<http:ntlm-authentication username="UN" password="PW" />
</http:authentication>
</http:request-connection>
</http:request-config>
<flow name="digest_flow">
...
<http:request method="GET" doc:name="Request"
config-ref="HTTP_Request_configuration"
path="test"
/>
</flow>
Digest Authentication
-
Drag an HTTP > Request operation from the Mule Palette to the Process area of the Studio flow. This operation is known as the HTTP Request connector.
-
In the properties editor for Connector Configuration, click the green plus icon.
-
Select the Authentication tab.
-
In the Protocol dropdown menu, pick Digest authentication.
-
Provide your Username and Password (or references to properties that contain them).
Digest Authentication - XML Editor
Digest authentication is configured in the same way as Basic Authentication, just provide your username and password in the attributes of the child element. The only difference is that the child element is differently named: "digest-authentication".
...
<http:request-config name="HTTP_Request_configuration"
doc:name="HTTP Request configuration" >
<http:request-connection host="example.com" port="8081" >
<http:authentication >
<http:digest-authentication
username="UN"
password="PW" />
</http:authentication>
</http:request-connection>
</http:request-config>
<flow name="digest_flow">
...
<http:request config-ref="HTTP_Request_configuration"
path="test"
method="GET" />
</flow>
In this example, a GET request is sent to http://www.example.com/test
, adding an "Authorization" header with the provided username and password.
OAuth2 - Authorization Code
The OAuth2 - Authorization Code configures the OAuth 2.0 authorization code grant type. The OAuth authentication server holds the resources that are protected by OAuth. For example, calls to the GitHub API can be authenticated through GitHub server using OAuth. The example in this section shows you how to create Mule client application to access a protected resource, GitHub user data, on the GitHub OAuth authentication server. The example covers the following things:
-
Set up authorization
-
Create a Mule client app
-
Run the Mule client app
This example requires that you have a GitHub account.
Set Up Authorization
-
Register the client application on the authentication server. The authentication server assigns a client ID and client secret to the Mule client app. The app uses these credentials later to identify itself to the authentication server. During the registration, you also provide the URL to the Mule app home page and the application callback URL.
-
Log in to GitHub.
-
Register the application in your GitHub personal settings. On the Register a new OAuth application page, fill in the following text boxes:
-
Application name: Type an arbitrary application name. For this example, use
oauth-grant-code
. -
Homepage URL: For this example, use
http://localhost:8082
. -
Authorization callback URL: For this example, use
http://localhost:8082/callback
. -
Click Register application.
GitHub creates a page for the registered application on
https://github.com/settings/applications/<app number>
that includes the GitHub-assigned client ID and client secret.
-
Create the Mule Client App
You can create a Mule client app that uses the GitHub assigned client ID and client secret to access the user data on the GitHub OAuth2 authentication server. The sample consists of an HTTP Listener connector, an HTTP Request connector, and a DataWeave (Transform) component for transforming plain text to JSON. In the HTTP Request connector, you configure access to the authentication server.
In the following procedure, you can configure a number of options, including:
-
Local authorization URL
Defines a URL in your application that listens for incoming requests.
-
Authorization URL
Provided by GitHub, this URL redirects the user request from the Mule client app to the Authorization URL of the GitHub authentication server.
-
Token URL
The Mule client app sends the token to the Token URL that you configure in the Mule client app.
The following sections help you configure the Mule client app for accessing the GitHub authentication server.
OAuth 2 Authorization - Studio Visual Editor
-
Drag an HTTP > Request operation from the Mule Palette to the Process area of the Studio flow. This operation is known as the HTTP Request connector.
-
Expand the Package Explorer and double-click the
pom.xml
file. -
At the end of the
<dependencies>
section and before the</dependencies>
statement, add these statements to enable OAuth options for the HTTP Request connector:<dependency> <groupId>org.mule.modules</groupId> <artifactId>mule-oauth-module</artifactId> <version>1.1.8</version> <classifier>mule-plugin</classifier> </dependency>
-
In the properties editor for Connector Configuration, click the green plus icon (or click the Edit icon if you have already created a configuration).
-
Set the Authentication field to Authorization code grant type.
-
Set the following required fields:
-
External callback url:
http://myapp.mycompany.com:8082/callback
The OAuth authentication server uses this URL to provide the authentication code to the Mule server so that the Mule server can retrieve the access token. This must be the externally visible address of the callback, not the local one.
-
Local authorization url:
https://localhost:8082/login
Lets you authenticate and grant access to the app for your account.
-
Authorization url:
https://github.com/login/oauth/authorize
Authorize the app for a user.
-
Client id: Type the client ID that GitHub provided when you registered the app.
-
Client secret: Type the client secret that GitHub provided when you registered the app.
-
Token url:
https://github.com/login/oauth/access_token
You can also set these optional fields:
-
Local callback url:
http://localhost:8082/callback
This value matches the value you configured for External callback URL when registering the app in GitHub. This is the configuration of the server that Mule creates to receive the requests that a remote host sends to the
externalCallbackUrl
. External and internal callback URLs are the same, just that one is the configuration to create a server in the runtime (internal) and the other is how that server is seen from the internet (external). -
Response Access Token:
#[payload.access_token]
This DataWeave expression extracts an access token.
-
Response Refresh Token:
#[payload.access_token]
You can use a similar DataWeave expression for the refresh token (that is:
#[payload.refresh_token]
) if the provider you are using sends a refresh token. In this example, however, GitHub doesn’t actually use a refresh token.
-
-
Click OK.
-
Save changes.
OAuth 2 Authorization - XML Editor
Within the global configuration of the connector, add an <http:authentication
> block
containing an oauth:authorization-code-grant-type
child element.
Include the following values in it:
-
The
clientId
andclientSecret
.Use the client ID and client secret you received from GitHub when registering your application.
-
The
localCallbackUrl
to which the GitHub authentication server sends the access token once the resource owner (RO) grants you access.
If you were required to provide a redirect URL when registering your application with GitHub, this value must match what you provided there.
Add the following attributes:
-
The
authorizationUrl
that the GitHub authentication server exposes -
The
localauthorizationUrl
Also, add the following attribute:
-
The
tokenUrl
that the GitHub authentication server exposes
<http:listener-config name="HTTP_Listener_Configuration"
host="0.0.0.0" port="8081" basePath="/github"/>
<http:request-config name="HTTP_Request_Configuration"
protocol="HTTPS" host="api.github.com" port="443">
<http:authentication>
<oauth:authorization-code-grant-type
externalCallbackUrl="http://myapp.mycompany.com:8082/callback"
localAuthorizationUrl="http://localhost:8082/login"
authorizationUrl="https://github.com/login/oauth/authorize"
clientId="CLIENT_ID"
clientSecret="CLIENT_SECRET"
tokenUrl="https://github.com/login/oauth/access_token" />
</http:authentication>
</http:request-config>
The localAuthorizationUrl value matches the value you configured for External callback URL when registering the app in GitHub. This is the configuration of the server that Mule creates to receive the requests that a remote host sends to the externalCallbackUrl . External and internal callback URLs are the same, just that one is the configuration to create a server in the runtime (internal) and the other is how that server is seen from the internet (external).
|
OAuth 2 Authorization - Run the Mule Client App
After deploying the Mule client app, you follow the procedure in this section to run the app. The procedure covers the following actions:
-
Submitting an HTTP request for GitHub access to the Mule client app (#1 in the following diagram).
The client app redirects the request to the GitHub authentication server (#2 in the diagram). GitHub prompts you to login and authorize the client app you registered.
-
Using your GitHub login account credentials to log in and authorize the application (#3-4 in the diagram).
In response, the GitHub authentication server returns an access token (#5 in the diagram).
-
Requesting the secured user data using the access token (#1-2 in the following diagram).
The client app gets the user data from the GitHub authentication server (#3 in the diagram).
To run the Mule client app to get GitHub user data:
Perform these steps before the access token expires:
-
Right-click the project name in project explorer, and choose Run as > Mule Application.
The console shows that the app is deployed.
-
In a browser, enter the local authorization URL
http://localhost:8082/login
to initiate the OAuth2 dance.GitHub prompts you to log in.
-
Log in using your GitHub user name and password.
GitHub prompts you to authorize the application you registered to run.
-
Click Authorize application.
Successfully retrieved access token
appears as body text in the browser you used to initiate the OAuth2 dance.To return the token to get data, enter the following URL in a browser:
http://localhost:8081/github
The GitHub API returns your user information.
{ "login":"kahn", "id":16xxx343,"avatar_url":"https://avatars.githubusercontent.com/u/16xxx343?v=3"` ... }
OAuth 2 Authorization - Using Scopes
Configuring the Scopes attribute in the Mule client app is optional, and not needed for the GitHub example. To configure scopes, define a comma-separated list of OAuth scopes available in the authentication server. Scopes in OAuth are like security roles.
Send OAuth2 Custom Parameters to the Authorization URL
There are OAuth implementations that require or allow extra query parameters to be sent when calling the Authentication URL of the OAS.
OAuth 2 Custom Parameters - Studio Visual Editor
-
In Studio, select the HTTP Request Configuration global element where you want to use the OAuth authorization code grant type.
-
In Authentication, select Authorization code grant type. If this option is not visible, set the pom.xml file for OAuth options.
-
Fill in the same fields as in the previous example:
-
External Callback URL =
http://myapp.mycompany.com:8082/callback
-
Local Authorization URL =
http://localhost:8082/login
-
AuthorizationUrl =
https://github.com/login/oauth/authorize
-
client ID = Get the Client ID from your GitHub account
-
client Secret = Get the Client Secret from your GitHub account
-
Token URL =
https://github.com/login/oauth/access_token
The Local Authorization URL
value matches the value you configured forExternal callback URL
when registering the app in GitHub. This is the configuration of the server that Mule creates to receive the requests that a remote host sends to theexternalCallbackUrl
. External and internal callback URLs are the same, just that one is the configuration to create a server in the runtime (internal) and the other is how that server is seen from the internet (external).
-
-
On
Custom Parameters
selectEdit inline
. Click the Plus (+) button as many times as you need and define a name and value for each custom parameter.
OAuth 2 Custom Parameters - XML Editor
This example includes two oauth:custom-parameter
child elements that define parameters that are specific to this API.
<http:request-config name="HTTP_Request_Configuration"
host="api.box.com" port="443" basePath="/2.0">
<http:authentication>
<oauth:authorization-code-grant-type
externalCallbackUrl="http://myapp.mycompany.com:8082/callback"
localAuthorizationUrl="http://localhost:8082/login"
authorizationUrl="https://github.com/login/oauth/authorize"
clientId="CLIENT_ID"
clientSecret="CLIENT_SECRET"
tokenUrl="https://github.com/login/oauth/access_token" />
<oauth:custom-parameters>
<oauth:custom-parameter
key="box_device_id" value="123142"/>
<oauth:custom-parameter
key="box_device_name" value="my-phone"/>
</oauth:custom-parameters>
</http:authentication>
</http:request-config>
Override the Redirect URI
This section lets you override the redirect URI (external redirect_uri
).
The OAuth 2.0 specification describes checking the redirect URI from the destination site of the redirect. The OAuth authentication server uses the URL to provide the authentication code to the Mule server for retrieving the access token. If you provide this URL, Mule creates an endpoint at the URL for storing the authentication code unless there’s already an endpoint registered to manually extract the authorization code.
You configure the external redirect URI by setting the External Callback URL attribute (externalCallbackUrl
in XML).
Using externalCallbackUrl
is particularly useful for deploying applications to CloudHub, for example. When configuring authentication, you can optionally specify the localCallbackUrl
attribute as well.
For example, the localCallbackUrl
is http://localhost:8082/callback
in the previous example:
To create the endpoint for CloudHub, Mule has to create an endpoint for CloudHub in a different format. For example:
https://<app>.cloudhub.io/<redirect Uri>
To instruct Mule to create the endpoint for CloudHub in the correct format, include the externalCallbackUrl
attribute in your oauth:authorization-code-grant-type
configuration.
Extract Parameters from the Token URL Response
After you have obtained an authorization code from the authentication server, the OAuth dance makes a request to the Token URL of the server to receive an access token.
The format of the response to the request to the token URL is not defined in the OAuth spec. Each implementation may therefore return different response formats. By default, Mule expects the response to be in JSON format. When this is the case, HTTP Request knows how to extract the required information, as long as its elements are named as below:
-
Response access token: The JSON field is named
access_token
-
Response refresh token: The JSON field is named
refresh_token
-
Response expires in: The JSON field is named
expires_in
When the response is in JSON format, the parameters are automatically extracted and you can use DataWeave expressions to reference these values in the response to the request to the token URL, as shown in the previous GitHub example.
When the response is not in JSON format, then you must first configure the connector so that it knows how to extract these values. In the following example, the connector expects the response to have a Content-Type
of application/x-www-form-urlencoded
, so the body of the response is transformed into a Map in the payload. You extract the values from the map through DataWeave expressions, such as #[payload.access_token]
(the default value for the Response access token and Response refresh token).
Extract Parameters - Studio Visual Editor
On the Authentication tab, verify these default options for the OAuth2 - Authorization Code:
-
Response Access Token:
#[payload.access_token]
-
Response Refresh Token:
#[payload.refresh_token]
-
Response Expires In:
#[payload.expires_in]
Extract Parameters - XML Editor
This example includes two oauth:custom-parameter
child elements that define parameters specific to this API.
<http:request-config name="HTTP_Request_Configuration"
host="api.box.com" port="443" basePath="/2.0">
<http:authentication>
<oauth:authorization-code-grant-type
localCallbackUrl="http://localhost:8082/redirectUrl"
externalCallbackUrl="http://myapp.mycompany.com:8082/callback"
localAuthorizationUrl="http://localhost:8082/authorization"
authorizationUrl="http://www.box.com/api/oauth2/authorize"
clientId="your_client_id"
clientSecret="your_client_secret"
tokenUrl="http://www.box.com/api/oauth2/token"
responseAccessToken="#[payload.access_token]"
responseRefreshToken="#[payload.refresh_token]"
responseExpiresIn="#[payload.expires_in]" />
</http:authentication>
</http:request-config>
Refresh Access Token Customization
The access token you obtain from the token URL eventually expires. The length of time the token is valid depends on the authentication server implementation. After the access token expires, instead of going through the whole process once again, you can retrieve a new access token by using the refresh access token provided by the token URL response.
Mule handles this use case automatically. So by default, when an HTTP Request is executed, if the response has a status code of 403, Mule calls the token URL and gets a new access token.
You can customize when Mule performs one of these requests to obtain a new access token using a DataWeave expression. The expression is evaluated against the response of the HTTP Request call.
Refresh - Studio Visual Editor
In Authentication > Authorization code grant type, configure Request Token When to Expression and the field next to it with the following DataWeave expression:
#[payload.response.status == 'unauthorized']
Refresh - XML Editor
To set when to perform a call to obtain a new access token, set a DataWeave expression for the attribute refreshTokenWhen
in the oauth:authorization-code-grant-type
element.
<http:request-config name="HTTP_Request_Configuration"
host="api.box.com" port="443" basePath="/2.0">
<http:authentication>
<oauth:authorization-code-grant-type
localCallbackUrl="http://localhost:8082/redirectUrl"
externalCallbackUrl="http://myapp.mycompany.com:8082/callback"
localAuthorizationUrl="http://localhost:8082/authorization"
authorizationUrl="http://www.box.com/api/oauth2/authorize"
clientId="your_client_id"
clientSecret="your_client_secret"
tokenUrl="http://www.box.com/api/oauth2/token"
refreshTokenWhen="#[payload.response.status == 'unauthorized']" />
</http:authentication>
</http:request-config>
When a request authorization fails, the response contains an XML node named status with value ‘unauthorized’
. In the previous example, the DataWeave expression evaluates that condition. When it evaluates to true, Mule sends a request to the Token URL to retrieve a new access token.
Use HTTPS for OAuth Authorization Code
When you need to use HTTPS for the communication with the authentication server, such as in a production environment, apply HTTPS encoding to the OAuth credentials in all requests, including those for the:
-
Local authorization URL
-
Authorization URL
-
Redirect URL
-
Token URL
By specifying a TLS context in your HTTP Request Connector authentication settings, this is handled in all of these requests.
HTTPS - Studio Visual Editor
-
In the TLS Configuration field, select Global Reference.
-
Click the green plus sign next to the field to create a new TLS Context.
-
Set up the trust store and key store configuration and click OK to save.
The TLS Configuration field encode your OAuth credentials.
HTTPS - XML Editor
Set tlsContext
to reference a TLS context element, provide your trust store and key store credentials in this element.
<http:request-config name="HTTP_Request_Configuration_HTTPS"
host="api.box.com" port="443" basePath="/2.0"
tlsContext-ref="TLS_Context" protocol="HTTPS">
<http:authentication>
<oauth:authorization-code-grant-type
localCallbackUrl="http://localhost:8082/redirectUrl"
externalCallbackUrl="http://myapp.mycompany.com:8082/callback"
localAuthorizationUrl="https://localhost:8082/authorization"
authorizationUrl="https://www.box.com/api/oauth2/authorize"
clientId="your_client_id"
clientSecret="your_client_secret"
tokenUrl="https://www.box.com/api/oauth2/token"
tlsContextFactory="TLS_Context"
scopes="access_user_details, read_user_files" />
</http:authentication>
</http:request-config>
<tls:context name="TLS_Context">
<tls:trust-store path="your_trust_store"
password="your_password"/>
<tls:key-store path="your_keystore_path"
password="your_password" keyPassword="your_key_password"/>
</tls:context>
The tlsContextFactory
attribute in the oauth:authorization-code-grant-type
element points
to the <tls:context
element where you encode your OAuth credentials.
OAuth2 - Client Credentials
In the OAuth authentication, the Client Credentials tab lets you configure the client credentials grant type.
The OAuth authentication server (OAS) is a server that holds the resources that are protected by OAuth. For example, the Box server provides an API with OAuth authentication.
The client application (CA) is the server that tries to access a protected resource that belongs to a resource owner and that is held in an OAuth authentication server. For example, a Mule Server trying to access the resources that belong to a Box user and that are held in a Box server.
In this case, the resource owner (RO) is also the CA. This means that the CA is implicitly authorized by the RO, which makes the whole procedure a lot simpler.
To access protected resources:
-
The CA must register an app to the OAS server. When this happens, the OAS assigns credentials to the CA that it can later use to identify itself:
client ID
andclient secret
. The OAS must also provide aToken URL
, to which the CA can later send HTTP requests to retrieve anaccess token
that is required when accessing the Protected Resources. -
The CA makes a request to the
Token URL
of the OAS, containing its client ID to prove its identity. As a response, the OAS grants it anaccess token
. -
With this access token, the CA is now free to access the protected resources in the OAS as long as it includes it in its requests. Depending on the policies defined by the OAS, this token may eventually expire.
OAuth2 - Configuration
Client credentials grant type is meant to be used by a CA to grant access to an application on behalf of itself, rather than on behalf of a RO (resource owner) in the OAS. To get an access token all you need is the application credentials.
OAuth2 - Studio Visual Editor
-
In Studio, select the HTTP Request Configuration global element where you want to use the OAuth client credentials grant type.
-
In Authentication, select Client credentials grant type.
-
Fill in the following fields:
-
For Client Id and Client Secret, use the values that the OAS provided you when you registered your application.
-
The Scopes field is optional, it allows you to define a comma-separated list of OAuth scopes available in the OAS. Scopes in OAuth are very much like security roles.
-
The Token URL that the OAS exposes
-
OAuth2 - XML Editor
You must include the following information:
-
The
clientId
andclientSecret
the OAS gave you when registering your application. -
The
scopes
attribute is optional, it allows you to define a comma-separated list of OAuth scopes available in the OAS. Scopes in OAuth are very much like security roles. -
The
tokenUrl
that the OAS exposes
<http:request-config name="HTTP_Request_configuration" >
<http:request-connection host="some.api.com" port="80" >
<http:authentication>
<oauth:client-credentials-grant-type
clientId="your_client_id"
clientSecret="your_client_secret"
tokenUrl="http://some.api.com/api/1.0/oauth/token"
scopes="access_user_details, read_user_files" />
</http:authentication>
</http:request-connection>
</http:request-config>
When the Mule application deploys, it tries to retrieve an access token. If the app is not able to retrieve an access token, it fails in the deployment.
Token Manager Configuration
To access authorization information for client credentials and authorization codes, use a token manager configuration.
Token Manager Configuration - Studio Visual Editor
-
In Studio, select the HTTP Request Configuration global element where you want to use the OAuth authorization code grant type.
-
In Authentication, select Client credentials grant type.
-
In the Advanced section of the form, set Token Manager to Global Reference, and click the green plus sign next to Token Manager to create a new token manager.
-
Assign the token manager as a reference to an object store.
Token Manager Configuration - XML Editor
The tokenManager-ref attribute need to reference a token-manager-config element in the configuration.
<oauth:token-manager-config name="Token_Manager_Config"/>
<http:request-config name="HTTP_Request_Configuration"
host="api.box.com" port="443" basePath="/2.0">
<http:authentication>
<oauth:authorization-code-grant-type
clientId="your_client_id"
clientSecret="your_client_secret"
localCallbackUrl="http://localhost:8082/redirectUrl"
tokenManager-ref="Token_Manager_Config"
localAuthorizationUrlResourceOwnerId="#[attributes.queryParams.userId]"
resourceOwnerId="#[vars.userId]"
authorizationUrl="https://www.box.com/api/oauth2/authorize"
localAuthorizationUrl="https://localhost:8082/authorization"
scopes="access_user_details, read_user_files"
tokenUrl="https://www.box.com/api/oauth2/token" />
</http:authentication>
</http:request-config>
Token Manager - Access Authorization
After you have a token manager associated with the authorization grant type (in the example below, with authorization code) you can use the operations provided by the OAuth module anywhere in the flow to access information from an OAuth authorization.
If you’re using client credentials or authorization code with a single RO, use the following operations in a flow:
<oauth:retrieve-access-token
tokenManager="tokenManagerConfig"/>
<oauth:retrieve-refresh-token
tokenManager="tokenManagerConfig"/>
<oauth:retrieve-expires-in
tokenManager="tokenManagerConfig"/>
<oauth:retrieve-state
tokenManager="tokenManagerConfig"/>
<oauth:retrieve-custom-token-response-param
tokenManager="tokenManagerConfig"
key="#[vars.key]"/>
This operations provide access to the OAuth authorization information from a token manager.
-
tokenManager
: Name of a token manager in the configuration
If you’re using authorization code with multiple RO, use the following operations:
<oauth:retrieve-access-token
tokenManager="tokenManagerConfig"
resourceOwnerId="#[vars.resourceOwnerId]"/>
<oauth:retrieve-refresh-token
tokenManager="tokenManagerConfig"
resourceOwnerId="#[vars.resourceOwnerId]"/>
<oauth:retrieve-expires-in
tokenManager="tokenManagerConfig"
resourceOwnerId="#[vars.resourceOwnerId]"/>
<oauth:retrieve-state
tokenManager="tokenManagerConfig"
resourceOwnerId="#[vars.resourceOwnerId]"/>
<oauth:retrieve-custom-token-response-param
tokenManager="tokenManagerConfig"
resourceOwnerId="#[vars.resourceOwnerId]"
key="#[vars.key]"/>
This operations provide access to OAuth authorization information from a token manager.
-
tokenManager
: Name of a token manager in the configuration. -
resourceOwnerId
: Identifier of a RO.
Token Manager - Examples
This table includes examples of how to retrieve information from a Token Manager. Use these operations in your flow that you place after the HTTP Request Connector that handles your OAuth authentication.
Function | Result |
---|---|
|
|
|
|
|
|
|
Expires in value accessible through |
|
State used for the authorization URL accessible through |
|
Custom parameter extracted from the token URL response accessible through |
|
Custom parameter extracted from the token URL response for resource owner |
Token Manager - Access Token Invalidation
When using a Token Manager, you can block a particular resource owner.
Token Manager - Studio Visual Editor
-
Drag an OAuth component’s Invalidate OAuth Context operation to your canvas.
-
In its properties editor, set up the Token Manager Configuration so that it points to the same Token Manager that your HTTP Request Connector references when handling OAuth authentication.
-
Set the Resource Owner Id to an expression that points to the RO you want to clear. For example
#[vars.resourceOwnerId]
Token Manager - XML Editor
<flow name="invalidateOauthContext">
<oauth:invalidate-oauth-context
tokenManager="tokenManagerConfig"/>
</flow>
The OAuth component’s *Invalidate OAuth Context operation cleans up all of the OAuth information stored in the token manager.
When using multiple RO with a single Token Manager, if you want to only clear the OAuth information of one RO, then you must specify the resource owner ID in the Invalidate OAuth Context element.
<flow name="invalidateOauthContextWithResourceOwnerId">
<oauth:invalidate-oauth-context
tokenManager="tokenManagerConfig"
resourceOwnerId="#[vars.resourceOwnerId]"/>
</flow>
Token Manager - Customize the Token Manager Object Store
By default, the token manager uses an in-memory object store to store the credentials. You can customize the token manager object store by using the objectStore
attribute. See also Configure a custom object store.