当前位置:首页 >> 计算机软件及应用 >> Studio+Update+Sites-16(Securing)

Studio+Update+Sites-16(Securing)


Securing
? ? ?
Anypoint Enterprise Security Configuring Security FIPS 140-2 Compliance Support

Anypoint Enterprise Security
Enterprise Edition, CloudHub Version 1.2 Anypoint Enterprise Security is a collection of security features that enforce secure access to information in Mule applications. This suite of security features provides various methods for applying security to Mule Service-Oriented Architecture (SOA) implementations and Web services. The following security features bridge gaps between trust boundaries in applications:

? ? ? ? ? ?

Mule Secure Token Service (STS) OAuth 2.0a Provider Mule Credentials Vault Mule Message Encryption Processor Mule Digital Signature Processor Mule Filter Processor Mule CRC32 Processor Install the Anypoint Enterprise Security update on your instance of Anypoint Studio Enterprise Edition 3.3.2 or later. Contents

Why Do Applications Need Security?
Businesses must ensure that the valuable information they store and make available through software applications and Web services is secure. Locked away and protected from unauthorized users and malicious attackers, protected resources — such as credit card information or Social Security numbers — must still be accessible to authorized legitimate users and systems in order to conduct business transactions. To provide secure access to information, applications and services can apply a variety of security measures. The suite of security features in Anypoint Enterprise Security enables developers to protect

applications according to security requirements, prevent security breaches and facilitate authorized access to data.

Advantages of Anypoint Enterprise Security
Anypoint Enterprise Security adds new features on top of of Mule ESB Enterprise’s existing security capabilities. Mule ESB already provides the following security features:

?

Mule Security Manager, client authentication and authorization on inbound requests as well as credential mapping for outbound calls

? ? ?

LDAP and third party identity management system integration Validation of inbound requests through the SAML 2.0 federated identity standard Secure FTP (SFTP) Transport that enables Mule flows to read and write to remote directories over the SSH protocol. In most cases the above features were accessible only to expert Mule developers who are very familiar with the Spring Security framework. Anypoint Enterprise Security expands the types of security available to apply to Mule applications and, through its accessibility in Studio, makes security features accessible to a broader range of skilled developers. Compiled to form an easily-accessible, user-friendly collection, Anypoint Enterprise Security offers developers a clear, structured method for adding security to Mule ESB applications. Developers can easily drag-and-drop one or more security features into Mule flows in Studio, Mule ESB’s graphical user interface (GUI), and can find configuration support in Mule documentation.

Features Summary
Anypoint Enterprise Security offers developers six tools to ensure that authorized end users have secure access to protected data. Each tool plays a different role in securing a Mule application.

Mule Secure Token Service (STS) OAuth 2.0a Provider
Mule can apply OAuth 2.0a security to a REST Web service provider or consumer. OAuth uses tokens to ensure that a resource owner never has to share credentials, such as a username or password, with a 3rd-party Web service. For example, Facebook uses OAuth to connect to Gmail to collect a user’s Gmail contacts. When a u ser initiates the request to connect, Facebook opens a new browser window for the user to enter a Gmail address and password. If authenticated, Gmail provides all the user’s contacts to Facebook, but does not share the user’s Gmail login credentials. OAuth ensures that the 3rd-party Facebook application never has access to the user’s protected Gmail credentials.

Apply OAuth 2.0a to my Mule Web service provider Apply OAuth 2.0a to my Mule Web service consumer

Mule Credentials Vault
Mule can encrypt properties in a .properties file. The .properties file in Mule stores data as key-value pairs. Mule flows may access this data — usernames, first and last names, credit card information — as the flow processes messages. In the context of Anypoint Enterprise Security, Mule refers to the .properties file in which it safely stores encrypted properties as the Mule Credentials Vault. Encrypt a properties file

Mule Message Encryption Processor
Mule can encrypt an entire payload or several fields of data within a message. Where sensitive information must move between users, yet remain hidden from them, a developer can encrypt message content to prevent unauthorized access. Typically, you may need to encrypt data such as a password, credit card number or social security number (SSN). Encrypt a message payload Decrypt a message payload

Mule Digital Signature Processor
Mule uses digital signatures to ensure that messages maintain integrity and authenticity. Mule can verify that an incoming Web service request originates from a valid source, and can sign an outgoing Web service response to ensure its contents. Digital signatures ensure that a sender is valid, that a message is not modified in transit between Web services, and that no unauthorized user has tampered with a message. Add a digital signature to a message in Mule Sign part of a message payload Verify a digital signature in Mule

Mule Filter Processor
Mule can filter messages it receives to avoid processing invalid ones. With a filter processor in place, Mule discards any message it receives that does not match the filter’s parameters — a message from outside a set range of IP addresses, for example. Filter unsecure messages

Mule CRC32 Processor
Mule can apply a cyclic redundancy check (CRC) to messages to ensure message integrity. CRC uses an algorithm to apply a check value to a message when it enters a system, and verifies the value when the message leaves the system. If the entry and exit values do not match, CRC marks the message as changed. Generally, CRC32 (32 indicates the 33-bit polynomial length in the algorithm) detects unintentional changes to messages, such as the accumulation of ―noise‖ between transmission points, but it can also detect unauthorized intentional changes – for instance, flagging a message that has been tampered with during transmission to change it into a Trojan horse. Apply a CRC to a message

Go Further
1. Install the Anypoint Enterprise Security update on your instance of Anypoint Studio or Standalone Enterprise 3.3.2 or later. 2. pages. 3. action: Explore two example applications that demonstrate Anypoint Enterprise Security features in Examine the details of above-listed features; use menu in left-nav bar to access feature-specific

? ? ?
Anypoint Enterprise Security Example Application Mule STS OAuth 2.0a Example Application

Installing Anypoint Enterprise Security
Enterprise Edition, CloudHub

? ?

STUDIO

MULE

Requirements
?

Anypoint Enterprise Security requires an Enterprise license. Contact MuleSoft Support to acquire a license.

?

Anypoint Enterprise Security requires Mule Enterprise version 3.3.2 or later. (Not sure which version of Mule you have installed? Find out.)

?

If you've already downloaded Anypoint Enterprise Security version 1.1 onto your instance of Anypoint Studio, follow the procedure below to update to version 1.2. (Not sure which version of Anypoint Enterprise Security you have installed? Find out.)

Installing Anypoint Enterprise Security for Anypoint Studio

1. 2. 3. 4.

Launch Anypoint Studio. Under the Help menu, select Install New Software... Mule opens the Install wizard. Click the Add... button next to the Work with field. In the Add Repository panel, enter a Name for the repository, such as Anypoint Enterprise Security, and in the Location field, paste the following link:

http://security-update-site.s3.amazonaws.com/

then click OK. 5. 6. 7. 8. In the table, check the box to select Premium, then click Next. Click Next in the next wizard pane. Use the radio button to accept the terms of the license agreement, then click Finish. Anypoint Studio installs Anypoint Enterprise Security version 1.2, then asks that you restart the application. Upon relaunch, Studio displays a new palette group called Security which contains six new message processors (see below).

Go Further
?
Refer to the Anypoint Enterprise Security Release Notes for details about what is included with version 1.2.

?

Explore the features of Anypoint Enterprise Security; use menu in left-nav bar to access feature-specific pages.

?
action:

Explore two example applications that demonstrate Anypoint Enterprise Security features in

? ?

Anypoint Enterprise Security Example Application Mule STS OAuth 2.0a Example Application

Mule Secure Token Service OAuth 2.0a Provider
Contents

? o ? ? ?

Overview of OAuth 2.0a The OAuth Dance Configuring OAuth 2.0a on a Mule Web Service Provider Configuring OAuth 2.0a on a Mule Web Service Consumer Next Steps

The Mule Oauth 2.0a Secure Token Service is not yet fully certified for operation on CloudHub. If you are interested in deploying it in this environment, please visit the MuleSoft Customer Portal and open a ticket to request guidance.

Overview of OAuth 2.0a
OAuth 2.0a (Open standard for Authorization) is a method of allowing an application to have limited access to a protected resource via a 3rd-party Web service. In other words, OAuth provides a secure way for a Web service to gain limited, temporary access to a resource, such as a user account, via another Web service. Use Mule Secure Token Service to apply OAuth 2.0a to your Web service provider to:

? ? ?

grant consumers of your Web service limited access to secure data avoid disclosing an end user's access credentials to a Web service consumer retain the authority to revoke the consumer’s access to an end user's secure data at any time To better understand how OAuth works, we must first define the entities involved.

Access Credentials

information one needs to access an asset, such as username and password

Resource Owner Protected Resource Service Provider

a person or system that owns the protected resource and credentials needed to access the resource data which a Consumer wishes to use, to which only the resource owner has access via the access credentials an application or system which stores the protected resource; issues tokens to the Consumer after authenticating the resource owner and confirming authorization to access data

Consumer (Client) Authorization Code Token

a 3rd-party application or system that needs to use the protected resource

a code issued by the Service Provider after confirming the identification of a registered Consumer; exchanged with Service Provider during OAuth dance to acquire a Token authorization that a Service Provider gives to a Consumer to use the protected resource; (the token does not contain the protected resource or access credentials)

Refresh Token

credentials that a Service Provider issues to a Consumer to obtain access to a protected resource again when the original Token expires or becomes invalid; (facilitates access to the protected resource without performing the whole dance again)

Scope

an identifier in the token that defines the specific data to which the consumer has access

Adding OAuth to an online interaction is like giving a parking attendant the valet key to your rental car. You don’t want the parking attendant to access the laptop you have stored in your trunk, but you do want him to park your car for you (limited use of the protected resource). As the resource owner, you could give the attendant your car key (access credentials) to park your car, but with the key, he could also open the trunk and take your laptop. Luckily, the car rental company (the service provider) provided a valet key (token) that will enable the attendant to start the car (scope), but will not allow him to access the trunk.

Access Credentials Resource Owner Protected Resource Service Provider Consumer

car key you car rental car company parking attendant

Token Scope

valet key ability to drive the car, but not access the trunk

In the online world, adding OAuth to an online activity gives a Web service permission to use some of the information in an online private account an end user maintains with another Web service. For example, say you have just discovered a new website that issues online invitations for events. You are anxious to use this service for your upcoming party for 100 friends, but you do not want to enter the email addresses of 100 invitees into the online invitation website. You have already entered them into your online address book on another website. Luckily, the invitation website can use OAuth to solve the problem. Because it wants to make your life easier, the invitation website gives you the option of importing all your contacts from another website. You (resource owner) can click a button to access your account (protected resource) on the daily planner website. When you click the button, the invitation website (consumer) directs you to login page for the daily planner website (service provider). You enter your username and password (access credentials) to access your account (protected resource). After you log in, the daily planner website provides the invitation website with a token that allows the invitation website to import all of your contacts (scope), yet do nothing more (for example, it cannot change your password or access the personal calendar you have stored in the same account). The interaction between Consumer and Service provider in this context is referred to as the OAuth dance (see figure below).

Access Credentials Resource Owner Protected Resource Service Provider Consumer

your username and password to your account on the daily planner website you your account on the daily planner website daily planner website invitation website

Token Scope

token access to the address book, only

The OAuth Dance
The example above briefly describes the OAuth dance between client, provider and resource owner. The list below describes the sequential steps in an OAuth dance which employs the Authorization Code grant type. (For a graphical illustration of the dance steps, see the Mule STS OAuth 2.0a Example Application.) 1. 2. Client app submits a request to the service provider to become a registered client. Service provider evaluates the client request, then, if approved creates a client ID and client secret (if the client identifies itself as

CONFIDENTIAL ) for the client app, which it stores in a list of

registered clients, and sends to the client app. (If the client identifies itself as PUBLIC, the service provider issues only a client ID, but no client secret.) 3. Client app wants to use data (protected resource) housed by service provider, so initiates a request to access the data to the service provider. 4. Client app calls the service provider's authorization server, providing client ID to confirm that it is a registered client of the Service Provider. 5. Client app, using a login page supplied by the service provider, asks that the resource owner use the access credentials to authenticate themselves to the service provider. 6. After confirming that the client ID is valid (i.e. the client app has previously registered with the service provider), and authenticating the resource owner via login credentials, the service provider returns an authorization code. 7. Client app calls the service provider's authorization server again, providing its authorization code, client ID (again), and client secret. 8. 9. Service provider returns a token in which it specifies the scope. Client app calls the service provider's resource server, providing the token, to request the protected resource (data). 10. Service provider delivers the protected resource.

Configuring OAuth 2.0a on a Mule Web Service Provider
Whenever you wish to expose a Web service protected with OAuth 2.0a security, you must insert an OAuth Provider and a Global OAuth Provider into your Mule Application. The Creating an OAuth 2.0a Web Service Provider document describes how to build a Web service protected by OAuth 2.0a.

Configuring OAuth 2.0a on a Mule Web Service Consumer
Whenever you wish to connect your Web service client to an API which uses OAuth 2.0a security, you must comply with the provider’s mandate and add OAuth 2.0a security to your Web service client. (Access the Web service provider’s documentation to determine whether it demands the use of OAuth 2.0a.) Apply OAuth 2.0a to your Web service client to access a Web service that mandates the use of OAuth. This enables you to:

?

leverage an end user’s secure asset with a Web service provider by requesting, and temporarily gaining restricted access to, the asset

?

avoid acquiring a resource owner’s protected resources Use an Anypoint? Connector (several are included in the out-of-the-box Mule ESB distribution) in your Mule flow to consume a Web service. Alternatively, use DevKit to build a customized connector that will enable you to connect with, and consume, the Web service of an external service provider.

Next Steps
1. Examine the Mule STS OAuth 2.0a Example Application which illustrates how to add OAuth 2.0a to a Web service provider in Mule. 2. Learn more about Authorization Grant Types.

Creating an OAuth 2.0a Web Service Provider

Contents

? ? ? ? ? ? ? ? ?

Assumptions OAuth 2.0a Elements Applying OAuth 2.0a to a Web Service Provider Paths to Authentication Defining Resources Creating an OAuth Provider Global Element OAuth Grant Types Creating a Client Registration Flow Disallow Client Access Version 1.2 only

?

Creating OAuth Validation Flows

? ?

Persisting Object Stores Go Further The primary responsibility of an OAuth2 Web service provider is to control access to protected resources. Playing the part of both the Authorization server and the Resource server, the OAuth provider module hosts the protected resources and issues tokens to access protected resources without sharing the resource owner's credentials with the client applications. The service provider in the OAuth dance performs the following tasks:

? ? ? ? ? ? ?

Provides a login page for resource owners to enter login credentials Authenticates clients, both CONFIDENTIAL and PUBLIC Authenticates the resource owner's credentials Issues and validates authorization codes Provides tokens, which specify the data to which a client may have access (scope) Validates tokens, thereby granting access to a protected resource Issues refresh tokens to clients For a detailed explanation of the OAuth dance, see the Mule STS OAuth 2.0a Example Application.

Assumptions
This topic introduces the idea of Global Elements; if you are unfamiliar with this functionality, access Global Elements to learn more before proceeding. It is assumed that you're familiar with the OAuth dance and OAuth2 grant types.

OAuth 2.0a Elements
Mule provides two elements that enable you to configure a Web service provider capable of completing the tasks listed above.

Element Global OAuth Element

Description A global element in which you specify most of the configuration settings for the provider, such as login page details, security providers,

Studio Visual Editor The Coding Referenceattribute in any OAuth Provider Module

XML

<oauth2-provider:config />

Message Processor refers to this.

Element

Description whether to issue refresh tokens, token lifespan, and supported grant types and scopes. This global element is meant to be referenced by message processors.

Studio Visual Editor

XML

Validate

Configure to validate tokens, that confirming the client

Add

an OAuth

Provider

<oauth2-provider:validate />

Message Processor and set the operation attribute toValidate

presents the correct scopes to access the protected resource.

Because the OAuth provider module message processor only issues tokens to registered clients, Mule also offers two methods for registering clients: 1. You can manually define a list of registered clients during the configuration of your Mule application. 2. You can enable clients to register dynamically in the Mule application. Note that the OAuth provider module itself does not generate client IDs or secrets. These are generated by another mechanism, for a example a Web page with a form that validates user input, then generates the ID and secret. After generating the ID and secret, this mechanism – the Web page in this example – simply passes the information to the OAuth provider module, which uses the data to keep track of clients registered to use the service. With respect to registering clients, then, the OAuth provider module is responsible for the following tasks:

? ? ?
only

Accepting and storing the client ID Accepting and storing the client secret Removing, when necessary, a client ID from the clientStore of registered clients Version 1.2

?

Revoking access or refresh tokens Version 1.2 only

Mule provides three elements to complete the above-listed tasks:

Element

Descriptio n

Studio Visual Editor

XML

Create client

Accepts and stores client the data,

Add an OAuth Provider Message Processor and set the operation attribu te to create client.

<oauth2-provider:create-clie nt />

including ID, secret, redirection URIs, scopes, and

grant types in the clientStore. (the clientStore could be a or

database the

default

persistent object store, depending on your requirements. ) Delete Client –Version 1.2 only Removes clientIDs from the clientStore. Add an OAuth Provider Message Processor and set the operation attribu te to delete client. Revoke Token – Versio n 1.2 only Revokes access refresh tokens, or Add an OAuth Provider Message Processor and set the operation attribu

<oauth2-provider:delete-clie nt />

<oauth2-provider:revoke-toke n />

Element

Descriptio n invalidating the correspondin g pair as well (i.e. if the

Studio Visual Editor

XML

te to revoke token.

message processor revokes the

access token, it automatically revokes any

refresh token associated with it, and vice versa).

Skip to the code

Applying OAuth 2.0a to a Web Service Provider
To apply OAuth 2.0a to a Web service that you publish, you must complete, at minimum, five tasks. The first two tasks define resources which the OAuth Provider elements reference; the last three apply OAuth 2.0a to Mule flows, initiating OAuth2 authentication when a consumer calls the Web service. The table below lists these tasks, along with the Mule elements involved in each task and the OAuth tasks for which each element is responsible.

Task 1. Create a Spring bean to define an authentication manager and provider 2. Configure a security manager

Mule Element Spring bean

OAuth Tasks Performs client authentication

Mule Security Manager

Delegates client authentication

Task 3. Create a Global OAuth 2.0a provider to define several OAuth parameters 4. Create a Client Registration flow 5. Create OAuth Validation flows

Mule Element Global OAuth provider element

OAuth Tasks Defines most of the service provider's OAuth 2.0 parameters

OAuth provider module configured to Create

Stores client IDs and secrets Validates the access token, thereby granting, or rejecting, access to a protected resource

Client
OAuth provider module configured to Validate or

Validate-client

Paths to Authentication
Before tackling the work of creating an OAuth 2.0a Web service, it is important to understand the various ways in which a service provider can authenticate a client. When a client calls an OAuth Web service, it must identify itself by one of two types: PUBLIC or CONFIDENTIAL.

? ?

A PUBLIC client provides a client ID which the Web service provider uses for authentication A CONFIDENTIAL client provides validation credentials (client ID and client secret) which the Web service provider uses for authentication If CONFIDENTIAL, a client must provide validation credentials in one of three different parts of the request:

? ? ?

In the query In the body In the authentication headerTherefore, you must configure your OAuth 2.0a Web service provider to match the type(s) of client requests you expect to receive. The figure below illustrates the different types of requests and their resulting paths to authentication.

If the client sends validation credentials in the body or the query of the request, the OAuth Web service provider simply validates the incoming credentials (client ID and client secret) against the content in the clientStore. If, on the other hand, the client sends validation credentials in the authentication header of the request, the service provider uses a security manager to delegate authentication to an authentication manager. The authentication manager users an authentication provider to validate a client'sprincipals (username and password, for example).

Defining Resources
The following procedure describes the steps you need to take in order to define the resources that the OAuth Provider and Global OAuth Provider reference. To define OAuth provider resources, complete the steps listed below.

1.

Within your Web service project in Mule, create a Spring bean called ss-authentication

manager, in which you define theauthentication-provider. It will essentially be a database of
the users that are allowed.

<spring:beans> <ss:authentication-manager id="resourceOwnerAuthenticationManager"> <ss:authentication-provider> <ss:user-service id="resourceOwnerUserService"> <ss:user authorities="RESOURCE_OWNER"/> </ss:user-service> </ss:authentication-provider> </ss:authentication-manager> </spring:beans>
Refer to the Spring Security documentation for different ways of configuring the authentication database.
2. Within your Web service project in Mule, create a security manager element which references the authentication manager. (In the context of an OAuth Web service, the authentication manager is the security provider.)

name="john"

password="doe"

<mule-ss:security-manager> <mule-ss:delegate-security-provider name="resourceOwnerSecurityProvider" delegate-ref="resourceOwnerAuthenticationManager"/> </mule-ss:security-manager>

The OAuth 2.0 provider enables you to configure two security providers: resourceOwnerSecurityProvider and clientSecurityProvider. resourceOwnerSecurityProvider authenticates resource owners (eg: when the user credentials are validated after the login page). The only situation where this provider is not required, is when the Grant Type is Client Credentials. clientSecurityProvider validates client credentials, it's only needed when a client is confidential AND has a client secret. Whenever the client credentials are sent on the authorization header, you need this provider to delegate the authentication.

Creating an OAuth Provider Global Element
A Global Element in Mule is an element that stores common configuration settings. A global element can be referenced by any number of message processors, which in this way use the configuration settings of the global element. ? ?
1. 2. STUDIO Visual Editor

XML Editor or Standalone Add an OAuth Provider module message processor to your Mule project. Configure the attributes of the message processor according to the table below the image. The "Required" column indicates that an attribute is required for validating a client app and resource owner. (Refer to example code below.)

Field

Requi red

Value

Field

Requi red

Value

Name Access Token Endpoint Path Host

A unique name for the global element. Configures the path of the access token endpoint required to access resource server. Default value: token

Web service host used for the generated authorization, token and login endpoints. Default value: localhost

Provider Name Authoriza tion Ttl Seconds Port

Name of the Web service provider. For example, in the login page. Lifespan of authorization code in milliseconds. Default value: 600

TweetBook. This is displayed

Port on which the Web service is exposed. The authorization endpoint and the token endpoint listen on this port. Default value: 9999

Client Store Referenc e Authoriza tion Code Store Referenc e Token Store Referenc e Authoriza

In-memory store that retains OAuth client-specific information. Use this field to reference a specific element that implements the ClientStore interface, typically an object store. Default value: persistent

object store

In-memory store that retains OAuth client-specific information. Use this field to reference a specific element that implements the AuthorizationCodeStore interface, typically an object store. Default value: persistent

object store

In-memory store that retains OAuth client-specific information. Use this field to reference a specific element that implements the TokenStore interface, typically an object store. Default value: persistent

object store

Configures the path of the authorization endpoint required to access resource

Field

Requi red

Value

tion Endpoint Path Login Page

server. Default value: authorize

URL for the service provider's end user login page. The resource owner logs into her account from this page. Default value: org/mule/modules/oauth2/provider/www/templates/lo

gin.html
Scopes x A space-separated list that defines a set of scopes of data to which to provide access. Consumers may then be limited to access certain scopes only. Example: READ_PROFILE

WRITE_PROFILE READ_BOOKSHELF

WRITE_BOOKSHELF
Token Ttl Seconds Connecto r Referenc e Resource Owner Security Provider Referenc e If the only configured grant type is Client Credentials, then this field is not required. Client Security Provider Referenc e The reference to the security provider that validates client credentials. x Lifespan of token in milliseconds. Default value: 86400 A reference to the type of transport, which defaults to HTTP. If your application uses something other than HTTP – Jetty, HTTPS, Servlet – or you have some specific HTTP transport configurations you wish to reference, use this field to reference a specific connector. The reference to the authentication server's security provider. For example,resourceOwnerSecurityProvider references the Spring security manager (which, in turn, references the authentication manager Spring bean).

Field

Requi red

Value

Supporte d Grant Types

Space-separated list of authorization grant types that the OAuth Web service provider supports. Specify one of the values listed below. See the section below for more details.

AUTHORIZATION_CODE (default) IMPLICIT RESOURCE_OWNER_PASSWORD_CREDENTIALS CLIENT_CREDENTIALS
Rate Limiter Referenc e References a package to define limitations for the rate at which a client can call the interface. By default, referencesorg.mule.modules.oauth2.provider.rateLimit.Sim

pleInMemmoryRateLimiter.
Use the class to set maximumFailureCount (default = 5) and authResetAfterSeconds(default = 600).

Enable Refresh Token

Set to TRUE, this attribute allows Mule to send refresh tokens. Default value: FALSE

URIs for accessing endpoints are be built following the structure below:
http://localhost:<port>/<path>

<oauth2-provider:config name="oauth2Provider" providerName="TweetBook" host="localhost" port="${http.port}" authorizationEndpointPath="tweetbook/oauth/authorize" accessTokenEndpointPath="tweetbook/oauth/token" resourceOwnerSecurityProvider-ref="resourceOwnerSecurityProvider" scopes="READ_PROFILE WRITE_PROFILE READ_BOOKSHELF WRITE_BOOKSHELF" doc:name="OAuth provider module"> </oauth2-provider:config>

OAuth Grant Types
OAuth provides four basic grant types that the client can use to validate itself when it requests for a token. Each of these grant types requires a specific configuration of the OAuth Provider Global Element.

If unsure about the difference between each grant type, and when to use each type, you can glean some context from the introduction to the OAuth2 spec. ? ? ? ?
Authorization Code

Implicit

Resource Owner Password Credentials

Client Credentials

The Authorization Code grant type is meant for general use and is the most secure of all the grant types. To implement authorization code, clients need to define the following pieces of information:

? ? ?

Client ID Client Secret Redirect URL Below is a simple typical configuration of an oauth2 module with an authorization code client:

<oauth2-provider:config name="oauth2Provider" providerName="SampleAPI" supportedGrantTypes="AUTHORIZATION_CODE" port="8081" authorizationEndpointPath="sampleapi/api/authorize" accessTokenEndpointPath="sampleapi/api/token" resourceOwnerSecurityProvider-ref="resourceOwnerSecurityProvider" scopes="READ_RESOURCE POST_RESOURCE" doc:name="OAuth provider module"> <oauth2-provider:clients> <oauth2-provider:client clientId="myclientid" secret="myclientsecret" Bookstore">

type="CONFIDENTIAL" clientName="Mule Bookstor

<oauth2-provider:redirect-uris> </oauth2-provider:redirect-uris> <oauth2-provider:authorized-grant-types> </oauth2-provider:authorized-grant-types> <oauth2-provider:scopes> <oauth2-provider:scope>READ_RESOURCE</oauth2-provider:scope> <oauth2-provider:scope>POST_RESOURCE</oauth2-provider:scope> </oauth2-provider:scopes> </oauth2-provider:client> </oauth2-provider:clients> </oauth2-provider:config>
Click to see a full working Mule flow that includes this configuration In order to test this example, you need to perform an OAuth2 dance with several steps: 1. You must first invoke the authorization endpoint with a request that includes the client id, the type of authorization you want to perform, the redirect URL, and the scopes you want to authorize. The structure of the request should look like the URI below:

<oauth2-provider:redirect-uri>http://localhost*</oauth2-provider:r

<oauth2-provider:authorized-grant-type>AUTHORIZATION_CODE</oa

http://localhost:8081/sampleapi/api/authorize?response_type=code&client_id=myclientid&scope=READ_RESOURCE&
2. This displays the login page in the browser. Once the user has successfully logged in, the provider sends a redirect to the specified redirect_uri. This redirect includes additional properties, including an access code. 3. You then need to send this code to the token endpoint in a request that also includes the client id, the client secret and some of the information in the previous call, for security reasons. The structure of the request should look like the URI below:

http://localhost:8081/sampleapi/api/token?grant_type=authorization_code&client_id=myclientid&client_secret=myclien

here the access code>&redirect_uri=http://localhost:8081/redirect
4. If everything works correctly, you get a JSON response like the one below:

{ "scope":"READ_RESOURCE", "expires_in":86400, "token_type":"bearer",

"access_token":"huig0RVoGdFoz_mvBaV4ovfjj0Afe8yOAp_v2q0tunevsJVpD2HNRhx8lL6JnMDys

}
5. You can now include the access_token in your requests to access to protected resources:

http://localhost:8081/resources?access_token=huig0RVoGdFoz_mvBaV4ovfjj0Afe8yOAp_v2q0tunevsJVpD2HNRhx8lL

Creating a Client Registration Flow
Recall that in order to use a Web service protected by OAuth 2.0a, a client must first register with the service. The following procedure describes the steps needed to configure a Mule flow to dynamically accept client registration requests.

? ?
1. 2.

STUDIO Visual Editor

XML Editor or Standalone Create a new Mule flow with an inbound connector. Use one of three following methods to store client IDs and secrets.

a.

Add an OAuth provider module message processor to the flow which will accept and store client IDs and secrets. Configure the element's fields according to the table below.

Field Display Name Config Reference Operation Client Id

Required

Value Enter a unique name for the global element.

x

Reference the global OAuth provider module element you created above.

x x

Create client Define where to acquire the client ID. (In the example code below, Mule accesses an object store to validate

the client_ID and client_secret.) Use a Mule expression to dynamically accept this information from clients. Client Name Description Principal Secret Offer a brief description of the client application. Defines a client's principals (username and password, for example). Define where to acquire the client secret. Not a required attribute if the type is PUBLIC. Type Strings Define the client type (PUBLIC or CONFIDENTIAL). Select Create A List, then click the icon to add Identify the client application by name.

an oauth2-provider:authorized-grant-types child

element

to the oauth2-provider:create-client element in your config. In the dialog, click Define, then enter one or more of the following values, separated by spaces:

AUTHORIZATION_CODE RESOURCE_OWNER_PASSWORD_CREDENTIALS CLIENT_CREDENTIALS
Strings Select Create A List, then click the icon

IMPLICIT

to

add to

an oauth2-provider:redirect-urischild

element

the oauth2-provider:create-client element in your config. In the dialog, click Define, then enter a URI to which the message processor

Field

Required

Value redirects an authorization code. During registration, a client indicates which are its valid redirect URIs. When the client later requests an authorization code, it also includes a redirect URI. If the redirect URI included in the request for authorization code is valid (i.e. matches one of the redirect URIs submitted by the client during registration), the message processor directs the authorization code to the specified URI.

Strings

Select Create

A

List,

then

click

the

icon element

to

add to

an oauth2-provider:scopes child

the oauth2-provider:create-client element in your config. In the dialog, click Define, then enter a space-separated list of scopes which the client must provide when it uses the service.

See the code example below. Notice that Mule creates a default object store, then loads clients' information into that object store.

<oauth2-provider:config ... <oauth2-provider:clients>

<oauth2-provider:client clientId="${client_id}" secret="${client_secre Bookstore"> <oauth2-provider:redirect-uris> </oauth2-provider:redirect-uris> <oauth2-provider:authorized-grant-types> </oauth2-provider:authorized-grant-types> <oauth2-provider:scopes> <oauth2-provider:scope>READ_PROFILE</oauth2-provider:scope>

type="CONFIDENTIAL" clientName="Mule Bookstor

<oauth2-provider:redirect-uri>http://oauth-consumer.qa.cloudhub.io*</oa

<oauth2-provider:authorized-grant-type>AUTHORIZATION_CODE</oa

<oauth2-provider:scope>READ_BOOKSHELF</oauth2-provider:scope> <oauth2-provider:scope>WRITE_PROFILE</oauth2-provider:scope> </oauth2-provider:scopes> </oauth2-provider:client> </oauth2-provider:clients>

<oauth2-provider:scope>WRITE_BOOKSHELF</oauth2-provider:scope

</oauth2-provider:config>
b. Add a Spring bean and write Java code to be referenced by it, using the default object store. In order to do this you must use the XML Console. In the example code below, the Spring bean invokes the initialize method of the TweetBookInitializer Java class. Mule generates the value of the default object store, then the Spring bean sets that value on the clientRegistration property.

<spring:bean class="org.mule.modules.security.examples.oauth2.TweetBookInitializer" init-method="initialize" /> public class TweetBookInitializer { public static final String BOOKSTORE_CLIENT_SECRET

p:clientRegistration="#{oauth2Provider.configuration.clientStore

public static final String BOOKSTORE_CLIENT_ID = "e7aaf348-f08a-11e1-9237-96c6dd6a "ee9acaa2-f08a-11e1-bc20-96c6dd6a022f"; private ClientRegistration clientRegistration; public void initialize() { final Client bookstoreClient = new Client(BOOKSTORE_CLIENT_ID); bookstoreClient.setSecret(BOOKSTORE_CLIENT_SECRET); bookstoreClient.setType(ClientType.CONFIDENTIAL); bookstoreClient.setClientName("Mule Bookstore"); bookstoreClient.setDescription("Mule-powered On-line Bookstore"); bookstoreClient.getRedirectUris().add("http://localhost*"); bookstoreClient.getScopes().addAll(

bookstoreClient.getAuthorizedGrantTypes().add(RequestGrantType.AUTHORIZATION_

Utils.tokenize("READ_PROFILE READ_BOOKSHELF WRITE_BOOKSHELF WRITE_PROFILE clientRegistration.addClient(bookstoreClient); } public void setClientRegistration(final ClientRegistration clientRegistration) {

this.clientRegistration = clientRegistration; } }
c. IDs and secrets. Create a custom implementation of the object store to store client data, which includes

i.

Create an implementation of the org.mule.modules.oauth2.provider.client.ClientStore interface

ii.

In the XML configuration, add a

clientStore-ref property to

the oauth2-provider:create-client element. Mule invokes the getClientById method of the contract to obtain client IDs and secrets.

Disallow Client Access
Version 1.2 only To prevent an existing client from using the Web service, use a flow to remove the client ID from the list of registered clients.

delete-client element in a new

Removing a client ID from the list of registered clients does not automatically revoke tokens related to the clientID. After removing a client from the list, you can wait for the client's existing token – access or refresh – to expire, which thereafter bars them from using the Web service, or you can revoke the tokens manually using the revoke-token element (Revoke Token message processor in Studio's Visual Editor). ? ?
1. 2. 3. Studio Visual Editor

XML Editor Create a new Mule flow that includes an inbound connector. Add an OAuth Provider Module after the inbound connector. Configure the attributes of the OAuth Provider Module according to the table below.

Field Display Name Config Reference Operation Client Id

Required

Value Enter a unique name for the global element.

x

Reference the global OAuth provider module element you created above.

x x

Delete client Define where to acquire the client ID. Use a Mule expression to dynamically accept this information from clients.

4.

Optionally, add a second OAuth Provider Module after the first one to revoke tokens from a client, immediately barring them from using the Web service. Then configure the attributes as per the table below.

Field Display Name Config Reference Operation Client Id

Required

Value Enter a unique name for the global element.

x

Reference the global OAuth provider module element you created above.

x x

Revoke token Define where to acquire the token. Use a Mule expression to dynamically accept this information from clients.

Full Code Example of User Registration and Deletion
Note that if you copy this code into an editor, there are several fields that need to be completed with implementation-specific data.

<?xml version="1.0" encoding="UTF-8"?>

<mule xmlns:oauth2-provider="http://www.mulesoft.org/schema/mule/oauth2-provider" xmlns:http="http xmlns="http://www.mulesoft.org/schema/mule/core"

xmlns:doc="http://www.mu

xmlns:spring="http://www.springframework.org/schema/beans" version="EE-3.4.0" xmlns:xsi="http://w
http://www.mulesoft.org/schema/mule/core http://www.mulesoft.org/schema/mule/core/current/mule.xsd http://www.mulesoft.org/schema/mule/http http://www.mulesoft.org/schema/mule/http/current/mule-http.xsd

xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/b

http://www.mulesoft.org/schema/mule/oauth2-provider http://www.mulesoft.org/schema/mule/oauth2-provider/1.2/mule

<spring:bean id="clientsObjectStore" class="org.mule.util.store.InMemoryObjectSto destroy-method="dispose" />

<spring:bean name="clientStore" class="org.mule.modules.oauth2.provider.client.Ob <spring:property name="objectStore" ref="clientsObjectStore" /> </spring:bean> <!-- sample for token store --> <!--

<spring:bean name="tokenStore" class="org.mule.modules.oauth2.provider.token.Obje <spring:property name="refreshTokenObjectStore" ref="clientsObjectStore" /> <spring:property name="accessTokenObjectStore" ref="clientsObjectStore" /> </spring:bean> --> <oauth2-provider:config name="oauth2ProviderRegister" providerName="SampleAPI" supportedGrantTypes="IMPLICIT" port="8085" clientStore-ref="clientStore" authorizationEndpointPath="sampleapi/api/authorize" accessTokenEndpointPath="sampleapi/api/token" resourceOwnerSecurityProvider-ref="resourceOwnerSecurityProvider" scopes="READ_RESOURCE POST_RESOURCE" doc:name="OAuth provider module" />

<!-- sample flow for registering a client --> <flow name="register-clientsFlow1" doc:name="register-clientsFlow1"> <http:inbound-endpoint exchange-pattern="request-response" host="localhost" doc:name="HTTP"/> <oauth2-provider:create-client clientId="#[message.inboundProperties.clientId]" <oauth2-provider:redirect-uris> </oauth2-provider:redirect-uris> <oauth2-provider:authorized-grant-types> </oauth2-provider:authorized-grant-types> <oauth2-provider:scopes> <oauth2-provider:scope>READ_RESOURCE</oauth2-provider:scope> <oauth2-provider:scope>POST_RESOURCE</oauth2-provider:scope> </oauth2-provider:scopes> </oauth2-provider:create-client> secret="#[message.inboundProperties.secret]" doc:name="OAuth provider module">

config-

clientName="#[message.in

<oauth2-provider:redirect-uri>http://localhost*</oauth2-provider:redirect-

<oauth2-provider:authorized-grant-type>AUTHORIZATION_CODE</oauth2-pro

</flow> <!-- sample flow for revoking a client --> <flow name="unregister-clientsFlow1" doc:name="unregister-clientsFlow1"> doc:name="HTTP"/> <oauth2-provider:delete-client clientId="#[message.inboundProperties.clientId]" /> </flow> </mule>

<http:inbound-endpoint exchange-pattern="request-response" host="localhost" p

config-

Creating OAuth Validation Flows
The following procedure describes the steps to configure Mule flows to accept requests for protected resources. You can create a flow that allows a client app to access just one scope of a protected resource, or multiple scopes of a protected resource. (In ourexample application — see code below — Mule uses two flows with OAuth provider modules: one to enable clients to access theREAD_PROFILE scope, one to enable clients to access the

READ_BOOKSHELF scope.)

A validation flow must contain an OAuth provider module message processor which defines a few of the attributes required for an OAuth 2.0a Web service provider. Generally speaking, however, the OAuth Provider message processor in a flow behaves more like a placeholder, referencing the OAuth provider global element for the bulk of its processing instructions.

? ?
1.

STUDIO Visual Editor

XML Editor or Standalone Create a new Mule flow that includes an inbound connector and a connection to a protected resource.

2.

To this Mule flow, add an OAuth2 provider module message processor before the point in the flow at which Mule accesses the protected resource. In other words, set the OAuth2 provider module message processor before Mule calls a database or another service to access the resource owner's private, secure data.

3.

Configure the attributes of the OAuth2 provider module according to the table below.

Field Display Name Config Reference Operation

Required

Value Enter a unique name for the message processor in your flow.

x

Use the name of the new global OAuth provider module element you created above.

x

Set to validate for authorization grant types that utilize "three-legged OAuth" (Authorization Code, Implicit, and Resource Owner Password Credentials). Set to validate-client to check that the provided client credentials are valid.

Resource

Specifies resource owner roles Mule enforces when validating a token.

Owner Roles Scopes Throw Exception Unaccepted On x Specifies the scopes of data to which the client app will have access. Version 1.2 only When set to FALSE , if the message processor encounters an invalid token, it performs two actions: it returns an HTTP error, then stops the flow. When set to TRUE, if the message processor encounters an invalid token which Mule can manage with an exception strategy, it throwns an InvalidAccessTokenException. Default value: FALSE.

FORBIDDEN 403

<flow name="publicProfile" doc:name="publicProfile"> <http:inbound-endpoint <oauth2-provider:validate <component class="org.mule.security.examples.oauth2.ProfileLookupComponent" doc:name="Profile Lookup"/> </flow> <flow name="publicBookshelf" doc:name="publicBookshelf"> <http:inbound-endpoint <oauth2-provider:validate address="http://localhost:8084/tweetbook/api/bookshelf" scopes="READ_BOOKSHELF" exchange-pattern="request-response" doc:name="Bookshelf API"/> config-ref="oauth2Provider" doc:name="OAuth provider module"/> <set-payload value="The Lord of the Rings,The Hitchhiker's Guide to the Galaxy" doc:name="Retrieve Bookshelf"/> </flow> address="http://localhost:8084/tweetbook/api/profile" scopes="READ_PROFILE" exchange-pattern="request-response" doc:name="Profile API"/> config-ref="oauth2Provider" doc:name="OAuth provider module"/>

Persisting Object Stores
The Oauth2 provider enables you to specify the implementation of the object stores where the clients, the tokens and the refresh tokens are stored. Here is a sample configuration on how to do this with the client store.

<spring:bean

id="clientsObjectStore"

class="org.mule.util.store.InMemoryObjectS

init-method="initialise" destroy-method="dispose" /> <spring:bean <spring:property name="objectStore" ref="clientsObjectStore" /> </spring:bean> <oauth2-provider:config name="oauth2ProviderRegister" providerName="SampleAPI" supportedGrantTypes="IMPLICIT" port="8085" clientStore-ref="clientStore" authorizationEndpointPath="sampleapi/api/authorize" accessTokenEndpointPath="sampleapi/api/token" resourceOwnerSecurityProvider-ref="resourceOwnerSecurityProvider" scopes="READ_RESOURCE POST_RESOURCE" doc:name="OAuth provider module" />

name="clientStore" class="org.mule.modules.oauth2.provider.client.ObjectStoreClientSt

You may use the JDBC Transport or the Mongo DB transport for database-backed client object stores. Similarly, you may define settings for storing the access tokens and the refresh tokens:

<spring:bean <spring:property ref="refreshTokenObjectStore" />

name="tokenStore" name="refreshTokenObjectStore"

class="org.mule.modules.oauth2.provider.token.ObjectStoreTokenStore">

<spring:property name="accessTokenObjectStore" ref="accessTokenObjectStore" /> </spring:bean>
If you do this, you then need to reference these in the

oauth2-provider:

<oauth2-provider:config name="oauth2ProviderRegister" providerName="SampleAPI" supportedGrantTypes="IMPLICIT" port="8085" tokenStore-ref="tokenStore" authorizationEndpointPath="sampleapi/api/authorize" accessTokenEndpointPath="sampleapi/api/token" resourceOwnerSecurityProvider-ref="resourceOwnerSecurityProvider" scopes="READ_RESOURCE POST_RESOURCE" doc:name="OAuth provider module" />

Go Further
? ?
Read the OAuth2 specs to understand Grant Types better. How to use OAuth with Mule as an OAuth Consumer.

Authorization Grant Types
There are four ways that a consumer can obtain authorization to dance with an OAuth service provider. 1. 2. 3. 4. Authorization Code Implicit Resource Owner Password Credentials Client Credentials The sections below offer brief descriptions of each type of authorization grant, listed according to the level of security, in descending order. Refer to the Mule Secure Token Service document for details regarding OAuth Roles and the OAuth dance.

Authorization Code
For a service provider, this grant type involves the use of both an authorization server (responsible for confirming and granting permission to access the protected resource) and a resource server (responsible for providing access to the protected resource). Though described as independent servers, the authorization and resource entities actually reside on the same Mule server. A consumer must ask for a service provider’s permission to ask for protected resources, then it can ask for the protected resources.

An OAuth dance that involves an Authorization Code grant type proceeds as follows: 1. Client app wants to use data (protected resource) housed by service provider, so initiates a request to access the data to the service provider. 2. Client app calls the service provider's authorization server, providing its client ID to confirm that it is a registered client of the Service Provider. 3. Client app, using a login page supplied by the service provider, asks that the resource owner use the access credentials to authenticate themselves to the service provider. 4. After confirming that the client ID is valid (i.e. the client app has previously registered with the service provider), and authenticating the resource owner via login credentials, the service provider returns authorization code. 5. Client app calls the authorization server again, providing its authorization code, client ID (again), and client secret. 6. 7. 8. Service provider returns a token in which it specifies the scope. Client app calls the resource server, providing the token, to request protected resource (data). Service provider delivers protected resource. This type of authorization grant is especially secure because it authenticates the client and transmits the token without exposing the token to unauthorized parties, including the resource owner.

Implicit
As with the Authorization Code, an Implicit grant type involves both an authorization server and a resource server. However, rather than taking the extra steps to authenticate a client application via authorization code and client secret, the service provider authenticates a client based upon its client ID, then simply hands over the token to access the protected resource. An OAuth dance that involves an Implicit grant type proceeds as follows: 1. Client app wants to use data (protected resource) housed by service provider, so initiates a request to access the data to the service provider. 2. Client app calls the service provider's authorization server, providing its client ID to confirm that it is a registered client of the Service Provider. 3. Client app, using a login page supplied by the service provider, asks that the resource owner use the access credentials to authenticate themselves to the service provider. 4. After confirming that the client ID is valid (i.e. the client app has previously registered with the service provider), and authenticating the resource owner via login credentials, the service provider returns a token. 5. Client app calls the resource server, providing the token, to request protected resource (data).

6.

Service provider delivers protected resource. A simplified version of Authorization Code, the Implicit grant type optimizes performance for clients implemented in a browser using a scripting language, such as Javascript. However, this grant type may expose the token to the resource owner, or the resource owner's user-agent.

Resource Owner Password Credentials
For this type of authorization, a client application simply demands that the resource owner share their service provider login credentials. The client app then accesses the service provider and logs into the resource owner's account using the shared login credentials. The service provider accepts the valid login credentials and grants the client app full access to the resource owner's account. The resource owner, in this case, must trust the client app not to abuse their trust in sharing access to private data. An OAuth dance that involves Resource Owner Password Credentials proceeds as follows: 1. 2. Resource owner provides access credentials to the client app . Client app calls service provider, providing client ID to confirm that it is a registered client of the Service Provider, and the access credentials for the protected resource, and requests a token. 3. token. 4. 5. Client app calls the resource server, providing the token, to request protected resource (data). Service provider delivers protected resource. Offering a much shorter version of the OAuth Dance, this type of authorization grant optimizes performance at the expense of sharing secure access credentials. Service provider authenticates the client app and validates the access credentials, then issues a

Client Credentials
For this type of authorization, a client app requests access to data that is not associated with a particular resource owner. Because no protected resources are involved, a service provider must only verify the client as valid. This type of OAuth interaction is sometimes referred to as "two-legged OAuth" because it involves only two roles: service provider, and an client app. The other three authorization types involve a third role, resource owner, thus are sometimes referred to as "three-legged OAuth". An OAuth dance that involves Client Credentials proceeds as follows: 1. Client app calls the authorization server, providing client ID to confirm that it is a registered client of the Service Provider. 2. After confirming that the client ID is valid (i.e. the client app has previously registered with the service provider), the service provider returns a token, specifying the scope. 3. Client app call the resource server, providing the token, to request specific data.

4.

Client app retrieves the data. Typically, this authorization grant applies when the the client is also the resource owner.

Mule Credentials Vault
Use the Mule Credentials Vault to encrypt data in a .properties file. (In the context of this document, we refer to the .properties file simply as the properties file.) The properties file in Mule stores data as key-value pairs which may contain information such as usernames, first and last names, and credit card numbers. A Mule application may access this data as it processes messages, for example, to acquire login credentials for an external Web service. However, though this sensitive, private data must be stored in a properties file for Mule to access, it must also be protected against unauthorized – and potentially malicious – use by anyone with access to the Mule application. How do you protect the data in a properties file while still making it available to Mule? Use three ingredients: 1. 2. 3. a Mule Credentials Vault a global Secure Property Placeholder element a key to unlock the vault

In the context of Anypoint Enterprise Security, the properties file which stores encrypted properties is called the Mule Credentials Vault.
Contents

How It Works
Imagine a situation in which a developer is tasked with designing a Mule application for the Human Resources department which must access a secure database of private employee information. An HR employee – an authorized end user of the Mule application – submits a request for information, say, an employee's base salary, and the Mule application must access a secure database to retrieve the information. One cannot access this HR database without valid login credentials, so the developer must design the Mule application to access the database, yet keep the database login credentials secret. First, the developer designs the application to process HR end user requests, which includes a call to the secure database. He then creates a Mule Credentials Vault to store the database login credentials, or properties. In the context of Anypoint Enterprise Security, the properties file which stores encrypted properties is the Credentials Vault. When he adds data to the properties file, Mule gives him the option to encrypt the data. He chooses an encryption algorithm (of the 19 available), then enters an encryption key. That encryption key is the only way to decrypt the properties in the properties file. In other words, the encryption key is the only thing that will unlock the Credentials Vault.

Next, the creates a global Secure Property Placeholder element which locates the Credentials Vault (i.e. properties file), then retrieves encrypted properties. However, the Secure Property Placeholder can only access the Credentials Vault (i.e. decrypt the data) if it has the key. Now he has data in a vault and a mechanism to request the data, but where is the key to unlock the vault (i.e. decrypt the data)? And how does the developer ensure that the key is not accessible by everyone with access to the application? If he were to simply hardcode the key into the configuration of the global Secure Property Placeholder, any colleague with access to the application could simply read the key and unlock the vault. The developer, therefore, configures the Secure Property Placeholder to use the key that Mule collects from the user at runtime (see code below). In this context, the key to decrypt the properties becomes a runtime password.

<secure-property-placeholder:config location="test.${env}.properties"/>

key="${prod.key}"

At runtime (i.e. when you run the Mule application on premise or in the cloud), Mule demands that the user (for example, an Operations Administrator) enter a key, which Mule stores in-memory. Recall that the key that Mule demands at runtime is the same key the developer used to encrypt the properties in the Credentials Vault; the developer in this scenario had to have manually given the key to the person who is responsible for running the application, such as an Ops Admin. Whenever a Secure Property Placeholder within the Mule application must unlock the Credentials Vault to retrieve HR database login credentials, it uses the key the Ops Admin entered at runtime. Conveniently, Mule remembers the key for the duration of the Ops Admin's session so as to avoid demanding a key each time a Mule decrypts a property in the vault. However, when the Ops Admin ends the Mule session (i.e. terminates the application), Mule discards the key. To configure Mule to demand that the user enter a key at runtime, the developer includes the following in the system properties (themule-app.properties file in the src>main>app folder):

-M-Dprod.key=uniquepassword -M-Denv=prod
When it needs the key to decrypt the contents of the properties file, the secure properties placeholder asks Mule's system properties file, which uses the in-memory key as entered by the Ops Admin.

Placeholders, Keys and Vaults
In Mule, you can set up several variations of of the Placeholder-Vault-Key relationship.

This topic introduces the idea of Global Elements; if you are unfamiliar with this functionality, access Understand Global Mule Elements to learn more before proceeding.

One-to-One-to-One Relationship
The first variation is a simple one-to-one-to-one relationship, as illustrated in the graphic below. The configuration of one global secure property placeholder demands that it use one key to unlock one Credentials Vault. (In other words, one key decrypts the properties in one properties file.) Unlocked and decrypted at runtime with the key, any flow which must access the data in the properties file can do so.

One-to-One-to-Many Relationship
The second variation is a one-to-one-to-many relationship, as illustrated in the graphic below. The configuration of one global secure property placeholder demands that it use one key to unlock many Credentials Vaults. (In other words, one key decrypts the properties in many properties files.) Unlocked and decrypted at runtime with the key, any flow which must access the data in any of the properties file can do so.

Multiple One-to-One-to-One Relationships
As soon as you assign a different key to each property file, you create a situation that requires multiple one-to-one-to-one relationships. As illustrated in the graphic below, each global secure property placeholder uses only one key which, in turn, unlocks only one Credentials Vault. (In other words, each key decrypts the properties in only one properties file.) Unlocked and decrypted at runtime with multiple keys, any flow which must access the data in any of the properties file can do so.

Use Mule Credentials Vault
To use the Mule Credentials Vault, you must perform three tasks: 1. 2. encrypt properties in a properties file create a global secure property placeholder in your Mule application to use the encryption key Mule collects at runtime 3. configure Mule's system properties file to demand the key at runtime The following sections describe how to complete these three tasks.

Encrypt Properties
? ?
1.

STUDIO Visual Editor

XML Editor or Standalone In Studio, right click the src/main/resources folder, then select New > File.

2.

In the New File wizard, enter a Filename, including the .properties extension. For example, test.properties.

3.

Click Finish. Studio saves the new, blank file in your project and opens a new window in a Properties File Editor window.

4. 5.

Click the

in the .properties tab to close the Properties File Editor window.

In the Package Explorer, right-click the .properties file, then select Open With > Mule Properties Editor.

6.

Click the green property dialog.

icon in the Studio toolbar (see image below) to open the Add a new

7.

Add the key-value pair (property) you wish to record in the properties file.

8.

If you want to save the property as an unencrypted key-value pair, simply click OK to add the new property to the properties file. Essentially, this produces an unencrypted properties file. However, if you wish to encrypt the properties file (i.e. create a Credentials Vault), click the Encrypt button.

9.

Studio opens a Setup encryption information dialog, in which you:

? ?

select the type of algorithm you wish to use to encrypt the value enter the key that Mule will require when asked to decrypt the value

Don't Forget the Key!

The key that you enter to encrypt the properties file is the same key that the administrator enters at runtime. Be sure to keep this key secure and pass it to the administrator(s) who will deploy and run your Mule application. ?

10. 11.

Click OK to complete the encryption. In the Add a new property dialog, Studio displays the encrypted value in the Value field (see below). Click OK to save the property.

12.

Repeat steps 6 - 11 to add many properties to your Credentials Vault. Note that the first time you add an encrypted a property to a properties file, Mule demands that you enter the key. The next time you add an encrypted property to the same properties file, Mule uses the key you entered and does not demand it again. Mule remembers the key (in-memory store) for the duration of your Studio session; when you end your session (i.e. close Studio), Mule "forgets" the key.

You can add unencrypted properties to a properties file. In the properties file, an encrypted property is indecipherable, but recognizable by its wrapper.
encrypted property unencrypted property

Username=![r8weir09458riwe0r9484oi] Username=Aaron Martinez

Set Global Secure Property Placeholder
? ?
1. 2.

STUDIO Visual Editor

XML Editor or Standalone In Studio, create a new global Secure Property Placeholder element. Configure the field values of the global element according to the table below.

Field Name Key

Req'd x x

Value A unique name for your global secure property placeholder. the word or phrase to unlock the Credentials Vault according to the system property you define in this field. For example, ${runtime.property} instructs Mule to demand the key at runtime.

Location Encryption Algorithm Encryption Mode

The name of the properties file that the key unlocks. The type of algorithm you used to encrypt the content of the Credentials Vault.

The procedure that allows Mule to repeatedly use a block cipher with a single key.

Configure Mule to Demand the Key
? ?
1.

STUDIO Visual Editor

XML Editor or Standalone In Studio, access the src>main>app folder, then double-click the mule-app.properties file to open it.

2.

To this system properties file, add code which instructs Mule to demand that the user enter a key at runtime, and store that key in-memory (see sample code below).

-M-Dprod.key=uniquepassword -M-Denv=prod
3. 4. Save your changes to the file, then close. When you start Mule, provide the key to decrypt the properties file.

./mule -M-Dprod.key.property=uniquePassword

Use Case Example
A company has built a Mule application which connects to the Salesforce API. The application stores Salesforce login credentials for all its users. Developers who work on the application must be able to test Salesforce connection functionality, but must not be able to access the users’ Salesforce account information. Therefore, the application has two properties files, one for the production environment of the application, and one that the developers can use to test functionality.

? ?

test.prod.properties (Salesforce key to production environment) test.dev.properties (sandbox environment) The test.prod.properties file stores encrypted contents in the Mule Credentials Vault; the test.dev.properties file stores unencrypted information inside properties file. At runtime, Mule behavior differs according to environment.

?

At runtime in production, the Mule application demands a key which it uses to unlock the Credentials vault so that the Mule flows in the application can utilize the properties in the Credentials Vault to log in to Salesforce (refer to secure property placeholder configuration below). The

secure-property-placeholder element automatically identifies the environment (env) and accesses the Mule Credentials Vault (test.prod.properties file) for genuine credentials

<secure-property-placeholder:config location="test.${env}.properties"/>
? At runtime in the sandbox, the Mule application demands no key because

key="${prod.key}"

the test.dev.properties file is not encrypted. The secure-property-placeholder element automatically identifies the environment (env) and accesses the test.dev.properties file for fake credentials
Because the developers do not have the

prod.key value (i.e. the runtime password, which is also the

key to access the Credentials Vault), they cannot access the secure Salesforce login credentials in the test.prod.properties file. The only one who knows theprod.key is the Operations Team Lead who deploys the application into production.

prod.key for the Credentials prod.key as valid for the duration of the Ops Team Lead’s Mule session. When he quits the application, Mule forgets the prod.key.
When the Ops Team Lead starts Mule, Mule demands that he enter the Vault (see command below). Mule accepts the

./mule -M-Dprod.key=uniquepassword -M-Denv=prod

Go Further
?
Access the example application which demonstrate Anypoint Enterprise Security in action.

Mule Message Encryption Processor
Contents

? o o o ? ? ? ? ?

Encrypting a Message Payload JCE Encrypter XML Encrypter PGP Encrypter Encrypting Part of a Message Payload Decrypting a Message Payload Decrypting Part of a Message Payload Go Further Appendix

Encrypting a Message Payload
Add a Mule Message Encryption Processor to a flow to change the content of a message so that it becomes unreadable by unauthorized entities. Mule can encrypt the entire payload of a message or specific parts of the payload, according to security requirements, using one of the following three Encryption Strategies:

Encryption Strategy JCE Encrypter XML Encrypter

Characteristics ? encrypts stream, byte[] or string ? encrypts string ? encrypts individual fields using xpath express ions

PGP Encrypter

? encrypts stream, byte[] or string ? applies tighter security (relative to JCE and XML)

Encryption Strategy

Characteristics ? increases processing load (relative to JCE and XML)

JCE Encrypter
As Mule’s default encryption strategy, the Java Cryptology Extension (JCE) encrypter encodes a message payload, or part of a payload.

? ?
1.

STUDIO Visual Editor

XML Editor or Standalone Create an global Encryption element, specifying a name for the element if you wish; keep the default value for the Default Encrypter: JCE_ENCRYPTER.

2.

Set an Encryption message processor in the flow in which you wish to encrypt data in the message payload.

3.

Configure the message processor according the table below.

Field Display Name Config Reference Operation Input reference Select encrypter Reference expression or

Req'd

Value A unique name for your message processor.

x

Use the drop down to select the global Encryption element you created.

x

Encrypt Enter a Mule expression to define the part(s) of the message Mule should encrypt. If no value is entered, Mule encrypts the entire message payload.

x

JCE_ECRYPTER

If selected, in the Jce Encrypter Reference, use an expression to reference attributes you have defined elsewhere in the XML configuration of your applications, or to reference the configurations defined in a bean.

Field Define attributes Key ?

Req'd

Value If selected, enter values in the following four fields.

x

The key (i.e. password) to decrypt the encrypted data. It must be 16 bytes long

Key Password ? Algorithm

If the key is stored in a keystore, enter the passwoard to the keystore.

Select an algorithm to use to encrypt the data. Refer to Appendix below for list of available algorithms.

Encryption Mode

Select an encryption code for Mule to use to encrypt the data.

? mutually exclusive

XML Encrypter
The XML encrypter encodes XML string content in a message payload.

? ?
1.

STUDIO Visual Editor

XML Editor or Standalone Create an global Encryption element, specifying a name for the element if you wish; change the default value for the Default Encrypter to XML_ENCRYPTER.

2.

Set an Encryption message processor in the flow in which you wish to encrypt data in the message payload.

3.

Configure the message processor according the table below.

Field Display Name Config Reference Operation Input reference Select encrypter

Req'd

Value A unique name for your message processor.

x

Use the drop down to select the global Encryption element you created.

x

Encrypt Enter a Mule expression to define the part(s) of the message Mule should encrypt. If no value is entered, Mule encrypts the entire message payload.

x

XML_ECRYPTER

Field Reference expression or

Req'd

Value If selected, in the Xml Encrypter Reference, use an expression to reference attributes you have defined elsewhere in the XML configuration of your applications, or to reference the configurations defined in a bean.

Define attributes Key ? Key Password ? Algorithm x

If selected, enter values in the following four fields.

The key (i.e. password) to decrypt the encrypted data. If the key is stored in a keystore, enter the passwoard to the keystore.

Select an algorithm to use to encrypt the data. Refer to Appendix below for list of available algorithms.

Encryption Mode

Select an encryption code for Mule to use to encrypt the data.

4.

? mutually exclusive

PGP Encrypter
Mule has the ability to encrypt a message payload, or part of a payload, using Pretty Good Privacy (PGP). Because of its increased complexity, the topic has earned its own page: refer to the PGP Encrypter document.

Encrypting Part of a Message Payload
For details on message encryption in Mule, refer to the Encrypt a Message Payload section above. By default, when you apply an encrypter, Mule encrypts the entire message payload. However, you can use a Mule Expression to encrypt a specific part of a message rather than the whole payload. Configure the Input Reference to define the specific part(s) of the payload you wish to encrypt.

?

STUDIO Visual Editor

?

XML Editor or Standalone

Additionally, you can add an Xpath expression attribute to the XML encrypter to define specific field(s) to encrypt — credit card number or SSN, for example (see below). ? ?
STUDIO Visual Editor

XML Editor or Standalone

Decrypting a Message Payload
Add a Mule Message Encryption Processor to decrypt the content of a message so that it becomes readable by the message processors in your Mule application. Mule can decrypt the entire payload of a message or specific parts of the payload using one of the following three Encryption Strategies: 1. 2. 3. JCE Decrypter PGP Decrypter XML Decrypter Refer to Encrypt a Message Payload document for details on the Encryption strategies. The type of encryption strategy you use to decrypt a message depends entirely upon the type of encryption employed by the message sender.

Further, you must configure a decrypter’s attributes to address the type of encryption the message’s sender applied. For example, if the message uses a keystore for encryption, your decrypter must use the keystore to decrypt the message.

Decrypting Part of a Message Payload
Refer to the Decrypting a Message Payload section for details on message decryption in Mule. By default, Mule decrypts the entire message payload when you apply a decrypter. However, you can use a Mule Expression to decrypt a specific part of a message payload rather than the whole payload. Configure the Input Expression to define the specific part(s) of the payload you wish to decrypt. Additionally, you can add an Xpath expression attribute to the XML decrypter to define specific field(s) to decrypt — credit card number or SSN, for example (refer to the encryption screenshot and code in Encrypt Part of a Message Payload).

Go Further
?
Examine the Anypoint Enterprise Security Example Application which illustrates how to encrypt and decrypt a message in a Mule flow.

Appendix
Algorithms Available in JCE Minimum Key Size Maximum Key Size AES Blowfish DES DESede Camellia CAST5 CAST6 16 1 8 16 16 1 1 16 Unlimited 8 24 16 16 Unlimited

Algorithms Available in JCE

Minimum Key Size

Maximum Key Size

Noekeon Rijndael SEED Serpent Skipjack TEA Twofish XTEA RC2 RC5 RC6 RSA

16 16 16 16 16 16 8 16 1 1 1 16

Unlimited 16 Unlimited 16 Unlimited Unlimited Unlimited Unlimited Unlimited Unlimited Unlimited Unlimited

PGP Encrypter
Mule has the ability to encrypt a message payload, or part of a payload, using Pretty Good Privacy (PGP). PGP combines data compression and data encryption to secure messages. The compression reduces message transmission time between origin and destination. There are two scenarios that this document addresses:

? ?

using another party's public key to encrypt a messages in a Mule application using one's own set of private and public keys so as to accept, and decrypt messages in a Mule application The sections below outline the steps involved in encrypting or decrypting messages using PGP in Mule. Contents

? ? ? o

Assumptions Encrypting Decrypting Generating PGP Keys

o o o ?

Determining the Numeric Value of the Secret Alias ID Examples Configuring a Decrypter Go Further

Assumptions
This document assumes that you are reasonably familiar with PGP encryption, and the concept of public and private keys. For more details on encryption in general, and PGP in particular, review the PGP 6.5.1 documentation or How PGP Works.

Encrypting
In the world of PGP encryption, the sender of a message must encrypt its contents using the receiver's public key. Thus, where your Mule flow handles messages that it must encrypt with someone else's public key, you'll need to add the receiver's public key to your "key ring" in Mule. Essentially, Mule stores asks the user for the key ring file which the Message Encryption message processor accesses to encrypt the any part of your message before sending.

? ?
1.

STUDIO Visual Editor

XML Editor or Standalone Use a tool such as GPG Keychain Access to import the other party's public key. Refer to section below for more details about using GPG to facilitate implementation of PGP encryption and decryption in Mule.

2.

Using the same tool, export the public key, selecting binary as the output format. This produces a key ring file with a .gpgextension.

3.

Ensure that the .gpg file is stored in a place that the Mule application can access it at runtime; record the filepath of the .gpgfile (also known as your public key ring file).

4.

In your Mule application, create a global Encryption element, specifying a name for the element; change the default value for the Default Encrypter to PGP_ENCRYPTER. (See image below, left.)

5. below.

On the Pgp Encrypter tab, configure the fields (see image below, right) according to the table

Field General Tab Name Default Encrypter

Req'd

Value

x

A unique name for the global element. PGP_ENCRYPTER

Pgp Encrypter Tab Reference expression or If selected, in the Pgp Encrypter Config Reference, use an expression to reference attributes you have defined elsewhere in the XML configuration of your applications, or to reference the configurations defined in a bean. Define attributes Public Ring Name Key File Enter the filepath of the public key ring. This binary "key ring" holds the message receiver's public key. Read more about creating the public key ring above. Note that you do not enter the public key itself, only the location of the key ring file in which the public is stored. 6. Set an Encryption message processor in the flow in which you wish to encrypt data in the message payload. 7. Configure the message processor according the table below. If selected, enter values in the following field.

Field Display Name Config Reference Operation Input reference Select encrypter

Req'd

Value A unique name for your message processor.

x

Use the drop down to select the global Encryption element you created in the steps above.

x

Encrypter Enter a Mule expression to define the part(s) of the message Mule should encrypt. If no value is entered, Mule encrypts the entire message payload.

x

PGP_ENCRYPTER

Field Reference expression or

Req'd

Value If selected, in the Pgp Encrypter Reference, use an expression to reference attributes you have defined elsewhere in the XML configuration of your applications, or to reference the configurations defined in a bean.

Define attributes Principal

If selected, enter values in the following field.

An alternative to using a clientID and secret to authenticate a client, define a username and password as the principal.

8.

Click OK to save your PGP encrypter configuration.

Decrypting
In the world of PGP encryption, the receiver of a message must be prepared to use a private key to decrypt its contents which were encrypted with a public key. Therefore, the receiver of an encrypted message must first generate a set of PGP keys:

? ?

a public key to distribute to those who will use it to encrypt and send messages to you a private key to decrypt the messages you receive which were encrypted using the public key Thus, where your Mule flow receives messages that it must decrypt using your own private key, you must complete the following steps:

1. 2. 3.

Generate a set of keys. Send the public key out to those who will send you encrypted messages. Set a message encryption processor in your Mule flow that uses the private key to decrypt messages it receives. Mule itself does not generate sets of keys, nor distribute public keys. Access the Generating PGP Keys section below to learn more about key generation; otherwise, if you already have your keys, proceed to the instructions directly below to set up a message encryption processor in your Mule flow.

Generating PGP Keys
You can use a tool such as GPG Keychain Access to create a new set of keys in the application (see screenshot below) or from the command line, answering questions to customize and identify your keys

(see code sample below). Best practice recommends using the same key size – 1536 bits or

2048 bits – in all your environments (development, QA and production).

Aarons-MacBook-Air:~ aaron$ gpg --gen-key gpg (GnuPG/MacGPG2) 2.0.19; Copyright (C) 2012 Free Software Foundation, Inc. This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. Please select what kind of key you want: (1) RSA and RSA (default) (2) DSA and Elgamal (3) DSA (sign only) (4) RSA (sign only) Your selection? 1 RSA keys may be between 1024 and 8192 bits long. What keysize do you want? (2048) 2048 Requested keysize is 2048 bits Please specify how long the key should be valid. 0 = key does not expire <n> = key expires in n days <n>w = key expires in n weeks <n>m = key expires in n months

<n>y = key expires in n years Key is valid for? (0) <n=2> invalid value Key is valid for? (0) 2 Key expires at Sat Jun 29 11:46:00 2013 PDT Is this correct? (y/N) y GnuPG needs to construct a user ID to identify your key. Real name: Aaron Somebody Email address: aaron.somebody@mulesoft.com Comment: no comment You selected this USER-ID: "Aaron Somebody (no comment) <aaron.somebody@mulesoft.com>" Change (N)ame, (C)omment, (E)mail or (O)kay/(Q)uit? O You need a Passphrase to protect your secret key. ***passphrase entered, and hidden*** We need to generate a lot of random bytes. It is a good idea to perform some other action (type on the keyboard, move the mouse, utilize the disks) during the prime generation; this gives the random number generator a better chance to gain enough entropy. We need to generate a lot of random bytes. It is a good idea to perform some other action (type on the keyboard, move the mouse, utilize the disks) during the prime generation; this gives the random number generator a better chance to gain enough entropy. gpg: key D54945B4 marked as ultimately trusted public and secret key created and signed. gpg: checking the trustdb gpg: 3 marginal(s) needed, 1 complete(s) needed, PGP trust model gpg: depth: 0 valid: pub uid sub 3 signed: 0 trust: 0-, 0q, 0n, 0m, 0f, 3u gpg: next trustdb check due at 2013-06-29 2048R/D54945B4 2013-06-27 [expires: 2013-06-29] Key fingerprint = 68BC E0A3 A377 417A 5102 ABB3 7689 9D95 D549 45B4 Aaron Seombody (no comment) <aaron.somebody@mulesoft.com> 2048R/C1596E6C 2013-06-27 [expires: 2013-06-29]

When it has completed the operation, the key generation tool adds your new public key to a system wide public key ring, and adds your private key to a parallel system-wide private key ring. The next step is to identify the filepath of the key rings so as to make them available for Mule to access.

? ? ? ?

find the public key ring file (pubring.gpg) on your local drive find the private key ring file (secring.gpg) Mac or Unix: located in the hidden .gnupg folder on your local drive Windows: location varies according to your local configuration, but may be at a location similar toC:/Users/myuser/AppData/Roaming/gnupg

Determining the Numeric Value of the Secret Alias ID
To configure your message encryption processor in Mule, you must be in possession of the Secret Alias ID (i.e. the public key). Determining the numeric value for the Secret Alias Id is somewhat complex as its numeric value isn't accessible via the key ring file or within the GPG utility. You can, however, employ a trick to discover the secret alias ID: assign a random value, such as "1", to the Secret Alias Id in the message encryption processor in your Mule flow, then run the application to let Mule throw an error on purpose. In the exception thrown from the Console output, Mule displays a message indicating the keys you can use. See image below.

Examples
Two MuleSoft blog posts offer examples of how to use PGP encryption in Mule. Access the following links to dig deeper into PGP.

? ?

PGP Encryption and Salesforce Integration Using PGP Security: Explained from the Top

Configuring a Decrypter
? ?
1. STUDIO Visual Editor

XML Editor or Standalone Before you begin, ensure you have the following three pieces of information in your possession:

a. b. c.

the filepath of your public key ring the filepath of your private key ring the numeric value of the Secret Alias Id (i.e. the public key) See Generating PGP Keys section above to learn more about acquiring these values.

2.

Create an global Encryption element, specifying a name for the element if you wish; change the default value for the Default Encrypter to PGP_ENCRYPTER. (Refer to image below, left.)

3.

On the Pgp Encrypter tab, configure the fields according to the table below. (Refer to image below, right.)

Field General Tab

Req'd

Value

Name Default Encrypter Pgp Encrypter Tab Reference or expression

x

A unique name for the global element. PGP_ENCRYPTER

If selected, in the Pgp Encrypter Reference, use an expression to reference attributes you have defined elsewhere in the XML configuration of your applications, or to reference the configurations defined in a bean.

Define attributes Public Ring Name Secret Ring Name Secret Id Secret Passphrase Alias Key File Key File

If selected, enter values in the following four fields.

Enter the filepath of the public key ring. This binary "key ring" holds the public key. Read more about finding and creating public key rings in the Generating PGP Keys section above. Enter the filepath of the private key ring. This binary "key ring" holds the message sender's private key. Read more about finding and creating public public and private key rings in the Generating PGP Keys section above. The numeric value of the RSA public key.

The password to access the private key. When you generate keys using GPG, the wizard or command line prompt demands that you enter your Real Name and Email Address, then asks you to create a password for accessing your keys. The password you used to generate the keys is the value you enter as the secret passphrase, which Mule uses to access the contents of the private key ring.

4.

Set an Encryption message processor in the flow in which you wish to encrypt data in the message payload.

5.

Configure the message processor according the table below.

Field Display Name Config Reference

Req'd

Value A unique name for your message processor.

x

Use the drop down to select the global Encryption element you created.

Field Operation Input reference Select encrypter Reference or expression

Req'd x

Value Decrypter Enter a Mule expression to define the part(s) of the message Mule should decrypt. If no value is entered, Mule decrypts the entire message payload.

x

PGP_ENCRYPTER

If selected, in the Pgp Encrypter Reference, use an expression to reference attributes you have defined elsewhere in the XML configuration of your applications, or to reference the configurations defined in a bean.

Define attributes Principal

If selected, enter values in the following field.

An alternative to using a clientID and secret to authenticate a client, define a username and password as the principal. When you generate a set of keys with GPG, you are asked to enter a Real Name and an Email Address – together, these two pieces of data form the value of your Principal.

Go Further
? ? ?
Learn how to encrypt your properties file with the Mule Credentials Vault. Learn how to encrypt or decrypt messages with XML or JCE Encryption. Two MuleSoft blog posts offer examples of how to use PGP encryption in Mule. Access the following links to dig deeper into PGP.

? ?

PGP Encryption and Salesforce Integration Using PGP Security: Explained from the Top

Mule Digital Signature Processor
The Mule Digital Signature Processor adds a digital signature to a message payload, or part of the payload, to prove the identity of the message’s sender. Mule can also verify a signature on a message it receives to confirm the authenticity of the message’s sender. To sign or verify the signature of a message, Mule uses one of the following two Digital Signature Strategies:

1. 2.

JCE Signer XML Signer As the sender of a message, use a digital signature when you want to advise the message’s receiver that you are a legitimate sender and that you vouch for all, or part, of its contents. Use the table below to determine which type of digital signature strategy best suits your security needs.

Digital Signature Strategy JCE Signer XML Signer

Characteristics ? sign a message payload, or part of a payload, using a key and algorithm ? sign a message payload, or part of a payload, using a keystore ? apply attributes to specify the type of algorithm, and type of signature

As the receiver of a message, use the digital signature feature when you need to verify the identity and confirm the legitimacy of its sender. Contents

Adding a Digital JCE Signature to a Message
As Mule’s default signature strategy, the Java Cryptology Extension (JCE) signer enriches a message payload with a digital signature.

This topic introduces the idea of Global Elements; if you are unfamiliar with this functionality, access Global Elements to learn more before proceeding.
At minimum, you must explicitly define the following:

? ?

a Global Signature element a Signature message processor in your Mule flow

Global vs. Local

To apply a digital signature to a message in Mule, you must use two elements, as described above: aSignature message processor in a Mule flow, and a Global Signature element to which the Signature message processor refers for configuration information.
Learn more... You can define the required configurations in either the Global Signature element or the local Signature message processor. Note, however, that you can only instruct Mule to use a key in a keystore via the configurations in the Global Signature element.

The following procedure describes how to apply JCE digital signatures to messages processed in a Mule flow.

? ?
1.

STUDIO Visual Editor

XML Editor or Standalone Add a global Signature message processor to your application, applying a unique Name for the element and keeping the default value, left).

JCE_SIGNER, in the Default Signer field (see image below,

2.

Click the JceSigner tab (see image below, right), then configure the message processor's attributes according to the table below. Note that while none of the attributes on the Jce Signer tab are required, this global element is the only place you can define a Keystore Path and Keystore Password for your Signature element.

Field Reference expression or

Req'd

Value If selected, in the Jce Signer Reference, use an expression to reference attributes you have defined elsewhere in the XML configuration of your applications, or to reference the configurations defined in a bean.

Define attributes Algorithm

If selected, enter values in the following five fields.

Algorithm to encrypt the key, not required if using a keystore. Refer to Appendix for list of available algorithms.

Key

Unique key that encrypts and decrypts message; or, if using keystore, the

Field

Req'd

Value name of the specific key within the keystore.

Keystore Path

Indicates the location (i.e. filepath) of the keystore file, required if using keystore.

Keystore Password Key Password

Password to access the keystore, required if using keystore.

Password to read the key within the keystore; required only if the specific keys within the keystore have their own passwords.

If you are using a Keystore, you must also define a Key to specify which key within the keystore the application should invoke. The key can be configured either on the Global Element Properties window or in the Pattern Properties window. ?
If configured in the Global Element Properties window, that key will be invoked for all message processors which refer to that global element — unless there is a different key specified in the local Pattern Properties window for that building block, because local configuration overrides global configurations.

?

If configured in the local Pattern Properties window, that key will be invoked only for that message processor, so any other message processors in the same flow that also refer to that global element would need a key configured in their Pattern Properties windows.

3. 4.

Add a Signature message processor to your flow. Configure the message processor's fields according to the table below.

Field Display Name Config Reference Operation Input Reference

Req'd x x

Value A unique name for your message processor. Use the name of the global element you created above.

x

Sign Identify the part of the message payload to which you want to apply the signature. This value must be in byte array format. By default, Mule signs the entire message payload.

Variable

Indicate the location in which Mule should store the signature which enriches the message.

Reference expression

or

If selected, in the Jce Signer Reference, use an expression to reference attributes you have defined elsewhere in the XML configuration of your applications, or to reference the configurations defined in a bean.

Define

If selected, enter values in the following three fields.

Field attributes Algorithm Key

Req'd

Value

Define an algorithm to encrypt the key, not required if using keystore. x Unique key that encrypts and decrypts message; or, if using keystore, the name of the specific key within the keystore.

Key Password

Password to read the key within the keystore; required only if the specific keys within the keystore have their own passwords.

Adding a Digital XML Signature to a Message
The XML signer enriches a message payload with a digital signature.

This topic introduces the idea of Global Elements; if you are unfamiliar with this functionality, access Global Elements to learn more before proceeding.
At minimum, you must explicitly define the following:

? ?

a Global Signature element a Signature message processor in your Mule flow You can define the required configurations in either the Global Signature element or the local Signature message processor. Refer to the Global vs. Local tip above for more information on how to apply configurations. Note, however, that you can only instruct Mule to use a key in a keystore via the configurations in the Global Signature element. The following procedure describes how to apply XML digital signatures to messages processed in a Mule flow.

? ?
1.

STUDIO Visual Editor

XML Editor or Standalone Add a global Signature message processor to your application, applying a unique Name for the element and change the default value, (see image below, left).

JCE_SIGNER, in the Default Signer field

to XML_SIGNER

2.

Click the XML Signer tab (see image below, right), then configure the message processor's attributes according to the table below. Note that while the Keystore Path and Keystore Password are

optional, this global element is the only place you can define a them for your Signature element.

Field Name Default Signer Reference Expression or

Req'd x x

Value A unique name for your global element. XML_SIGNER If selected, in the Jce Signer Reference, use an expression to reference attributes you have defined elsewhere in the XML configuration of your applications, or to reference the configurations defined in a bean.

Define Attributes Digest Algorithm Method x

If selected, enter values in the following nine fields. The algorithm Mule uses to encrypt the digest: RIPEMD160 SHA1 SHA256 (Default) SHA512

Canonicalization Algorithm

x

The algorithm Mule uses for XML canonicalization: EXCLUSIVE (Default) EXCLUSIVE WITH COMMENTS INCLUSIVE INCLUSIVE WITH COMMENTS

Field Signature Method Algorithm

Req'd x

Value The algorithm Mule uses to protect the message from tampering: RSA_SHA1 (Default) DSA_SHA1 HMAC_SHA1

Signature Type

x

Defines whether the signature applies to: ? data outside its containing document (DETACHED) ? a part of its containing document (ENVELOPED) (Default) ? data it contains within itself (ENVELOPING)

Reference Uri Key

External URI reference for messages with a Detached signature type. Unique key that encrypts and decrypts message; or, if using keystore, the name of the specific key within the keystore.

Keystore Path

Indicates the location (i.e. filepath) of the keystore file, required if using keystore.

Keystore Password

Defines the password to read the key stored in the keystore, required if using keystore.

Key Password

Password to read the key within the keystore; required only if the specific keys within the keystore have their own passwords.

If you are using a Keystore, you must also define a Key to specify which key within the keystore the application should invoke. The key can be configured either on the Global Element Properties window or in the Pattern Properties window. ?
If configured in the Global Element Properties window, that key will be invoked for all building blocks which refer to that global element — unless there is a different key specified in the local Pattern Properties window for that building block, because local configuration overrides global configurations.

?

If configured in the local Pattern Properties window, that key will be invoked only for that building block, so any other building blocks in the same flow that also refer to that global element would need a key configured in their Pattern Properties windows.

3. 4.

Add a Signature message processor to your flow. Configure the message processor's fields according to the table below.

Field Display Name Config Reference Operation Input

Req'd x x x

Value A unique name for your message processor. Use the name of the global element you created above. Sign xml Identify the part of the message payload to which you want to apply the signature. This value must be in byte array format. By default, Mule signs the entire message payload.

Key

x

Unique key that encrypts and decrypts message; or, if using keystore, the name of the specific key within the keystore.

Key Password

Password to read the key within the keystore; required only if the specific keys within the keystore have their own passwords.

Reference Uri Canonicalization Algorithm

External URI reference for messages with a Detached signature type. The algorithm Mule uses for XML canonicalization: EXCLUSIVE EXCLUSIVE WITH COMMENTS

Field

Req'd

Value INCLUSIVE INCLUSIVE WITH COMMENTS

Digest Algorithm

Method

The algorithm Mule uses to encrypt the digest: RIPEMD160 SHA1 SHA256 SHA512

Signature Method Algorithm

The algorithm Mule uses to protect the message from tampering: RSA_SHA1 DSA_SHA1 HMAC_SHA1

Signature Type

Defines whether the signature applies to: ? data outside its containing document (DETACHED) ? a part of its containing document (ENVELOPED) ? data it contains within itself (ENVELOPING)

Example of a Signed Payload
What follows are examples of a message payloads: one without a digital signature (below, top), and one with an XML digital signature (below, bottom). View the XML Without Digital Signature View the XML With Digital Signature

Signing Part of a Message Payload
By default, Mule signs the entire message payload when you apply a signature. However, you can use a Mule Expression to sign a specific part of a message payload rather than the whole payload. Enter a Mule expression in the Input Reference field of a JCE or XML Signature message processor to define the specific part(s) of the payload you wish to sign.

Applying a Signature Using MEL
As described above, to apply a digital signature to a message in Mule, you normally need two ingredients:

? ?

a Global Signature element which defines all, or some, of the signature attributes a Signature message processor in a Mule flow which defines all, or some, of the signature attributes However, you can also add a signature to a message without adding a Signature message processor to a Mule flow. To do so, you need:

? ?

a Global Signature element which defines all of the signature attributes a Mule expression appended to a message processor as message attribute, which references the Global Signature element to apply a signature to the message To reference a Global Signature element via Mule expression in another element, you must first set the Global Signature element'sEnable Language attribute to true (below, left), then apply all the Global Signature attributes (below, right).

? ?

STUDIO Visual Editor

XML or Standalone Editor

Then, add a message attribute to an element in your flow, a Logger, for example, to apply a digital signature according to the configurations in the Global Signature element.

? ?

STUDIO Visual Editor

XML or Standalone Editor

Verifying a Digital Signature
In addition to signing a message, Mule also uses a Signature message processor to verify the identity of a message’s sender as legitimate. Where Mule discovers an invalid signature, it discards the message, processing it no further. Mule verifies the signature on the message payload according to the configurations of any of the optional attributes if explicitly defined (see lists above for JCE- and XML-specific attributes).

This topic introduces the idea of Global Elements; if you are unfamiliar with this functionality, access Global Elements to learn more before proceeding.
To verify JCE or XML signatures on messages in a Mule flow, you must, at minimum, create:

? ?

a Global Signature element a Signature message processor in your Mule flow The following procedure describes how to verify digital signatures on messages a Mule flow receives.

1.

In your Mule flow, add a Signature message processor early in your flow in Studio to verify signatures on messages that arrive to be processed.

2.

In the Operations field, select Verify

Signature. Alternatively, add a Signature element

to your flow, configured to verify signatures (see code, below).

<signature:verify-signature config-ref="" doc:name="Signature"/>
3. Use the Using field (or using attribute in XML) to indicate the type of signature: JCE_SIGNER or XML_SIGNER.

4.

Optionally, enter a Mule expression in the Input Reference field to indicate the part of the message payload to which the signature applies. In other words, a signature may apply to only part of the message payload.

5.

In the Expected Signature field, enter a Mule expression that Mule can use to compare and verify that the signature on a message it received is authentic.

6.

Configure any other attributes of the local Signature message processor. Refer to the JCE Signer and XML Signer sections above for attribute configuration details. Also, refer to the Global vs. Local tip to decide which attributes to configure locally, on the Signature message processor, and which attributes to configure in the Global Signature element.

7.

Configure any other attributes of a Global Signature element. Again, refer to the JCE Signer and XML Signer sections above for attribute configuration details.

8.

Configure the Signature message processor to reference the Global Signature element.

<signature:config name="Signature" enableLanguage="true" doc:name="Signature"> </signature:config> ... <flow name="Get_CC_information" doc:name="Get_CC_information"> <signature:verify-signature <set-payload doc:name="Set Payload"/> </flow> config-ref="Signature"

<signature:jce-signer-config algorithm="HmacMD5" key="JLfl5sER3kt4oVkzP2d39UQrUxrE

<http:inbound-endpoint exchange-pattern="request-response" host="localhost" po doc:description="Verify if the Signature is correct, so we can validate the User"/> value="#[new

input-ref="#[message.i

Canada&lt;/name&gt;&lt;id&gt;Royal_Bank_Of_Canada&lt;/id&gt;&lt;cc&gt;&lt;company&gt;

<encryption:encrypt config-ref="plainXml" doc:name="Encrypt the XML (only th C

Next Steps
Examine the Anypoint Enterprise Security Example Application which illustrates how to verify the digital signature of a message.

Appendix
JCE Signer Available Algorithms

JCE Signer Available Algorithms HmacMD5 HmacSHA1 HmacSHA256 HmacSHA384 HmacSHA512 MD2WithRSAEncryption MD4WithRSAEncryption MD5WithRSAEncryption RIPEMD128WithRSAEncryption RIPEMD160WithRSAEncryption RIPEMD256WithRSAEncryption SHA1WithRSAEncryption SHA224WithRSAEncryption SHA256WithRSAEncryption

Mule Filter Processor
Generally positioned immediately after an inbound connector in a Mule flow, the Mule Filter Processor evaluates two message properties, then rejects the message if the values fall outside of its configured parameters. The properties that are evaluated are:

?

IP address – If the IP address of a message falls outside the filter’s configured IP address range, Mule does not process the message (see image below).

?

Creation timestamps — Where the message’s creation date and time fall outside the filter’s configured acceptable lifespan (i.e. the message is older than expected), Mule does not process the message (see image below).

Contents

Configuring the Mule Filter Processor
Use a Mule Filter Processor to protect a network, database, or system from unauthorized access by users outside the network. In other words, use a filter to exclude users from non-authorized IP addresses from accessing your system. Further, use a security filter to protect your resource against a replay attack. By rejecting messages with a lifespan that exceeds a short timeframe — 30 seconds, for example — Mule protects your application from processing the same message a user maliciously sends multiple times. To be effective, a Mule flow should employ a digital signature, in addition to this type of security filter, to sign the creation time of the message. This topic introduces the idea of Global Elements; if you are unfamiliar with this functionality, access Understand

Global Mule Elements to learn more before proceeding. ? ?
STUDIO Visual Editor

XML Editor or Standalone

The following steps describe how to configure the Mule Filter Processor to filter by IP address range. 1. Add a global Filter Element to your application, apply a unique Name to the element, the only attribute to configure. 2. Place a Filter message processor in your flow, typically positioned after an inbound connector, such as HTTP, so as to filter out invalid messages early in the flow. 3. Configure the message processor according to the table below.

Field Display Name Config Reference Operation Regex

Req'd x x

Value A unique name for your message processor. Use the name of the global element you created above.

x

Filter by ip Enter a regex expression to apply further rules for filtering messages based on the IP address range.

Filter Strategies
The Mule Filter processor allows you to filter messages according to the following four filter strategies:

Operation Filter IP by

Description Type an IP address or regular expression to define the address or range from which the Filter will accept connections.

Example Regex:192.168.1.10, 192.168.1.* (to allow the range from 1.0 to 1.254)

Filter

by

Enter a net address and mask to determine the IP range. The IP addresses or ranges you enter will be

Net: 192.168.1.0 Mask: 255.255.255.0

IP range

considered valid, and allowed by the Filter. Filter IP by Enter the desired IP range in CIDR notation. Cidr: 192.168.1.0/24

range

CIDR Filter expired This option allows you to define an expiration time for the message. Date Time: #[variable:timestamp] Expires in: 30000

?

To define an expiration time based upon the time a message entered the flow, enter a Mule Expression to call a variable that provides this date and time in ISO 8601 format Date Time: (yyyy-MM-dd'T'hh:mm:ssZ), and an #[payload.createdAt] expiration time in milliseconds. (Earlier in the flow, you will need to name and define this variable so that it extracts the date and time information from your message's metadata.) The expiration time will be calculated based on the timestamp extracted from the message, and the filter will discard messages received after that expiration time. Expires in: 30000

?

To define an exact date and time after which messages should expire, enter a date and time in ISO 8601 format (yyyy-MM-dd'T'hh:mm:ssZ), and an expiration time in milliseconds. The expiration time is calculated from the precise date and time you enter, and the filter will discard messages received after that expiration time.

Mule CRC32 Processor

Mule can apply a cyclic redundancy check (CRC) to messages to ensure integrity. The CRC32 processor acts as an enricher to generate a checksum to a message when it enters a system, then act as a filter to verify the checksum when the message leaves the system. If the entry and exit values do not match, CRC terminates the message's processing. The CRC32 processor allows the user to verify that a message remains intact between a sender and a receiver. Because it does not itself provide encryption or append a signature to the message, you can use it in conjunction with other security features to provide an additional level of confidence in the authenticity of a message. Contents

? ?

Generating a Checksum Verifying a Checksum

Generating a Checksum
This topic introduces the idea of Global Elements; if you are unfamiliar with this functionality, access Global
Elements to learn more before proceeding. To use the CRC32 processor to generate a checksum on a message, you must, at minimum, configure two elements in your Mule application:

? ?

a global CRC32 element a CRC32 processor Completing these steps ensures that Mule calculates a checksum based on your payload and enriches the properties of your Mule message with that checksum.

Creating a Global Element
? ?
1.

STUDIO Visual Editor

XML Editor or Standalone Create and configure the global element through the Global Element tab at the bottom of the canvas, or directly within the CRC32 building block's Properties pane by clicking the of the Connector Ref field. icon to the right

2.

Configure the global element's attributes according to the table below.

Attribute Name Target Expression

Req'd x x

Value A unique name for your global element. A Mule expression, accept the default variable

name #[variable:crc32]

Configuring a CRC32 Message Processor
? ?
1. 2.

STUDIO Visual Editor

XML Editor or Standalone Insert a CRC32 processor in your Mule flow. Configure the message processor's attributes according to the table below.

Attribute Display Name Config Reference Operation Input Reference

Req'd x

Value A unique name for your message processor.

x

Use the global element you created above.

x

Calculate By default, Mule calculates based on the entire payload. Use the Input Reference field to specify a different target for the calculation, if necessary.

Verifying a Checksum
To use the CRC32 processor to verify a checksum on a message, you must, at minimum, configure two elements in your Mule application:

? ?

a CRC32 message processor a CRC32 global element Completing these steps ensure that Mule verifies the checksum in the properties of your message by comparing it against the checksum you calculated in the CRC32 calculation, above.

Configuring a CRC32 Message Processor
?

STUDIO Visual Editor

?
1.

XML Editor or Standalone Insert a CRC32 processor into your Mule flow, positioned at the point where you would like to verify the checksum.

2.

Configure the message processor's attributes according to the table below.

Attribute Display Name Config Reference

Req'd x x

Value A unique name for your message processor. Create a "blank" global element satisfies Anypoint Studio's configuration requirements and needs no further configuration.

a. b.

Click the

icon next to the Config Reference field.

Delete the default text in the Target Expression field, leaving this field blank, then click OK.

Operation Expected Checksum

x x

CRC32 Filter Enter the Expected Checksum, matching the contents of the Target Expression field in the CRC32 global element in your configuration of the CRC32 calculation.

Input Reference

By default, Mule calculates based on the entire payload. Use the Input Reference field to specify a different target for the calculation, if necessary.

Anypoint Enterprise Security Example Application
Designed as a simple demo, this example application offers some insight into how to use two Anypoint Enterprise Security features: Mule Digital Signature Processor and Mule Message Encryption Processor. The demo illustrates how to complete the following tasks with Mule:

? ? ?

verify a digital signature encrypt part of a message payload decrypt a message payload Contents

? ? ? ? o o o ?

Assumptions Importing the Application Setting Up, Then Running the Application How it Works Get_CC_Information Flow Decrypt_The_Request Flow Get_secret_file Flow Go Further

Assumptions
This document assumes that you have installed the Anypoint Enterprise Security extensions. It also assumes you are familiar with the Anypoint Studio interface. To increase your familiarity with Studio, consider completing one or more Anypoint Studio Tutorials. This document describes the details of the example within the context of Anypoint Studio, Mule ESB’s graphical user interface (GUI). Where appropriate, the XML configuration follows the Studio interface screenshot.

Importing the Application
1. 2. 3. 4. Download the Anypoint Enterprise Security Example Application. Launch Anypoint Studio. Under the File menu, select Import... Studio opens an Import wizard. Expand the Mule folder in the wizard, then select Anypoint Studio generated Deployable Archive (.zip). Click Next.

If your operating system automatically unzipped the application, select Anypoint Studio Project from External Location instead of Anypoint Studio generated Deployable Archive (.zip) .
5. Use the ellipsis button (. . .) next to the Zip File field to browse for, then select, the Mule application you downloaded:anypoint-enterprise-security-example.zip. 6. Click Finish. Studio imports, then opens the project.

Setting Up, Then Running the Application
1. In the anypoint_enterprise_security_example project, scroll down the Studio canvas to the Get_secret_file flow. 2. 3. Double-click the Groovy component to open its Pattern Properties panel. In the Script Text field, adjust the filepath of the filepath, then click OK to save your change. 4. 5. 6. Click the Save icon in Studio to save the project. In the Package Explorer, right-click the project name, then select Run As > Mule Application. Mule runs the application. In the console, it displays the following message: Started

encrypted.txt file to match your system’s

anypoint_enterprise_security_example app

How it Works
The Encrypted Message Producer application consists of three simple flows, each of which acts as a Web service provider which encrypts or decrypts a message before returning a response to the caller. Organized according to function, these flows serve different purposes within the application.

?

Get_CC_information receives Web service requests for a customer’s credit card information, which it retrieves, encrypts, then returns to the caller. (See image below, top.)

?

Decrypt_The_Request decrypts messages it receives, logs the decryption activity, then returns the unencrypted message contents — in this case, credit card information — to the caller. (See image below, middle.)

?

Get_secret_file decrypts, upon request, the contents of a file, then returns a response to the caller that displays the decrypted contents of the file. (See image below, bottom.)

View the XML

The sections below offer descriptions of the Anypoint Enterprise Security features’ actions as each flow processes end user requests.

Get_CC_Information Flow
Requesting
From a browser, an end user submits a request via the URL to the Mule application to acquire a customer’s credit card information. To submit this request, open your browser and type the following in the address bar:

http://localhost:8081/?user=Royal_Bank_of_Canada&token=z/TKVFswDDOQw2 kjW9Y4jQ==
Processing
Upon receipt of an HTTP request, this flow uses a Mule Digital Signature Processor to verify the identity of the message’s sender. Mule evaluates the token it receives as a parameter o f the request (i.e. the token in the URL of the request). The table below describes the configurations of the Digital Signature Processor.

Config Reference Operation Input Reference

references the Signature global digital signature element indicates that the element verifies a signature, rather than apply a signature uses a Mule Expression to define the part of the payload to which the digital signature applies

Expected Signature

uses a Mule Expression to define the parameter Mule uses to verify the signature

<signature:verify-signature input-ref="#[message.inboundProperties['user']]" expectedSignature="#[message.inboundProperties['token']]" User"/>
What is a Global Element?

config-ref="Signature" doc:name="Verify User

Signature" doc:description="Verify if the Signature is correct, so we can validate the

Mule ESB uses Global Elements, like the Signature global element in this example, to specify transport details and set reusable configurations. Rather than repeatedly write the same code to apply the same configuration to multiple message processors, you can create one global element that details your configurations or transport details. Then, you can instruct any number of message processors in your Mule application to reference that global element.
Learn more... View the XML for Global Signature Element

After verifying that the requester is valid, Mule uses an expression to set the payload of the message to bank and credit card information. (This function is a simple way to simulate the action of retrieving a customer’s credit card information from a database. For practical reasons in this example, the credit card details are hard-coded into the application.) Rather than returning the raw credit card information to the caller, Mule first encodes it using a Mule Message Encryption Processor. Using an XML encryption strategy, Mule encrypts the message payload. The table below describes the configurations of the encrypter.

Config Reference Operation Input Reference Using

references the plainXML global encryption element indicates that the element encrypts, rather than decrypt a message instructs Mule to encrypt the payload and display as a string indicates the encryption strategy

<encryption:encrypt config-ref="plainXml" doc:name="Encrypt the XML (only th CC Info)" using="XML_ENCRYPTER" input-ref="#[payload.toString()]"/>

The Message Encryption Processor references the plainXML global encryption element to behave according to the following configurations:

? ? ?

Enable Language key (i.e. encryption key) xpath expression which indicates the fields in the payload to encrypt

?

algorithm (i.e. encryption algorithm)

<signature:config name="Signature" enableLanguage="true" doc:name="Signature"> <signature:jce-signer key="JLfl5sER3kt4oVkzP2d39UQrUxrEK63LjmXAO45b6cU="/> </signature:config> algorithm="HmacMD5"

Responding
Finally, Mule uses the HTTP connector to pass the response — encrypted credit card information — to the end user’s browser. The highlighted content in the image below provides the encrypted credit card information.

Decrypt_The_Request Flow
Requesting
An end user submits a request to the Mule application to decrypt the message payload in order to acquire a customer’s unencrypted credit card information. Use an HTTP Request tool (such as the REST Console plugin in the Chrome Web browser) to POST the request below to http://localhost:8081/decrypt

<?xml version="1.0" encoding="UTF-8"?> <user><name>Royal Bank of xmlns:xenc="http://www.w3.org/2001/04/xmlenc#"><xenc:EncryptionMethod <xenc:EncryptedKey

Canada</name><id>Royal_Bank_Of_Canada<

xmlns:xenc="http://www.w3.org/2001/04/xmlenc#"/><ds:KeyInfo xmlns:ds="http://www.w3.org/2000/09/xml xmlns:xenc="http://www.w3.org/2001/04/xmlenc#"/><xenc:CipherData xmlns:xenc="http://www.w3.org/2001/04/xmlenc#"><xenc:CipherValue

xmlns:xenc="http://www.w3.org/2001/04/xmlenc#"><xenc:Encry

xmlns:xenc="http://www.w3.org/2001/04/xmlenc#">9eUu9/kVzwb4ExPxr2UTiugRKoU6oJE9</xenc:Cipher

xmlns:xenc="http://www.w3.org/2001/04/xmlenc#">cUmSEUP5M/OJsIS9MQvX3tMPBk9MgEo1yu2yGDc8swPVu

5jU4hTz3eJXqd3AVkvTsWA/3d79yoY/c1CyOiTenlSw38+kHQ+JR</xenc:CipherValue></xenc:CipherD

Processing
After accepting an HTTP request from and end user, Mule converts the message payload from a Java object to a string, then employs a Mule Message Encryption Processor to decrypt the message payload. Using an XML encryption strategy, Mule decrypts the message payload before logging the decryption activity. Mule then returns a response to the caller, which contains the unencrypted credit card data. The table below describes the configurations of the decrypter.

Config Reference Operation Encrypter to use

references the plainXML global encryption element indicates that the element decrypts, rather than encrypt a message indicates the encryption strategy

<encryption:decrypt config-ref="plainXml" using="XML_ENCRYPTER" doc:name="Decrypt the xml payload"/>

The Message Encryption Processor references the plainXML global encryption element to behave according to the following configurations:

? ? ? ?

Enable Language key (i.e. encryption key) xpath expression which indicates the fields in the payload to decrypt algorithm (i.e. encryption algorithm)

Responding
Finally, Mule uses the HTTP connector to pass the response — decrypted credit card information — to the end user’s browser. The code below displays the unencrypted credit card information.

<?xml

version="1.0"

encoding="UTF-8"?><user><name>Ro

Canada</name><id>Royal_Bank_Of_Canada</id><cc><company>Visa</company><number>12345678

Get_secret_file Flow
Requesting
From a browser, an end user submits a request via the URL to the Mule application to decrypt the contents of a particular file, then display the decrypted contents to the user. To submit this request, open your browser and type the following in the address bar:

http://localhost:8081/getFile?user=Royal_Bank_of_Canada&token=z/TKVFs wDDOQw2kjW9Y4jQ==
Processing
Upon receipt of an HTTP request, this flow, in a manner very similar to the Get_CC_Information flow, uses a Mule Digital Signature Processor to verify the identity of the message’s sende r. Next, Mule uses a Groovy script to locate the file that contains the data to decrypt (in this case, the encryption.txt file in the src > test> resources folder). It then passes the file content to the Mule Message Encryption Processor to decrypt. The processor references the symmetricPlain global encryption element for directions on how to decrypt the file’s contents. ThesymmetricPlain element uses the JCE encryption strategy (as indicated by the BINARY_ENCRYPTER selection in the Default field), provides the encryption key, and defines the encryption algorithm.

Responding
Finally, Mule uses the HTTP connector to pass the response — the decrypted message in the encrypted.txt file — to the end user’s browser (see image below).

Go Further
? ?
For more information on encryption in Mule, refer to Mule Message Encryption Processor. For more information on signatures in Mule, refer to Mule Digital Signature Processor.

Mule STS OAuth 2.0a Example Application
Contents

? ? ? ? ? ? ?

Assumptions Importing, then Running the Applications Witness the Working Example Shutting Down the Mule Server How It Works OAuth 2.0a Configuration in Tweetbook Related Materials This example Mule application behaves as a Web service provider offering its API to an external consumer.

Assumptions
This document assumes that you are familiar with the Anypoint Studio interface. To increase your familiarity with Anypoint Studio, consider completing one or more Anypoint Studio Tutorials.

Importing, then Running the Applications
Two for One

The Mule STS OAuth 2.0a Example Application consists of two applications: ? ?
one that acts as the Web service provider (Tweetbook) one that acts as the Web service consumer (Bookstore).

To examine a functional example, you must import and run both the Tweetbook and Bookstore applications, the former in Anypoint Studio, the latter in Mule ESB Standalone. To demonstrate the functionality of OAuth 2.0a as it applies to a Web service provider, in this document we

examine only the details of the Tweetbook application.

Import and Run Bookstore
1. If you do not already have Mule ESB Enterprise Standalone installed on your system, download Mule ESB Enterprise trial Runtime. 2. Download the Mule Bookstore application from the following link: Mule Bookstore 3. Navigate to your downloads folder, then unpack the bookstore-oauth2-consumer.zip file you downloaded. 4. Copy the unpacked folder bookstore-oauth2-consumer to <MULE_HOME>/apps

<MULE_HOME> is the value of the MULE_HOME variable employed by MULE ESB, usually the root
directory of the Mule ESB installation, such as
5. Start Mule. Need more detail? For Unix/Linux: Need more detail? For Windows: After it starts, Mule polls the apps folder every 5 seconds. When you copy the bookstore-oauth2-consumer application to the folder, Mule detects it and deploys it automatically. In the command line, Mule notifies you that it has deployed the application. ********************************************************************** * - - + APPLICATION + - * - - + STATUS + - - *

/opt/Mule/mule-standalone-3.3.1/.

********************************************************************** * bookstore-oauth2-consumer-1 * mmc * default * 00_mmc-agent * DEPLOYED * DEPLOYED * DEPLOYED * DEPLOYED * * * *

**********************************************************************

INFO

2012-10-29 15:40:57,516 [WrapperListener_start_runner]

org.mule.module.launcher.DeploymentService: ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ + Mule is up and kicking (every 5000ms) +

++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

Import and Run Tweetbook
1. Download the Mule Tweetbook application from the following link: Tweetbook 2. Navigate to your downloads folder, then uncompress the tweetbook-oauth2-provider.zip file you downloaded. 3. 4. 5. Launch Anypoint Studio. Under the File menu, select Import... In the Import wizard, expand the Mule folder, then select Anypoint Studio Project from External Location, then click Next. 6. In the Project Root field, use the ellipsis (. . .) button to navigate to your downloads folder, then select the tweetbook-oauth2-provider folder. 7. Click Finish to initiate import. Studio opens the tweetbook-oauth2-provider project and displays the application in the canvas. 8. In the Package Explorer, right-click the project name, then select Run As > Mule Application.

Studio may display a benign warning that reads:

Errors exist in required project(s): tweetbook-oauth2-provider Proceed with launch?
Click OK to proceed. Studio should launch and run the Tweetbook application without issue.
9. Studio runs the application, displaying its activities in the Studio console.

Witness the Working Example
With both the Bookstore and Tweetbook applications running, complete the following steps to experience the example applications' behavior as though a Bookstore user. 1. To access the Bookstore website in your browser, go to the following URL: http://localhost:8085/bookstore

2. 3.

Click the Your Tweetbook Account link to sign in with Tweetbook. Bookstore opens a Tweetbook login in window.

4.

In the Username and Password fields, enter the following login credentials:

? ?

username = john password = doe

Notice that on this page, Tweetbook not only requests your login credentials, but simultaneously requests your permission, as the user, to share read-only access to

yourPROFILE and BOOKSHELF. Tweetbook could have requested user login, then requested permission to share data, but in this case, Tweetbook combines both requests in one user activity.
5. 6. Click Login and Authorize. Tweetbook grants the Bookstore application access to your profile and bookshelf data. Bookstore imports the data, then logs you into your new user account on Bookstore. Then, Bookstore displays the contents of your Tweetbook bookshelf.

Shutting Down the Mule Server
To stop Mule ESB from running via the command line, execute the command <MULE_HOME>/bin/mule

stop

Note for Unix/Linux Users

If the Mule process is attached to the terminal (run as a foreground process), the command <MULE_HOME>/bin/mule

stop must be executed in a separate command line window. If,

however, the Mule process has been detached from the terminal (if you started the Mule server with the <MULE_HOME>/bin/mule

start command, then you can execute the stop from any terminal window.

command <MULE_HOME>/bin/mule

How It Works
The Web service provider is a Mule application called Tweetbook. Tweetbook users keep a list of books they have read in a virtual library in their account, and can share their library and reviews with other Tweetbook users in a readers’ social network.

Bookstore is an online retailer of books. End users who wish to purchase books and who are Tweetbook users can choose to create a Bookstore account using their Tweetbook account credentials. Should a user decide to use their Tweetbook account to create an account with Bookstore, Tweetbook will share the user’s virtual library with Bookstore. Users can then consult their Tweetbook library before purchasing new books. Tweetbook has offered its API to Bookstore and is prepared to provide read-only access to users’ profiles and virtual bookshelves. The table below describes the OAuth entities within the context of this example.

Access Credentials Resource Owner Protected Resource Service Provider Consumer Token Scope

login credentials to Tweetbook the end user the end user’s account with Tweetbook Tweetbook Bookstore token read-only access to the end user's profile and list of books in the virtual library

The following sections describe the OAuth dance that occurs between the service provider and consumer, and offer insight into how the Tweetbook Mule application is configured to behave as an OAuth service provider.

The OAuth Dance
1. Before they can dance, the consumer and service provider must set the following parameters:

? ?

The service provider must define itself as an OAuth 2.0a service provider. The consumer must register its Client ID with the provider. (The service provider stores the IDs of registered consumers in its object store.)

2.

On the Bookstore’s website, the end user — a Tweetbook account holder — decides to create a new account using his Tweetbook account credentials. The user clicks on the ―Sign in with Tweetbook!‖ link that Bookstore makes available for this purpose.

3.

Tweetbook and Bookstore use the Authorization Code grant type to perform the OAuth dance. The Bookstore directs the user to a URL to log in to his Tweetbook account. In this step, Bookstore calls Tweetbook’s authorization server and provides its client ID (so Tweetbook knows which consumer is asking to dance). The user enters his Tweetbook login credentials. When he clicks Login and Authorize, he not only accesses his Tweetbook account, he also authorizes Tweetbook to share read-only access of his profile and bookshelf with Bookstore. Tweetbook sends Bookstore an authorization code.

4.

Bookstore calls Tweetbook’s authorization server again to request permission to access the protected resource (the user's Tweetbook account). Bookstore provides its authorization code, client ID and client secret.

5.

Tweetbook grants permission to access the protected resource by providing a token. Within the token, it defines the scope (i.e. specific data) which Bookstore may access. In this case, the scope is read-only access to the user’s profile and virtual bookshelf.

6.

Bookstore calls Tweetbook’s resource server to request the user’s protected resource. It offers the token Tweetbook provided as both proof of its identity and its authorization to acquire the resource.

7.

Tweetbook accepts the token, then gives Bookstore the use r’s profile and bookshelf information.

8.

Bookstore allows the user to enter his new account where his virtual bookshelf is pre-populated with the list of books in his Tweetbook account.

Authorization Grant Type
There are four ways that a consumer can obtain authorization to dance with an OAuth service provider. 1. 2. 3. 4. Authorization Code Implicit Resource Owner Password Credentials Client Credentials This example application uses the Authorization Code grant type which, as described above, involves a multi-step process to authorize sharing of a protected resource. For a service provider, this grant type involves the use of both an authorization server (responsible for confirming and granting permission to access the protected resource) and a resource server (responsible for providing access to the protected resource). A consumer must ask for a service provider’s permission to ask for protected resources — like a suitor asking a chaperone’s permission to ask a woman to dance. If the chaperone (authorization server) grants permission to ask, the suitor (consumer) may then ask the woman (resource server) to dance. Refer to Authorization Grant Types for more information on the other types of authorization grants.

OAuth 2.0a Configuration in Tweetbook
This section describes the details of the example within the context of Anypoint Studio, Mule ESB’s graphical user interface (GUI). The XML configuration follows the Studio interface screenshot in an expandable section. The Tweetbook application uses the Mule Secure Token Service to apply OAuth 2.0a to the API it exposes. By including the OAuth2 message processor in the Web service’s flow, Tweetbook defines

itself as an OAuth2 service provider and enables Mule to perform the OAuth dance with consumers.

View the XML

Related Materials
?
For more information on OAuth 2.0a in Mule, refer to Mule Secure Token Service.

Configuring Security
Mule ESB allows you to authenticate requests via connectors using transport-specific or generic authentication methods. It also allows you to control method-level authorization on your components. The Security Manager is responsible for authenticating requests based on one or more security providers.

For information on the elements you can configure for the Security Manager, see Security Manager Configuration Reference. The following sections provide links to information on configuring different types of security managers.

New Anypoint Enterprise Security Features

In addition to the security features described on this page, Mule offers six new security features: ? ? ? ? ? ?
Mule Secure Token Service (STS) OAuth 2.0a Provider Mule Credentials Vault Mule Message Encryption Processor Mule Digital Signature Processor Mule Filter Processor Mule CRC32 Processor

For more information on these features and instructions for downloading them, see Anypoint Enterprise Security.

Spring Security 3.0
Spring Security is the next version of Acegi and provides a number of authentication and authorization providers such as JAAS, LDAP, CAS (Yale Central Authentication service), and DAO. The following topics will help you get started securing your flows using Spring Security:

? ? ?

Configuring the Spring Security Manager Component Authorization Using Spring Security Setting up LDAP Provider for Spring Security

WS-Security and SAML
WS-Security is a standard protocol for applying security to Web services. It contains specifications on how integrity and confidentiality in a SOAP message can be enforced via XML signatures and binary security tokens such as X.509 certificates and Kerberos tickets as well as encryption headers. It ensures end-to-end security by working in the application layer as opposed to the transport layer. Mule provides the following resources for WS-Security:

?

Enabling WS-Security - Describes how to secure your CXF connectors with WS-Security.

?

SAML Module - Mule now supports the SAML standard for exchange of security information between systems. This module is available in the enterprise edition of Mule as of version 2.2.3

Other Security Integration
Mule also supports the following security technologies:

? ? ?

Encryption Strategies - Secure your messages by encrypting them. PGP Security - Secure your messages by encrypting them with PGP. Jaas Security

Configuring the Spring Security Manager
? ?
Example Security Filters Use Spring Security 3.0 as a Security Manager inside of Mule. You can use any of the library's security providers such as JAAS, LDAP, CAS (Yale Central Authentication service), and DAO. For more information on the elements you can configure for a Mule security manager, see Security Manager Configuration Reference.

Example
The following example illustrates how to configure a single security provider on Mule, in this case an in-memory database of users. To configure the provider, we set up a the <authentication-manager> to which Mule delegates.

<user-service> element and

<?xml version="1.0" encoding="UTF-8"?> <mule xmlns="http://www.mulesoft.org/schema/mule/core" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:spring="http://www.springframework.org/schema/beans" xmlns:http="http://www.mulesoft.org/schema/mule/http" xmlns:mule-ss="http://www.mulesoft.org/schema/mule/spring-security" xmlns:ss="http://www.springframework.org/schema/security" xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-current.xsd http://www.mulesoft.org/schema/mule/core http://www.mulesoft.org/schema/mule/core/3.1/mule.xsd

http://www.mulesoft.org/schema/mule/http http://www.mulesoft.org/schema/mule/http/3.1/mule-http.xsd http://www.mulesoft.org/schema/mule/spring-security http://www.mulesoft.org/schema/mule/spring-security/3.1/mule-spring-security.xsd http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.0.xsd">

<mule-ss:security-manager> <mule-ss:delegate-security-provider delegate-ref="authenticationManager" /> </mule-ss:security-manager> <spring:beans> <ss:authentication-manager alias="authenticationManager"> <ss:authentication-provider> <ss:user-service id="userService"> <ss:user name="ross" password="ross" authorities="ROLE_ADMIN" /> <ss:user name="anon" password="anon" authorities="ROLE_ANON" /> </ss:user-service> </ss:authentication-provider> </ss:authentication-manager> </spring:beans> ...cut... </mule> name="memory-provider"

Security Filters
Security filters can be configured on an object to either authenticate inbound requests or attach credentials to outbound requests. For example, to configure an HTTP basic authorization filter on an HTTP connector, you would use the following connector security filter:

<inbound-endpoint address="http://localhost:4567"> <mule-ss:http-security-filter realm="mule-realm"/> </inbound-endpoint>
When a request is received, the authentication header will be read from the request and authenticated against all security providers on the Security Manager. If you only want to validate on certain ones, you can supply a comma-separated list of security provider names.

<inbound-endpoint address="http://localhost:4567">

<mule-ss:http-security-filter securityProviders="default,another"/> </inbound-endpoint>
The realm is an optional attribute required by some servers. You only need to set this attribute if required by the server on the other end.

realm="mule-realm"

Component Authorization Using Spring Security
? ?
Securing Flow Components Setting Security Properties on the Security Provider This page describes how you can configure method-level authorization using Spring Security on your components so that users with different roles can only invoke certain methods.

Securing Flow Components
To secure MethodInvocations, you must add a properly configured MethodSecurityInterceptor into the application context. The beans requiring security are chained into the interceptor. This chaining is accomplished using Spring's ProxyFactoryBean orBeanNameAutoProxyCreator. Alternatively, Spring Security provides a MethodDefinitionSourceAdvisor, which you can use with Spring'sDefaultAdvisorAutoProxyCreator to automatically chain the security interceptor in front of any beans defined against theMethodSecurityInterceptor. In addition to the daoAuthenticationProvider and inMemoryDaoImpl beans (see Configuring Security), the following beans must be configured:

? ? ? ? ?

MethodSecurityInterceptor AuthenticationManager AccessDecisionManager AutoProxyCreator RoleVoter The MethodSecurityInterceptor
The MethodSecurityInterceptor is configured with a reference to the following:

? ?

AuthenticationManager AccessDecisionManager

Following is a security interceptor for intercepting calls made to the methods of a component myComponent, which defines two methods: delete and writeSomething. Roles are set on these methods as seen below in the property

securityMetadataSource.

<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mule="http://www.mulesource.org/schema/mule/core" xmlns:mule-ss="http://www.mulesource.org/schema/mule/spring-security" ...cut... <bean

id="myComponentSe

class="org.springframework.security.access.intercept.aopalliance.MethodSecurityInterc <property name="authenticationManager" ref="authenticationManager"/> <property name="accessDecisionManager" ref="accessDecisionManager"/> <property name="securityMetadataSource"> <value> com.foo.myComponent.delete=ROLE_ADMIN com.foo.myComponent.writeSomething=ROLE_ANONYMOUS </value> </property> </bean>
Note: Because of a limitation in Spring, you must refer to the component implementation and not the interfaces it implements when defining the security bean.

The AuthenticationManager
This bean is responsible for passing requests through a chain of AuthenticationProvider objects.

<bean <property name= "providers"> <list> <ref local="daoAuthenticationProvider"/> </list> </property> </bean>

id="authenticationManager"

class="org.springframework.security.authentication.ProviderManager">

The AccessDecisionManager
This bean specifies that a user can access the protected methods if they have any one of the roles specified in thesecurityMetadataSource.

<bean <property name="decisionVoters"> <list> <ref bean="roleVoter"/> </list> </property> </bean> The AutoProxyCreator

id="accessDecisionManager"

class='org.springframework.security.access.vote.AffirmativeBased'>

This bean defines a proxy for the protected bean. When an application asks Spring for a myComponent bean, it will get this proxy instead.

<bean <property name="interceptorNames"> <list> <value>myComponentSecurity</value> </list> </property> <property name="beanNames"> <list> <value>myComponent</value> </list> </property> <property name='proxyTargetClass' value="true"/> </bean>
When using BeanNameAutoProxyCreator to create the required proxy for security, the

id="autoProxyCreator"

class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator">

configuration must contain the propertyproxyTargetClass set to true. Otherwise, the method passed to MethodSecurityInterceptor.invoke is the proxy's caller, not the proxy's target.

The RoleVoter
The RoleVoter class will vote if any ConfigAttribute begins with ROLE_. The RoleVoter is case sensitive on comparisons as well as the

ROLE_ prefix. GrantedAuthority, which returns a String

?

It will vote to grant access if there is a

representation (via the getAuthority()method) exactly equal to one or more ConfigAttribute objects starting with ROLE.

?

If there is no exact match of any ConfigAttribute starting with ROLE_, the RoleVoter will vote to deny access.

?

If no ConfigAttribute begins with ROLE_, the voter will abstain.

<bean id="roleVoter" class="org.springframework.security.access.vote.RoleVoter"/>

Setting Security Properties on the Security Provider
You can add any additional properties to the security provider in the following:

securityProperties map. For

example, this map can be used to change Spring Security's default security strategy into one of the

?

MODE_THREADLOCAL: allows the authentication to be set on the current thread (this is the
default strategy used by Spring Security)

?
thread

MODE_INHERITABLETHREADLOCAL: allows authentication to be inherited from the parent MODE_GLOBAL: allows the authentication to be set on all threads Securing Components in Asynchronous Systems
The use of Spring Security strategies is particularly useful for asynchronous systems, since we have to add a property on the security provider for the authentication to be set on more than one thread. In this case, we would use MODE_GLOBAL as shown in the following example:

?

<mule-ss:security-manager> <mule-ss:delegate-security-provider delegate-ref="authenticationManager"> <mule-ss::security-property name="securityMode" value="MODE_GLOBAL"/> </mule-ss::delegate-security-provider> </mule-ss:security-manager> name="memory-dao"

Setting Up an LDAP Provider for Spring Security
Contents

? ? ? ? ?

Setup Declaring the Beans Configuring the Mule Security Provider Configuring the MethodSecurityInterceptor Go Further

This page describes how you can configure a Spring Security LDAP provider, which can be used by Mule 2.2 or later as follows:

? ?

As its security provider via SpringProviderAdapter To perform component authorization For information on configuring an in-memory provider, see Configuring Security.

Setup
Before proceeding, ensure that you have the following .jar files in your project classpath:

? ? ?

spring-security-ldap-3.1.2.RELEASE.jar spring-security-core-3.1.2.RELEASE.jar spring-ldap-core-1.3.1.RELEASE.jar If you do not already have these files, you can download them here:

?

https://repo.springsource.org/libs-release-local/org/springframework/security/spring-security/3.1 .2.RELEASE/spring-security-3.1.2.RELEASE-dist.zip (this link contains spring-security-core-3.1.2.RELEASE.jar and spring-security-ldap-3.1.2.RELEASE under the "dist" directory)

?

http://s3.amazonaws.com/dist.springframework.org/release/LDAP/spring-ldap-1.3.1.RELEASEminimal.zip (this contains spring-ldap-1.3.1.RELEASE.jar inside the "dist" directoy)

Declaring the Beans
You must set up two beans in Spring, a DefaultSpringSecurityContextSource and an LdapAuthenticationProvider. TheDefaultSpringSecurityContextSource is the access point for obtaining an LDAP context where the

LdapAuthenticationProviderprovides

integration with the LDAP server. For example:

You need to set up an LDAP context source that will be used by the spring security authentication provider to search and authenticate your users. Also, you need to define an authentication manager with an embedded LDAP authentication provider as shown:

<mule xmlns:ss="http://www.springframework.org/schema/security" xmlns:mule-ss="http://www.mulesoft.org/schema/mule/spring-security" xmlns:spring="http://www.springframework.org/schema/beans" ... version="EE-3.3.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" ... xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-current.xsd http://www.mulesoft.org/schema/mule/core http://www.mulesoft.org/schema/mule/core/current/mule.xsd http://www.mulesoft.org/schema/mule/spring-security http://www.mulesoft.org/schema/mule/spring-security/current/mule-spring-security.xsd http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.0.xsd">

... <spring:beans> ... <spring:bean <spring:constructor-arg value="${ldap.url}"/> <spring:property name="userDn" value="${ldap.adminDn}"/> <spring:property name="password" value="${ldap.adminPassword}"/> </spring:bean> <ss:authentication-manager alias="authenticationManager"> <ss:ldap-authentication-provider </ss:authentication-manager> user-search-filter="(uid={0})" user-search-base="ou=People" group-search-base="ou=Group"/> id="contextSource"

class="org.springframework.security.ldap.DefaultSpringSecurityContextSource">

</spring:beans> ...
More information about the LDAP authentication provider and the different mechanisms to authenticate users against your LDAP server can be found here: http://static.springsource.org/spring-security/site/docs/3.1.x/reference/ldap.html.

Configuring the Mule Security Provider
The SpringSecurityProviderAdapter delegates to an AuthenticationProvider such as the LdapAuthenticationProvider.

<mule-ss:security-manager> <mule-ss:delegate-security-provider delegate-ref="authenticationManager"/> </mule-ss:security-manager>
With the above configuration, you can achieve connector-level security and other security features in Mule that require one or more security providers.

name="spring-security-ldap"

Configuring the MethodSecurityInterceptor
The configuration for component authorization is similar to the one described in Component Authorization Using Spring Security. A key point of configuration is

securityMetadataSource: name="securityMetadataSource"

<property

value="org.mule.api.lifecycle.Callable.onCall=ROLE_MANAGERS"/>
The roles are looked up by the DefaultLdapAuthoritiesPopulator, which you configured in

ROLE_, and its value is extracted and converted to uppercase from the LDAP attribute defined by the groupRoleAttribute.
the previous section. By default, a role is prefixed with

Go Further
For information on configuring an in-memory provider, see Configuring Security.

Upgrading from Acegi to Spring Security
? ? ? ?
Adding the Namespaces Updating the Acegi Package Names Using an AuthenticationManager Simplifying the Configuration Spring Security is version 3.0 of the Acegi Security framework. Upgrading your Mule application to use Spring Security instead of Acegi involves the following steps: 1. 2. 3. 4. Adding the necessary namespaces to your Mule configuration Updating the Acegi package names Updating your Mule configuration to use an

AuthenticationManager

Simplification using new Spring Security elements

Adding the Namespaces
Your Mule configuration file should have the following namespaces declared.

<mule xmlns="http://www.mulesource.org/schema/mule/core" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:spring="http://www.springframework.org/schema/beans" xmlns:mule-ss="http://www.mulesource.org/schema/mule/spring-security" xmlns:ss="http://www.springframework.org/schema/security" xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-current.xsd http://www.mulesource.org/schema/mule/core http://www.mulesource.org/schema/mule/core/3.0/mule.xsd http://www.mulesource.org/schema/mule/spring-security http://www.mulesource.org/schema/mule/spring-security/3.0/mule-spring-security.xsd http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.0.xsd">

... </mule>
The mule-ss namespace is for the Mule Spring Security extensions. The that is part of Spring Security 2.0.

ss namespace is for the

Spring Security schema elements that are not Mule specific and allows you to use the less verbose XML

Updating the Acegi Package Names
Except for the changed package names, the Spring Security API has remained largely compatible with Acegi. For example, assume you configured a DaoAuthenticationProvider like this one:

<bean class="org.acegisecurity.providers.dao.DaoAuthenticationProvider"> <property name="userDetailsService" ref="userService"/> </bean>
To use Spring Security, you simply change the to springframework.security:

acegisecurity package

<bean class="org.springframework.security.authentication.dao.DaoAuthenticationProvider"> <property name="userDetailsService" ref="userService"/> </bean>
Repeat this step for all your Acegi bean definitions. To find the correct spring framework package names, check the API documentation at http://static.springsource.org/spring-security/site/docs/3.0.x/apidocs/.

Using an AuthenticationManager
The only major difference between Mule integration with Acegi and Spring Security is that the latter uses the AuthenticationManager to provider authentication functions, while the former tied in at the Acegi AuthenticationProvider level. With the Acegi provider, the authentication flow followed this progression:

AcegiProviderAdapter (Mule) -> AuthenticationProvider (Acegi)
With the new Spring Security adapter, it follows this progression:

SpringProviderAdapter

(Mule)

->

AuthenticationManager

(Spring

Security)

->

AuthenticationProvider (Spring Security)
This allows the authentication manager to try multiple authentication providers to authenticate your messages. Configuration of this approach requires a little more XML. For example, consider this original configuration:

<mule ...> <acegi:security-manager> <acegi:delegate-security-provider name="memory-dao"

delegate-ref="daoAuthenticationProvider"/> </acegi:security-manager> <spring:bean class="org.acegisecurity.userdetails.memory.InMemoryDaoImpl"> <spring:property name="userMap"> <spring:value> ross=ross,ROLE_ADMIN anon=anon,ROLE_ANONYMOUS </spring:value> </spring:property> </spring:bean> <spring:bean id="daoAuthenticationProvider" id="inMemoryDaoImpl"

class="org.acegisecurity.providers.dao.DaoAuthenticationProvider"> <spring:property name="userDetailsService" ref="inMemoryDaoImpl"/> </spring:bean> </mule>
To upgrade this configuration, you add an AuthenticationManager. This would result in the following:

<mule ...> <mule-ss:security-manager> <mule-ss:delegate-security-provider delegate-ref="authenticationManager"/> </mule-ss:security-manager> <spring:bean <spring:property name="userMap"> <spring:value> ross=ross,ROLE_ADMIN anon=anon,ROLE_ANONYMOUS </spring:value> </spring:property> id="inMemoryDaoImpl" name="memory-dao"

class="org.springframework.security.core.userdetails.memory.InMemoryDaoImpl">

</spring:bean> <spring:bean id="daoAuthenticationProvider"

class="org.springframework.security.authentication.dao.DaoAuthenticationProvider"> <spring:property name="userDetailsService" ref="inMemoryDaoImpl"/> </spring:bean> <spring:bean <spring:property name="providers"> <spring:list> <spring:ref bean="daoAuthenticationProvider"/> </spring:list> </spring:property> </spring:bean> </mule> id="authenticationManager"

class="org.springframework.security.authentication.ProviderManager">

Simplifying the Configuration
Spring Security 3.0 includes new XML syntax that can simplify configurations, especially in simple cases. For example, the previous example has an in-memory user database, a DAO authentication provider, and an authentication manager. This can be simplified to:

<mule ...> <mule-ss:security-manager> <mule-ss:delegate-security-provider delegate-ref="authenticationManager" /> </mule-ss:security-manager> <spring:beans> <ss:authentication-manager alias="authenticationManager"> <ss:authentication-provider> <ss:user-service id="userService"> <ss:user name="ross" password="ross" authorities="ROLE_ADMIN" /> <ss:user name="anon" password="anon" authorities="ROLE_ANON" /> </ss:user-service> </ss:authentication-provider> name="memory-dao"

</ss:authentication-manager> </spring:beans> </mule>
The <authentication-manager> element defines the name of our AuthenticationManager bean. We then create a singleAuthenticationProvider with the <authentication-provider> and <user-service> elements. This <user-service> is the same as ourInMemoryDaoImpl above. For more information on how to configure Acegi, see the following Spring documentation:

? ? ?

Spring Security Documentation Spring Security Javadoc Spring Security XML Schema reference

Encryption Strategies
The Security Manager can be configured with one or more encryption strategies that can then be used by encryption transformers, security filters, or secure transports such as SSL or HTTPS. These encryption strategies can greatly simplify configuration for secure messaging as they can be shared across components. Following is an example of a password-based encryption strategy (PBE) that provides password-based encryption using JCE. Users must specify a password and optionally a salt and iteration count as well. The default algorithm is PBEWithMD5AndDES, but users can specify any valid algorithm supported by JCE.

<security-manager> <password-encryption-strategy name="PBE" password="mule"/> </security-manager>
This strategy can then be referenced by other components in the system such as filters or transformers.

12345678910111213 <decrypt-transformer name="EncryptedToByteArray" strategy-ref="PBE"/>

<flow name="Svc1"> <inbound-endpoint address="vm://test"> <encryption-security-filter strategy-ref="PBE"/> </inbound-endpoint> ...cut... </flow>

<flow name="Svc2"> ...cut... <outbound-endpoint address="vm://output" transformer-refs="EncryptedToByteArray"/> </flow> view rawEncryptionExample.xml hosted with ? by GitHub

Go Further
?
Read more about encryption in Mule Studio in our MuleSoft Blog.

PGP Security
This extension adds PGP security on connector communication. With PGP you can achieve end-to-end security communication with signed and encrypted messages between parties. Contents

? o ? o o o ? ? o o ? o o ? o o

Requirements Policy Files Encrypting and Decrypting Configuring the Security Manager Configuring the Key Manager Configuring a Credential Accessor Configuration Reference Security manager Attributes of <security-manager...> Child Elements of <security-manager...> Security provider Attributes of <security-provider...> Child Elements of <security-provider...> Keybased encryption strategy Attributes of <keybased-encryption-strategy...> Child Elements of <keybased-encryption-strategy...>

? o o

Security filter Attributes of <security-filter...> Child Elements of <security-filter...>

Requirements
Policy Files
If you are running JDK 1.4+ that comes with the Sun JCE by default, you must install the Unlimited Strength Jurisdiction Policy files, which can be downloaded from the following URL (note that they are listed entirely at the bottom of the page, in the Other Downloads section): JDK 1.4 JDK 5 JDK 6 These files must be installed in $JAVA_HOME$/jre/lib/security According to Sun, the default distribution of the JCE allows "strong, but limited strength cryptography." This means that you cannot use RSA keys bigger than 2048 bits and no symmetric ciphers that use more than 128 bits. ElGamal is not allowed at all, thus DH/DSS cannot be used for encryption.

Useful PGP Links

How PGP works (intro documentation) GnuPG (freeware implementation) enigmail (extension for Thunderbird)

Encrypting and Decrypting
To encrypt and decrypt messages you need to configure the following elements:

?

A security manager: responsible of holding a security provider, which contains the key rings, and the encryption strategy to be used. This allows for the encryption of all messages using the same key or to facilitate the use of different key rings.

?

A key manager: which is responsible for reading the key rings.

?

A credential accessor: which determines the key ring and key manager to be used to encrypt/decrypt the message being processed. A full example is shown below:

<spring:beans> <spring:bean id="pgpKeyManager" class="org.mule.module.pgp.PGPKeyRingImpl" init-method="initialise"> <spring:property name="publicKeyRingFileName" value="pubring.gpg"/> <spring:property name="secretKeyRingFileName" value="secring.gpg"/> <spring:property name="secretAliasId" value="${public.KeyId.LongValue}"/> <spring:property name="secretPassphrase" value="${secret.Passphrase}"/> </spring:bean> <spring:bean class="com.somecompany.apps.AppCredentialAccessor"> <spring:property </spring:bean> </spring:beans> <pgp:security-manager> <pgp:security-provider keyManager-ref="pgpKeyManager"/> <pgp:keybased-encryption-strategy name="keyBasedEncryptionStrategy" keyManager-ref="pgpKeyManager" credentialsAccessor-ref="credentialAccessor"/> </pgp:security-manager>
The pgpKeyManager (in the spring:beans tag) is the one responsible for reading the rings. You have to set all the parameters: public and secret rings, the alias id (the long value in the ring) and the secret passphrase. In the same section, you can see the credentials accessor which needs to implement the CredentialsAccessor interface basically returning the key id based on the message (MuleEvent). Finally the pgp:security-manager glues both beans. You are ready to encrypt and decrypt messages in your flows. The following two flows show how to use the encrypt-transformer and decrypt-transformer to encrypt and decrypt files.

id="credentialAccessor" name="credentials" value="John Smith (TestingKey)

&lt;john.smith@somecompany.com&gt;"/>

name="pgpSecurityProvider"

<flow name="processEncryptFiles">

<file:inbound-endpoint connector-ref="inputEncrypt" path="file:///temp/fileInput" moveToDirectory="file:///temp/fileInputBackup" moveToPattern="#[header:originalFilename].backup" transformer-refs="file2Bytes" /> <encrypt-transformer name="pgpEncrypt" strategy-ref="keyBasedEncryptionStrategy" /> <file:outbound-endpoint connector-ref="output" path="file:///temp/fileOutput" outputPattern="#[function:datestamp]-#[header:originalFilename]" /> </flow> <flow name="processDecryptFiles"> <file:inbound-endpoint connector-ref="inputDecrypt" path="file:///temp/fileOutput" moveToDirectory="file:///temp/fileOutputEncrypted" moveToPattern="#[header:originalFilename].backup" transformer-refs="file2Bytes" /> <decrypt-transformer name="pgpDecrypt" strategy-ref="keyBasedEncryptionStrategy" /> <file:outbound-endpoint connector-ref="output" path="file:///temp/fileOutputDecrypted" outputPattern="#[function:datestamp]-#[header:originalFilename]" /> </flow>
The following sections explain how to configure each element.

Configuring the Security Manager
To configure the Security Manager you need to reference your key manager and your encryption strategy. The Key manager is simple a reference to your key manager ring.

Configuring the Key Manager
To configure your key manager you have to create a spring bean as shown before. You will need to set the public and secret ring files, the alias id and the secret passphrase. As Mule uses the bouncy castle library to encrypt/decrypt messages we recommend to obtain the alias id (as a long value) using this library. If Mule does not find your id in the ring it will throw an exception and it will list all the available ids in your ring.

Configuring a Credential Accessor
To configure your credential accessor you need to define a class which determines your key id. For instance the following class (used in the example) returns always the same fixed string thus all the messages will be encrypted/decrypted using the same key id. If you need to use different key ids then return different strings according to the MuleEvent received as a parameter.

public class FakeCredentialAccessor implements CredentialsAccessor { private String credentials = "John Smith (TestingKey) <john.smith@somecompany.com>"; public FakeCredentialAccessor() { } public FakeCredentialAccessor(String string) { this.credentials = string; } public String getCredentials() { return credentials; } public void setCredentials(String credentials) { this.credentials = credentials; }

public Object getCredentials(MuleEvent event) { return this.credentials; } public void setCredentials(MuleEvent event, Object credentials) { // dummy } }

Configuration Reference

PGP Module
This extension adds PGP security on endpoint communication. With PGP you can achieve end-to-end security communication with signed and encrypted messages between parties.

Security manager
Attributes of <security-manager...>
Name Type Required Default Description

Child Elements of <security-manager...>
Name security-provider keybased-encryption-strategy Cardinality 0..1 0..1 Description Security provider for PGP-related functionality. The key-based PGP encryption strategy to use.

Security provider
Security provider for PGP-related functionality.

Attributes of <security-provider...>
Name keyManager-ref Type string Required yes Default Description Reference to the key manager to use.

Child Elements of <security-provider...>
Name Cardinality Description

Keybased encryption strategy
The key-based PGP encryption strategy to use.

Attributes of <keybased-encryption-strategy...>
Name keyManager-ref credentialsAccessor-ref Type string string Required yes no Default Description Reference to the key manager to use. Reference to the credentials accessor to use. checkKeyExpirity boolean no Check key expiration.

Child Elements of <keybased-encryption-strategy...>
Name Cardinality Description

Security filter
Filters messages based on PGP encryption.

Attributes of <security-filter...>
Name strategyName Type string Required yes Default Description The name of the PGP encryption strategy to use. signRequired string yes Whether signing is required.

Name keyManager-ref credentialsAccessor-ref

Type string string

Required yes yes

Default

Description Reference to the key manager to use. Reference to the credentials accessor to use.

Child Elements of <security-filter...>
Name Cardinality Description

Jaas Security
The JaasSimpleAuthenticationProvider is a security provider that provides a way to interact

with the Jaas Authentication Service.
The security provider for Jaas can be configured in a couple of different ways. It allows you to configure Jaas either by passing to the provider a Jaas configuration file or by passing the required attributes directly to the JaasSimpleAuthenticationProvider. These two configuration methods are described below. Contents

? o ? ? ? ? ? o ? o ?

Using the Jaas Configuration File Configuring the Provider in the Mule Configuration File Passing the Credentials Directly to the Provider Passing a Non-default Login Module Configuring the Security Filter on an Connector JAAS Module Reference Security Manager Child Elements of <security-manager...> Security Provider Attributes of <security-provider...> Jaas Security Filter

Using the Jaas Configuration File
Usually, JAAS authentication is performed in a pluggable fashion, so applications can remain independent from underlying authentication technologies.

jaasTest{ org.mule.module.jaas.loginmodule.DefaultLoginModule required credentials="anon:anon;Marie.Rizzo:dragon;" };
The above example was saved in a file called

jaas.conf. This file contains just one entry

called com.ss.jaasTest, which is where the application we want to protect can be found. The entry specifies the login module that will be used to authenticate the user. As a login module, you can either use Mule's DefaultLoginModule, one of the login modules that come with Sun, or else create your own. In this case, we have opted for Mule's

DefaultLoginModule.

The required flag that follows the login module specifies that the login module must succeed for the authentication to be considered successful. Additional flags are: Required - The login module is required to succeed. If it succeeds or fails, authentication still continues to proceed down the login module list. Requisite - The login module is required to succeed. If it succeeds, authentication continues down the login module list. If it fails, control immediately returns to the application. Sufficient - The login module is not required to succeed. If it does succeed, control immediately returns to the application (authentication does not proceed down the login module list). If it fails, authentication continues down the login module list. Optional - The login module is not required to succeed. If it succeeds or fails, authentication still continues to proceed down the login module list. The entry also specifies the credentials, in which we put a string of authorized users together with their passwords. The credentials are put here only when the another. The format of the credentials string must adhere to the following format if the DefaultLoginModule is going to be used: <username>:<password>;

DefaultLoginModule is going to be used,

as the method in which the user names and passwords are obtained may vary from one login module to

Configuring the Provider in the Mule Configuration File <mule xmlns="http://www.mulesource.org/schema/mule/core/2.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jaas="http://www.mulesource.org/schema/mule/jaas/2.2" ...cut... <jaas:security-manager>

<jaas:security-provider loginContextName="jaasTest" loginConfig="jaas.conf"/> </jaas:security-manager>

name="jaasSecurityProvider"

Note that in the above, the loginContextName contains the same name of the entry as in the Jaas configuration file. This name will be used for creating the login context as well as to find the complete URL of the jaas.conf file.

Passing the Credentials Directly to the Provider
The second option for the configuration of the provider.

JaasSimpleAuthenticationProvider is to pass

the configuration details that would otherwise be found in the Jaas configuration file directly to the

<jaas:security-manager> <jaas:security-provider name="jaasSecurityProvider" loginContextName="jaasTest" credentials="anon:anon;Marie.Rizzo:dragon;"/> </jaas:security-manager>
In the above configuration, note that we removed the property

loginConfig and don't need to pass

any Jaas configuration file. Instead, we simply pass the credentials to the provider (using the same format as specified above). Since no login module is specified, the DefaultLoginModule is used.

Passing a Non-default Login Module
The third option is to enter your own login module.

<jaas:security-manager> <jaas:security-provider name="jaasSecurityProvider" loginContextName="jaasTest" loginModule="com.sun.security.auth.module.NTLoginModule"/> </jaas:security-manager> loginModule property, which allows you to specify the NTLoginModule does not require you to input a list of accepted usernames and passwords, the property for the credentials was
In the above configuration, we have added the login module you want to use to authenticate the user. Since the removed.

Configuring the Security Filter on an Connector
You can use JaasSecurityFilter as a security filter, as follows:

<inbound> <inbound-endpoint address="vm://test"> <jaas:jaas-security-filter/> </inbound-endpoint> </inbound>

JAAS Module Reference
This module provides security via JAAS.

Security Manager
This is the security provider type that is used to configure JAAS related functionality.

Child Elements of <security-manager...>
Name security-provider Cardinality 0..1 Description This is the security provider type that is used to configure JAAS related functionality. password-encryption-strategy 0..*

Security Provider
This is the security provider type that is used to configure JAAS related functionality.

Attributes of <security-provider...>
Name loginContextName credentials loginConfig Type string string string Required no no no Default Description

Name loginModule

Type string

Required no

Default

Description

Jaas Security Filter
Authenticates users via JAAS.

SAML Module
Enterprise Mule Enterprise offers support for the Security Assertion Markup Language (SAML), which is a standard for exchange of security information between federated systems. For more information on SAML, see http://saml.xml.org/wiki/saml-wiki-knowledgebase.

This module implements SAML 1.1. Mule's CXF Module includes WS-Security with a SAML option that supports SAML 2.0.
Contents

? o o o ? ? ? ? o o ? o o ? o o ? o o

Using the SAML Module Adding the SAML Module JAR Configuring the Security Manager Configuring Security on an Connector Choosing a SAML Profile Example Configuration Reference Security manager Attributes of <security-manager...> Child Elements of <security-manager...> Saml security provider Attributes of <saml-security-provider...> Child Elements of <saml-security-provider...> Keystore provider Attributes of <keystore-provider...> Child Elements of <keystore-provider...> Sender vouches realm Attributes of <sender-vouches-realm...> Child Elements of <sender-vouches-realm...>

? o o

Holder of key realm Attributes of <holder-of-key-realm...> Child Elements of <holder-of-key-realm...>

Using the SAML Module
This section describes how to configure the SAML module in your Mule configuration.

Adding the SAML Module JAR
The use the SAML module, the mule-module-saml JAR file must be in a location on the classpath of your application.

Configuring the Security Manager
To use the features of the SAML module, add the SAML module namespace to your Mule configuration file as follows:

<mule xmlns:saml="http://www.mulesoft.org/schema/mule/ee/saml" xsi:schemaLocation="http://www.mulesoft.org/schema/mule/ee/saml
http://www.mulesoft.org/schema/mule/ee/saml/current/mule-saml-ee.xsd">

<!-- Rest of your mule configuration --> </mule>
Next, you configure the SAML security manager as shown below. The following example starts off with the definition of the SAML security manager and its accompanying security provider. The security provider specifies the default security realm to use by security filters if none is specified. This is especially useful in case you have only one security realm.

<saml:security-manager> <saml:saml-security-provider default-realm="senderVouches"> <saml:keystore-provider name="default-key-provider" key-store-file="classpath:saml.ks" key-store-type="JKS" key-store-password="changeit"/> <saml:sender-vouches-realm name="senderVouches" sign-key-alias="mulesaml" sign-key-password="changeit" key-provider-ref="default-key-provider" name="samlSecurityProvider"

resign-assertions="true"/> <saml:holder-of-key-realm key-provider-ref="default-key-provider" /> </saml:saml-security-provider> </saml:security-manager>
Within the security provider, you define a key provider, which reads keys and certificates from a standard Java keystore file. You configure this file using the normal Spring options to define resources. In this case, the keystore is read from the classpath. In this example, two security realms are defined. One uses the sender vouches SAML scheme and is also the default realm. The other is a holder of key realm. Both use the same key provider as defined above. For more information on these realms, seeChoosing a SAML Profile below.

name="holderOfKey"

Configuring Security on an Connector
Once you've defined a security manager, you can configure security filters on CXF connectors as shown in the examples below. The first example does not specify a security realm, so the default realm is used. Both filters specify the same certificate that is used to verify the SAML assertions as issued by the assertion provider.

<saml:cxf-security-filter certificate-alias="mulesaml"/> <saml:cxf-security-filter security-realm="non-default"/>
Additionally, you must create specific configurations for the various transports to instruct them to support SAML. For example, CXF has to be instructed to configure WSS4j for usage of SAML as WS-Security profile.

certificate-alias="mulesaml"

Choosing a SAML Profile
SAML defines two different profiles: Sender-vouches (SV) and Holder-of-key (HOK).

?

The Sender Vouches profile means that the sender of a message is authorized to act for one of its users towards another system. In this case, the sender of the message vouches its correctness. If both systems trust each other, this profile is appropriate.

?

Holder-of-key means that the user himself is authorized to perform the actions. In this case, the owner (holder) of the key is acting. If your target system trusts the token issuer (and therefore the user) you'll use Holder-of-key. For a more detailed description of these profiles and the use cases when they're appropriate, see the article in the SAP documentation here.

Example
Since SAML is used for single sign-on, authentication of the user is assumed to have already occurred, and the SAML token simply contains one or more subjects, which provide some information understood by other systems. In this case we will configure our flow to require a SAML subject of AllowGreetingServices. To our inbound connector we add a SAMLVerifyInterceptor with a callback, which will check for the correct SAML subject:

<spring:bean class="org.mule.module.saml.cxf.SAMLVerifyInterceptor"> <spring:property name="callback"> <spring:bean class="org.mule.example.security.VerifyAuthorization"> <spring:property name="subject" value="AllowGreetingServices" /> </spring:bean> </spring:property> </spring:bean> public class VerifyAuthorization implements SAMLVerifyCallback { private String subject; public SAMLAuthenticationAdapter verify(SAMLAuthenticationAdapter samlAuthentication) throws SecurityException { SAMLSubject samlSubject = samlAuthentication.getSubject(); if (!samlSubject.getNameIdentifier().getName().equals(subject)) { throw new UnauthorisedException(...cut...
When the expected SAML token is added to the WS-Security header of the message, it looks like this:

<Assertion xmlns="urn:oasis:names:tc:SAML:1.0:assertion" xmlns:saml="urn:oasis:names:tc:SAML:1.0:assertion" xmlns:samlp="urn:oasis:names:tc:SAML:1.0:protocol" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" AssertionID="_40082eadbf045476e26a107e4f37861d" IssueInstant="2009-11-13T02:26:06.569Z" Issuer="self" MajorVersion="1" MinorVersion="1">

<AuthenticationStatement AuthenticationInstant="2009-11-13T02:26:06.569Z" AuthenticationMethod="urn:oasis:names:tc:SAML:1.0:am:password"> <Subject> <NameIdentifier>AllowGreetingServices</NameIdentifier> <SubjectConfirmation> <ConfirmationMethod>urn:oasis:names:tc:SAML:1.0:cm:sender-vouches </ConfirmationMethod> </SubjectConfirmation> </Subject> </AuthenticationStatement> </Assertion>
To verify that the received SAML token is authentic, SAML offers two different modes of trust: Sender Vouches and Holder of Key. In this case, we are using Sender Vouches, which means that the sender of the message must be trusted (e.g., via a digital signature). In Holder of Key mode, the sender of the message does not matter, but the SAML token subject must contain a key from a trusted source (e.g., an X.509 certificate from Verisign).

Configuration Reference

SAML Module
Mule enterprise offers support for the Security Assertion Markup Language (SAML), a standard for exchange of security information between federated systems.

Security manager
Attributes of <security-manager...>
Name Type Required Default Description

Child Elements of <security-manager...>
Name saml-security-provider Cardinality 0..1 Description A security provider that delegates authorization to some other

Name

Cardinality

Description provider.

Saml security provider
A security provider that delegates authorization to some other provider.

Attributes of <saml-security-provider...>
Name saml-version default-realm Type samlVersion string Required no no Default 1.1 Description

Child Elements of <saml-security-provider...>
Name abstract-key-provider abstract-security-realm Cardinality 1..* 1..* Description

Keystore provider
Attributes of <keystore-provider...>
Name name key-store-file key-store-type key-store-password Type string string string string Required yes yes yes yes Default Description

Child Elements of <keystore-provider...>
Name Cardinality Description

Sender vouches realm
Attributes of <sender-vouches-realm...>
Name name key-provider-ref sign-key-alias sign-key-password resign-assertions Type string name (no spaces) string string boolean Required yes yes no no no Default Description

Child Elements of <sender-vouches-realm...>
Name Cardinality Description

Holder of key realm
Attributes of <holder-of-key-realm...>
Name name key-provider-ref Type string name (no spaces) Required yes yes Default Description

Child Elements of <holder-of-key-realm...>
Name Cardinality Description

FIPS 140-2 Compliance Support
As of Mule 3.5.0, Mule ESB can be configured to run in a FIPS 140-2 certified environment. Note that Mule does not run in FIPS security mode by default. There are two requirements:

? ?

Have a certified cryptography module installed in your Java environment Adjust Mule ESB settings to run in FIPS security mode Contents

? ? ? ? ? ? ?

Assumptions Setting Up a FIPS 140-2 Java Environment Running Mule in FIPS Security Mode Fine-Tuning SSL Connectors Anypoint Enterprise Security and FIPS Tips and Limitations Go Further

Assumptions
This document assumes that you are familiar with FIPS 140-2, the US government security standard that requires that compliant parties use only cryptographic security modules that have been certified by NIST. This document also assumes that you have selected and obtained a certified security module.

Setting Up a FIPS 140-2 Java Environment
Mule relies on the Java runtime to provide a FIPS-compliant security module, which is why the first requirement is to have a FIPS 140-2 Java environment properly set up. If you are setting up your system for FIPS compliance for the first time and you have not already configured a certified security provider, you must first select and obtain one, then set up your Java environment following the instructions specific to your selected provider. Details for this process vary according to your selected security provider Please refer to the documentation for your security provider for complete instructions. Example Setup Instructions Using RSA's BSAFE JCE Provider

Running Mule in FIPS Security Mode
Next, set up your Mule instances to work in a FIPS 140-2-compliant environment by updating the configuration of the wrapper that launches the Mule application server. 1. 2. Open your wrapper.conf file (located in $MULE_HOME/conf folder). Uncomment the line that sets Mule to work in FIPS security mode, as shown. Be sure to replace the <n> with the next sequential number in your wrapper.conf file.

3.

Save. When Mule next launches, the startup readout indicates that FIPS security mode is enabled.

With FIPS security mode enabled, Mule automatically restricts protocol negotiations to use only the subset of approved cryptographic cipher suites. Any HTTPS connectors and any other connectors that use a TLS security layer will be automatically affected by this restriction.

Fine-Tuning SSL Connectors
The Mule conf folder includes two files that allow you to fine-tune the configuration of SSL connectors by manually setting which cipher suites Mule can use and which SSL protocols are allowed:

?
mode)

tls-default.conf

(Allows fine-tuning when Mule is not configured to run in FIPS security

?

tls-fips140-2.conf

(Allows fine-tuning when Mule is running in FIPS security mode)

Open the relevant file and comment or uncomment items in the lists to manually configure the allowed cipher suites and SSL protocols. If you make no changes to these files, Mule allows the configured security manager to select cipher suites and protocols.

Anypoint Enterprise Security and FIPS
Anypoint? Enterprise Security version 1.3 supports FIPS security mode. When in FIPS security mode, Mule will not register a security provider, allowing the module to rely on the platform security provider. Note that not all encryption schemes and signatures included in Anypoint Enterprise Security configuration options are FIPS compliant. If you see an error at runtime that reads, " Could

not find encryption algorithm '<algorithm-name>'. You are running in FIPS mode, so please verify that the algorithm is compliant with FIPS" this means that your
application is using an algorithm that is not approved for FIPS use. Adjust your configuration to select an approved algorithm. Keep in mind that your different environments may have different security configurations, including different encryption schemes and algorithm selections; thus you may see this error only in certain environments, depending on how they are set up.

Tips and Limitations
?
The Bouncy Castle security provider, which is bundled with the Mule ESB distribution, is not FIPS certified. When Mule starts in FIPS security mode, the Bouncy Castle provider will not be registered or used.

Go Further
? ?
Access a full list of validated FIPS-2 Cyptographic Modules. Access a full list of approved cryptographic algorithms.


赞助商链接
更多相关文档:
更多相关标签:
网站地图

文档资料共享网 nexoncn.com copyright ©right 2010-2020。
文档资料共享网内容来自网络,如有侵犯请联系客服。email:zhit325@126.com