Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.


{span:style=
Span
Wiki Markup
style
font-size:2em;font-weight:bold
} JAX-RS: Security {span} {toc} h1. HTTPS Security


Table of Contents

HTTPS

Transport-level

...

protection

...

of

...

JAX-RS

...

endpoints

...

can

...

be

...

managed

...

by

...

underlying

...

Servlet

...

containers,

...

for

...

example,

...

see

...

this

...

Tomcat

...

SSL

...

Configuration

...

section.

Additionally CXF provides support for configuring endpoints which depend on embedded Jetty. CXF JAX-RS clients can also be configured to support SSL.

Configuring endpoints

JAX-RS endpoints using embedded Jetty can rely on the configuration like this one:

Code Block
xml
xml
|http://tomcat.apache.org/tomcat-6.0-doc/ssl-howto.html]. 

Additionally CXF provides support for configuring endpoints which depend on embedded Jetty. CXF JAX-RS clients can also be configured to support SSL. 
 
h2. Configuring endpoints

JAX-RS endpoints using embedded Jetty can rely on the configuration like this one:

{code:xml}
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:http="http://cxf.apache.org/transports/http/configuration"
       xmlns:httpj="http://cxf.apache.org/transports/http-jetty/configuration"
       xmlns:sec="http://cxf.apache.org/configuration/security"
       xsi:schemaLocation="
        http://www.springframework.org/schema/beans                 http://www.springframework.org/schema/beans/spring-beans.xsd
        http://cxf.apache.org/transports/http/configuration         http://cxf.apache.org/schemas/configuration/http-conf.xsd
        http://cxf.apache.org/transports/http-jetty/configuration   http://cxf.apache.org/schemas/configuration/http-jetty.xsd
        http://cxf.apache.org/configuration/security                http://cxf.apache.org/schemas/configuration/security.xsd">


    <httpj:engine-factory id="port-9095-tls-config">
        <httpj:engine port="9095">
            <httpj:tlsServerParameters>
                <sec:keyManagers keyPassword="password">
	            <sec:keyStore type="JKS" password="password" 
	                file="src/test/java/org/apache/cxf/systest/http/resources/Bethal.jks"/>
	        		</sec:keyManagers>
	        		<sec:trustManagers>
	            	<sec:keyStore type="JKS" password="password"
	                file="src/test/java/org/apache/cxf/systest/http/resources/Truststore.jks"/>
	     		</sec:trustManagers>
            </httpj:tlsServerParameters>
        </httpj:engine>
    </httpj:engine-factory>
</beans>
{code}

If you use JAXRSServerFactoryBean to create and start JAX-RS endpoints from the code then the above configuration can be utilized like this:
{code:java}

Instead keyPassword in keyManager you can also specify keyPasswordCallbackHandler attribute. In this case attribute must contain full name of the class implementing JSE CallbackHandler interface and providing key password on the runtime. Sample key password callback handler implementation can be found here.

If you use JAXRSServerFactoryBean to create and start JAX-RS endpoints from the code then the above configuration can be utilized like this:

Code Block
java
java
JAXRSServerFactoryBean bean = new JAXRSServerFactoryBean();
SpringBusFactory bf = new SpringBusFactory();
Bus bus = bf.createBus("configuration/beans.xml");
bean.setBus(bus);
bean.setAddress("http://localhost:9095/rest");
bean.setServiceClass(CustomerService.class);
{code}

If

...

you

...

also

...

have

...

a

...

jaxrs:server

...

endpoint

...

declared

...

in

...

the

...

above

...

beans.xml,

...

then

...

make

...

sure

...

you

...

have

...

a

...

'depends-on'

...

attribute

...

set:

Code Block
xml
xml


{code:xml}
<jaxrs:server serviceClass="CustomerService.class" address="http://localhost:9095/rest"
   depends-on="port-9095-tls-config"/>
{code} 

Once you have 

Once you have JAX-RS

...

and

...

Jetty

...

HTTPS

...

combined

...

then

...

you

...

can

...

get

...

the

...

application

...

context

...

initiated

...

like

...

this:

Code Block
java
java


{code:java}
public class Server {

    public void main(String[] args) throws Exception {
        Bus busLocal = new SpringBusFactory().createBus("configuration/beans.xml");
        BusFactory.setDefaultBus(busLocal);
        new Server();
        Thread.sleep(60000);
    }
}
{code}

Having

...

JAX-RS

...

endpoints

...

declared

...

alongside

...

CXF

...

Jetty

...

HTTPS

...

configuration

...

is

...

only

...

needed

...

when

...

an

...

embedded

...

Jetty

...

container

...

is

...

used.

...

If

...

you

...

have

...

application

...

WARs

...

deployed

...

into

...

Tomcat

...

or

...

Jetty

...

then

...

please

...

follow

...

container-specific

...

guides

...

on

...

how

...

to

...

set

...

up

...

SSL.

...

Please

...

also

...

see

...

this

...

HTTPS-based demo in the CXF distribution.

Additionally check the CXF Jetty Configuration section.

Configuring clients

Secure HTTPConduits for CXF JAX-RS proxies and WebClients can be configured as described in this section.

For example, check this configuration file. Endpoint addresses used by proxies or clients have to match the pattern used in the HTTPConduit configuration.

The configuration file can be referenced during the proxy or WebClient creation:

Code Block
java
java
final String address = "http://localhost:9095/rest";
final String configLocation;

WebClient client = WebClient.create(address, configLocation);
// or
BookStore proxy = JAXRSClientFactory.create(address, configLocation, BookStore.class);

HTTPConduits can also be 'bound' to proxies or WebClients using expanded QNames. Please see this section for more information.

Please see this blog entry on how the HTTPConduit TLS properties can be set up from the code. In the code, do WebClient.getConfig(myClient).getHTTPConduit() and proceed from there.

Authentication

It is often containers like Tomcat or frameworks like Spring Security which handle the user authentication. Sometimes you might want to do the custom authentication instead. CXF HTTP Transport adds decoded Basic Authentication credentials into an instance of AuthorizationPolicy extension and sets it on the current message. Thus the easiest way is to register a custom invoker or @PreMatching ContainerRequestFilter filter which will extract a user name and password like this:

Code Block
java
java
public class AuthenticationHandler implements ContainerRequestFilter {

    @Override
    public void filter(ContainerRequestContext requestContext) throws IOException {
        String authorization = requestContext.getHeaderString("Authorization");
        String[] parts = authValues.authorization(" ");
        if (parts.length != 2 || !"Basic".equals(parts[0])) {
            requestContext.abortWith(createFaultResponse());
            return;
        }
        
        String decodedValue = null;
        try {
   demo|http://svn.apache.org/repos/asf/cxf/trunk/distribution/src/main/release/samples/jax_rs/basic_https/] in the CXF distribution.

Additionally check the [CXF Jetty Configuration|http://cxf.apache.org/docs/jetty-configuration.html] section.

h2. Configuring clients

Secure HTTPConduits for CXF JAX-RS proxies and WebClients can be configured as described in this [section|http://cxf.apache.org/docs/client-http-transport-including-ssl-support.html]. 

For example, check this [configuration file|http://svn.apache.org/repos/asf/cxf/trunk/distribution/src/main/release/samples/jax_rs/basic_https/src/main/resources/ClientConfig.xml]. Endpoint addresses used by proxies or clients have to match the pattern used in the HTTPConduit configuration.

The configuration file can be referenced during the proxy or WebClient creation:
{code:java}
final Stribg address = "http://localhost:9095/rest";
final String configLocation;

WebClient client = WebClient.create(address, configLocation);
// or
BookStore proxy = JAXRSClientFactory.create(address, configLocation, BookStore.class);
{code}

HTTPConduits can also be 'bound' to proxies or WebClients using expanded QNames. Please see this [section|http://cxf.apache.org/docs/jax-rs-client-api.html#JAX-RSClientAPI-ConfiguringanHTTPConduitfromSpring] for more information.

h1. Authentication

It is often containers like Tomcat or frameworks like Spring Security which handle the user authentication. Sometimes you might want to do the custom authentication instead. CXF HTTP Transport adds decoded Basic Authentication credentials into an instance of AuthorizationPolicy extension and sets it on the current message. Thus the easiest way is to register a custom invoker or {{RequestHandler}} filter which will extract a user name and password like this:

{code:java}
public class AuthenticationHandler implements RequestHandler {

    public Response handleRequest(Message m, ClassResourceInfo resourceClass) {
        AuthorizationPolicy  policydecodedValue = (AuthorizationPolicy)m.get(AuthorizationPolicy.classnew String(Base64Utility.decode(parts[1]));
        String} usernamecatch = policy.getUserName();(Base64Exception ex) {
        String  password = policyrequestContext.getPasswordabortWith(createFaultResponse());
 
        if (isAuthenticated(username, password)) {return;
        }
    // let request to continue
    String[] namePassword = decodedValue.split(":"); 
        if  return null;(isAuthenticated(namePassword[0], namePassword[1])) {
        } else {
  // let request to continue
       // authentication} failedelse {
            return Response.status(401).build();   
        }
    }

}
{code} 

One other thing you may want to do, after authenticating a user, is to initialize org.apache.cxf.security.SecurityContext with Principals representing the user and its roles (if available).

If you prefer using Spring Security then see how the authentication is handled in a [spring-security|http://svn.apache.org/repos/asf/cxf/trunk/distribution/src/main/release/samples/jax_rs/spring_security] demo.

Next, please see the [Security] section on how CXF Security interceptors can help. 

Additionally check this [blog entry|http://sberyozkin.blogspot.com/2010/12/authentication-and-authorization-cxf.html] for more information on how CXF JAX-RS wraps the CXF security interceptors with helper filters.

For example, see how a JAX-RS filter can be used to wrap CXF JAASLoginInterceptor:

{code:xml}
// authentication failed, request the authetication, add the realm name if needed to the value of WWW-Authenticate 
            requestContext.abortWith(Response.status(401).header("WWW-Authenticate", "Basic").build());
        }
    }
    private Response createFaultResponse() {
        return Response.status(401).header("WWW-Authenticate", "Basic realm=\"service.com\"").build();
    }
 }

One other thing you may want to do, after authenticating a user, is to initialize org.apache.cxf.security.SecurityContext with Principals representing the user and its roles (if available).

If you prefer using Spring Security then see how the authentication is handled in a spring-security demo.

Next, please see the Securing CXF Services section on how CXF Security interceptors can help.

Additionally check this blog entry for more information on how CXF JAX-RS wraps the CXF security interceptors with helper filters.

For example, see how a JAX-RS filter can be used to wrap CXF JAASLoginInterceptor:

Code Block
xml
xml
<jaxrs:server address="/jaas">
    <jaxrs:serviceBeans>
        <bean class="org.apache.cxf.systest.jaxrs.security.SecureBookStoreNoAnnotations"/>
    </jaxrs:serviceBeans>		   
    <jaxrs:providers>
        <ref bean="authenticationFilter"/>
    </jaxrs:providers>
  </jaxrs:server>
  
  <bean id="authenticationFilter" class="org.apache.cxf.jaxrs.security.JAASAutheenticationFilterJAASAuthenticationFilter">
        <!-- Name of the JAAS Context -->
        <property name="contextName" value="BookLogin"/>
        <!-- Hint to the filter on how to have Principals representing users and roles separated 
             while initializing a SecurityContext -->
        <property name="rolePrefix" value="ROLE_"/>
        
        <property name="redirectURI" value="/login.jsp"/>
  </bean>
{code}

The

...

filter

...

will

...

redirect

...

the

...

client

...

to

...

"/login.jsp"

...

if

...

the

...

authentication

...

fails.

...

If

...

no

...

'redirectURI'

...

property

...

is

...

set

...

then

...

401

...

will

...

be

...

returned.

...

A

...

"realmName"

...

property

...

can

...

also

...

be

...

set.

...

If

...

the

...

JAAS

...

Authentication

...

succeeds

...

then

...

the

...

filter

...

will

...

set

...

a

...

SecurityContext

...

instance

...

on

...

the

...

message.

...

This

...

context

...

can

...

be

...

used

...

for

...

authorization

...

decisions.

Authorization

It is often containers like Tomcat or frameworks like Spring Security which handle user authorization, similarly to the way the authentication is handled.

CXF also provides two interceptors which make it easy to enforce authorization decisions, as described in the Securing CXF Services section.
CXF JAX-RS SimpleAuthorizingFilter can be used to wrap those interceptors and return 403 in case of failures:

Code Block
xml
xml
 

h1. Authorization

It is often containers like Tomcat or frameworks like Spring Security which handle user authorization, similarly to the way the authentication is handled.

CXF also provides two interceptors which make it easy to enforce authorization decisions, as described in the [Security] section.
CXF JAX-RS SimpleAuthorizingFilter can be used to wrap those interceptors and return 403 in case of failures:

{code:xml}
<jaxrs:server address="/jaas">
    <jaxrs:serviceBeans>
        <bean class="org.apache.cxf.systest.jaxrs.security.SecureBookStoreNoAnnotations"/>
    </jaxrs:serviceBeans>		   
    <jaxrs:providers>
        <ref bean="authorizationFilter"/>
    </jaxrs:providers>
  </jaxrs:server>
  
  <bean id="authorizationFilter" class="org.apache.cxf.jaxrs.security.SimpleAuthorizingFilter">
        <property name="methodRolesMap" ref="rolesMap"/>
  </bean>
  
  <util:map id="rolesMap">
     <entry key="getThatBook" value="ROLE_BOOK_OWNER"/>
     <entry key="getBook" value="ROLE_BOOK_OWNER"/>
  </util:map>
{code}

SimpleAuthorizingFilter

...

can

...

also

...

wrap

...

CXF

...

SecureAnnotationsInterceptor.

...

Note

...

that

...

wrapping

...

CXF

...

security

...

interceptors

...

with

...

JAX-RS

...

filters

...

is

...

not

...

required;

...

it

...

simply

...

makes

...

it

...

easier

...

to

...

handle

...

authentication

...

and

...

authorization

...

exceptions

...

and

...

return

...

appropriate

...

HTTP

...

error

...

statuses.

...

WS-Trust

...

integration

One of the requirements for deploying CXF endpoints into secure web service environments is to ensure that existing WS-Trust STS services can be used to protect the endpoints. JAX-WS endpoints can rely on CXF WS-Security and WS-Trust support. Making sure CXF JAX-RS endpoints can be additionally secured by STS is strategically important task. CXF provides close integration between JAX-WS and JAX-RS frontends thus reusing CXF JAX-WS and WS-Security is the most effective way toward achieving this integration.

Validating BasicAuth credentials with STS

Validating Basic Authentication credentials with STS is possible starting from CXF 2.4.1. JAX-RS and JAX-WS services can rely on this feature. Here is an example on how a jaxrs endpoint can be configured:

Code Block
xml
xml
<jaxrs:server serviceClass="org.customers.CustomerService"
    depends-on="ClientAuthHttpsSettings"
    address="https://localhost:8081/rest">

    <jaxrs:inInterceptors>
        <ref bean="basicAuthValidator"/>
    </jaxrs:inInterceptors>
  
    <jaxrs:properties>
         <entry key="ws-security.sts.client">
            <ref bean="stsclient"/>
         </entry>
    </jaxrs:properties>

</jaxrs:server>
   
<bean id="basicAuthValidator" class="org.apache.cxf.ws.security.trust.AuthPolicyValidatingInterceptor">
   <property name="validator">
        <bean class="org.apache.cxf.ws.security.trust.STSTokenValidator">
             <constructor-arg value="true"/>
        </bean>
   </property>
</bean>

<bean id="stsclient" class="org.apache.cxf.ws.security.trust.STSClient">
    <constructor-arg ref="cxf"/>
    <property name="wsdlLocation" value="https://localhost:8083/sts?wsdl"/>
    <property name="serviceName" value="{http://tempuri.org/}STSService"/>
    <property name="endpointName" value="{http://tempuri.org/STSServicePort"/>
</bean> 

<!-- jaxrs:server depends on this SSL configuration -->
<httpj:engine-factory id="ClientAuthHttpsSettings" bus="cxf">
  <httpj:engine port="8081">
    <httpj:tlsServerParameters>
      <sec:keyManagers keyPassword="skpass">
        <sec:keyStore type="jks" password="sspass" resource="servicestore.jks"/>
      </sec:keyManagers>
      <sec:cipherSuitesFilter>
        <sec:include>.*_EXPORT_.*</sec:include>
        <sec:include>.*_EXPORT1024_.*</sec:include>
        <sec:include>.*_WITH_DES_.*</sec:include>
        <sec:include>.*_WITH_NULL_.*</sec:include>
        <sec:exclude>.*_DH_anon_.*</sec:exclude>
        </sec:cipherSuitesFilter>
      <sec:clientAuthentication want="false" required="false"/>
   </httpj:tlsServerParameters>
</httpj:engine>
  
<!-- STSClient depends on this SSL configuration -->
<http:conduit name="https://localhost:8083/.*">
  <http:tlsClientParameters disableCNCheck="true">
    <sec:trustManagers>
      <sec:keyStore type="jks" password="sspass" resource="servicestore.jks"/>
    </sec:trustManagers>
    <sec:keyManagers keyPassword="skpass">
       <sec:keyStore type="jks" password="sspass" resource="servicestore.jks"/>
    </sec:keyManagers>
  </http:tlsClientParameters>
</http:conduit>

AuthPolicyValidatingInterceptor converts Basic Auth info into WSS4J UsernameToken and delegates to STS to validate.

Using STS to validate SAML assertions

Please see this section for more information on how STSTokenValidator can be used to validate the inbound SAML assertions.

Note about SecurityManager

If java.lang.SecurityManager is installed then you'll likely need to configure the trusted JAX-RS codebase with a 'suppressAccessChecks' permission for the injection of JAXRS context or parameter fields to succeed. For example, you may want to update a Tomcat catalina.policy with the following permission :

Code Block
grant codeBase "file:${catalina.home}/webapps/yourwebapp/lib/cxf.jar" {
    permission java.lang.reflect.ReflectPermission "suppressAccessChecks";
};

Securing JAX-RS messages

CXF provides a number of different ways to secure JAX-RS messages:

  • XML messages can be secured via XML Signature and XML Encryption. See JAX-RS XML Security for more information.
  • Messages can be signed and/or encryption using JOSE. In addition, authentication and authorization can be achieved using JSON Web Tokens. See JAX-RS JOSE for more information.
  • Security claims can be conveyed via SAML assertions. See JAX-RS SAML for more information.
  • Messages can be signed via HTTP Signature. See JAX-RS HTTP Signature for more information.

OAuth 2.0 / OpenId Connect.

CXF supports both OAuth 2.0 and OpenId Connect:

Restricting large payloads

Please see this section for more information.

Cross Origin Resource Sharing

Please see this section for more information. Also check the section about JSONP.