Saturday, May 31, 2014

Securing REST Services with Spring Security and OAuth2

Get the code:

This post will walk through setting up an OAuth2 provider service for protecting access to REST resources. The code is available in github. You can fork the code and start writing services that will be protected by OAuth access. This is a separate module but builds on services covered in a previous series that includes:

It would be useful but not required to be familiar with some of the technologies covered such as:

* OAuth2 Protocol
* Spring Security
* Spring Integration
* Spring Data
* Jersey/JAX-RS
* Gradle / Groovy
* MongoDB

Resource Owner Password Flow

Subsequent posts will deal with the other types of authorization flow, such as using third party providers (Facebook, Google, etc). The intent of this post is a walk through of the Resource Owner Password flow. This is a typical use case if you are the system of record for user credentials and trust client applications. It is simply the exchange of the user's username and password for an access token. This token can then be used on subsequent requests to authorize access to resources. It is also important to support token expiration and by extension token refresh.

Let's test out the code and then I'll walk through the application and explain how it is built

Building the project

Check out the source code

> git clone

> cd oauth2-provider

> ./gradlew clean build integrationTest

Running the Web Application

The application uses MongoDB as the persistence store. Before running the application ensure that mongod is running on port 27017. If you don't have mongo installed get it here

Once mongoDB is installed and running fire up the web application using the following command

> ./gradlew tomcatRun

To try it out you can open a browser window and navigate to http://localhost:8080/oauth2-provider/index.html

Testing with Curl

To create a user:

> curl -v -X POST \
   -H "Content-Type: application/json" \
   -H "Authorization: Basic MzUzYjMwMmM0NDU3NGY1NjUwNDU2ODdlNTM0ZTdkNmE6Mjg2OTI0Njk3ZTYxNWE2NzJhNjQ2YTQ5MzU0NTY0NmM=" \
   -d '{"user":{"emailAddress":""}, "password":"password"}' \

The result:

   "scope":"read write"

Requesting an access token:

> curl -v -X POST \
   -H "Content-Type: application/json" \
   -H "Authorization: Basic MzUzYjMwMmM0NDU3NGY1NjUwNDU2ODdlNTM0ZTdkNmE6Mjg2OTI0Njk3ZTYxNWE2NzJhNjQ2YTQ5MzU0NTY0NmM=" \

The result:


Refreshing a token:

> curl -v -X POST \
   -H "Content-Type: application/json" \
   -H "Authorization: Basic MzUzYjMwMmM0NDU3NGY1NjUwNDU2ODdlNTM0ZTdkNmE6Mjg2OTI0Njk3ZTYxNWE2NzJhNjQ2YTQ5MzU0NTY0NmM=" \

The result:


That's all that is needed to support registration of Users and managing tokens on their behalf. The source code also contains everything needed to support lost password and email verification. See previous posts for how to set it up.

In a typical deployment the authorization server and the resource server(s) would be separate, but for the purposes of this tutorial they are managed within the same application.
Let's delve into the details:

Web Context

There are two servlets.

A Jersey servlet as the default to handle all resource calls:
A Spring servlet to handle all oauth calls:
Wire in spring security by defining a filter:
and then map it to the root context so all calls are filtered:

Configuring OAuth flows to support

<oauth:authorization-server client-details-service-ref="client-details-service" token-services-ref="tokenServices">

In this scenario only password flow and refresh token are being supported. The default token endpoint is /oauth/token.

Protecting the token endpoint

It is a good idea to protect access to token requests to only those client applications that you know about. Using Spring security we can set up basic authentication on calls to the token endpoint:
    <http pattern="/oauth/token" create-session="stateless" authentication-manager-ref="clientAuthenticationManager"
        <anonymous enabled="false"/>
        <http-basic entry-point-ref="clientAuthenticationEntryPoint"/>
        <access-denied-handler ref="oauthAccessDeniedHandler"/>

Next we configure the authentication manager and client details service
    <bean id="clientCredentialsTokenEndpointFilter"
        <property name="authenticationManager" ref="clientAuthenticationManager"/>

    <authentication-manager id="clientAuthenticationManager" xmlns="">
        <authentication-provider user-service-ref="client-details-user-service"/>

    <bean id="client-details-user-service" class="">
        <constructor-arg ref="client-details-service" />

Depending on how many clients we expect to access the service will determine what type of client details service we implement. A simple file-based service might be sufficient. If you wanted to go a lot further with client sign up and managing API keys then you would have to involve a persistence tier for the client details service. Configuring with the default Spring file-based service is trivial:

<oauth:client-details-service id="client-details-service">






Accessing the oauth endpoint now requires a basic authentication header with the client id and secret concatenated with a ":" separator and base64 encoded.
e.g. -H "Authorization: Basic MzUzYjMwMmM0NDU3NGY1NjUwNDU2ODdlNTM0ZTdkNmE6Mjg2OTI0Njk3ZTYxNWE2NzJhNjQ2YTQ5MzU0NTY0NmM="

Configuring User Authentication Services

The Resource Owner Password flow requires an authentication manager for managing users.

    <bean id="passwordEncoder" class=""/>

    <sec:authentication-manager alias="userAuthenticationManager">
        <sec:authentication-provider user-service-ref="userService">
            <sec:password-encoder ref="passwordEncoder"/>

The password encoder is used to encrypt the password on authentication. The user service also uses the same encoder to encrypt passwords before persisting them.
The user service must implement UserDetailsService and retrieve the user by username.
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        notNull(username, "Mandatory argument 'username' missing.");
        User user = userRepository.findByEmailAddress(username.toLowerCase());
        if (user == null) {
            throw new AuthenticationException();
        return user;

Configuring Token Services

The final piece of configuration is to manage storage and retrieval of access tokens.

    <bean id="tokenServices" class="">
        <property name="tokenStore" ref="tokenStore"/>
        <property name="supportRefreshToken" value="true"/>
        <property name="clientDetailsService" ref="client-details-service"/>

Spring has a handy in-memory implementation that is useful when testing:

     <bean id="tokenStore" class=""/>

For this tutorial I have chosen MongoDB as the persistence technology, but it would be easy to wire in an alternative such as MySql or Redis It is a matter of implementing

<bean id="tokenStore" class="com.porterhead.oauth2.mongodb.OAuth2RepositoryTokenStore">
      <constructor-arg ref="OAuth2AccessTokenRepository"/>
      <constructor-arg ref="OAuth2RefreshTokenRepository"/>

Protecting access to resources

First we need to configure a spring resource server filter. This will check that there is a valid access token in the request header.

    <oauth:resource-server id="resourceServerFilter" token-services-ref="tokenServices"/>

Spring security has some useful classes for fine-grain control of roles and permissions. I prefer to use JSR-250 annotations. Luckily it is easy to wire this in. First we need to enable JSR-250 annotations with the following configuration:

    <sec:global-method-security jsr250-annotations="enabled" access-decision-manager-ref="accessDecisionManager"/>

Configure an access manager that uses the Jsr250Voter

    <bean id="accessDecisionManager" class="">
        <property name="decisionVoters">
                <bean class=""/>

Now we can protect REST resource methods with JSR-250 annotations such as @RolesAllowed

Trying it out

Typically the glue between the OAuth server and the application is a user identifier. When a client gets an access token for a user the next step is to typically load data related to that user. This will usually involve building a url with the userId as part of the path
i.e. /v1.0/users/{id}/someresource
A useful service to provide is a way to get user information based on the access token. The application can identify the user that owns the token and return information on that user to the client.
public class MeResource extends BaseResource {

    public ApiUser getUser(final @Context SecurityContext securityContext) {
        User requestingUser = loadUserFromSecurityContext(securityContext);
        if(requestingUser == null) {
            throw new UserNotFoundException();
        return new ApiUser(requestingUser);

    protected User loadUserFromSecurityContext(SecurityContext securityContext) {
        OAuth2Authentication requestingUser = (OAuth2Authentication) securityContext.getUserPrincipal();
        Object principal = requestingUser.getUserAuthentication().getPrincipal();
        User user = null;
        if(principal instanceof User) {
            user = (User)principal;
        } else {
            user = userRepository.findByEmailAddress((String)principal);
        return user;

To test this out start up the application:

> ./gradlew tomcatRun

Execute the following curl statement, substituting the access token that was returned from the login curl above

> curl -v -X GET \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer [your token here]" \

To try out some of the other services included in the code see previous posts: