Configure OAuth2 Spring Authorization Server with JWT support

Last Updated On

Table of Contents:

Update: 04/15/2020 Spring team announced a new initiative of "Spring Authorization server" development. At the time of writing this article it's in "experimental state" and available at the following GitHub repository.

Introduction

Before continuing with the article, it's worth mentioning that Spring Authorization Server is deprecated (as was written in the official spring blog post Spring Security OAuth 2.0 Roadmap Update). However, it's often very convenient to start up own authorization server for various demos and proofs-of-concept rather than using third-party products like Okta or spinning up CloudFoundry/UAA or KeyCloak in a docker container.

Spring's official Security OAuth 2.X guide is very detailed and well written. There is an auto-configuration for opaque tokens. Unfortunately, to set up OAuth2 with JWT (which pretty much standard in our days) it's required to do a little bit extra work which might be not straightforward. After following Spring's post, I still ended up getting exceptions during app startup. After some research, I was able to configure it the way I needed and want to share the config in this article.

It should be noted that we will not be covering OAuth2 concepts such as authorization grants, access and refresh tokens that represented by JWT tokens and involved parties such as client, resource server, authentication server in detail. If you landed on this page there is an assumption that you have a basic understanding of the material.

Before diving into the details, let's set some expectations from our Authorization Server.

Requirements

  1. Should use JWT tokens (not opaque tokens, which is the default)
  2. Should expose JWK (JSON Web Key) endpoint so that Resource Server can retrieve JWK to validate JWS (JSON Web Signature) of the token
  3. Should support OAuth2 "Password" Grant
  4. Should be able to refresh "access_token" via "refresh_token" (Spring uses "refresh_token" grant type for this)
  5. Should not use Basic Auth (which is the default). Many REST clients don't support Basic Auth and the fact of exposing sensitive data in the URL is no longer a good fit in our days even for small projects.

How to complete this guide

If you just need a working code you can go to the GitHub repository, download the code and jump to "Test the configuration" section. Alternatively, you can follow along with the steps below.

Authorization server setup

Dependencies

build.gradle.kts

  1. Provides defaults Filter for Servlets. Also needed for requirement .2.
  2. It will be used to configure credentials for users. It's worth clarifying that "Spring Security" module is used for the individual user whereas "Spring Security OAuth2" module is used for Authorization Server configuration. We will later see that things like username and password belong to a user and things like grant_type, client_id and client_secret belong to Authorization Server.
  3. This is where the core logic of Spring Authorization Server resides.
  4. Provides JwtAccessTokenConverter bean that is used to configure the use of JWT tokens instead of opaque tokens
  5. Provides convenient methods for JWK configuration

Utilities

Before we start with our Authorization Server config class, we need to set up a few utility beans such as:

PasswordEncoderConfig.class

Spring Security 5.x changed password storage format. Storage of plain passwords is not allowed anymore and the new format is described here. DelegatingPasswordEncoder will take care of that configuration for us.

JwtSetKeyGeneration.class

Generates public/private key pair to supply later for accessTokenCoverter as a part of its configuration and more importantly, to automatically configure JSON Web Key Set (JWKS). The latter would be exposed via public URL so that the resource server can key use it to verify access_token signature.

Authorization Server setup

JwkSetConfiguration.class

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerEndpointsConfiguration;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;

import java.security.KeyPair;

@Import(AuthorizationServerEndpointsConfiguration.class)
@Configuration
public class JwkSetConfiguration extends AuthorizationServerConfigurerAdapter {

    AuthenticationManager authenticationManager;
    KeyPair keyPair;
    PasswordEncoder passwordEncoder;
    UserDetailsService userDetailsService;

    public JwkSetConfiguration(AuthenticationConfiguration authenticationConfiguration, KeyPair keyPair, PasswordEncoder passwordEncoder, UserDetailsService userDetailsService) throws Exception {
        this.authenticationManager = authenticationConfiguration.getAuthenticationManager();
        this.keyPair = keyPair;
        this.passwordEncoder = passwordEncoder;
        this.userDetailsService = userDetailsService;
    }

    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) {
        security
          .tokenKeyAccess("permitAll()")
          .checkTokenAccess("isAuthenticated()")
          .allowFormAuthenticationForClients() // (1)
        ;
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients
            .inMemory() // (2)
            .withClient("test-client")
            .secret(passwordEncoder.encode("noonewilleverguess")) // (3)
            .scopes("any") // (4)
            .autoApprove(true)
            .authorizedGrantTypes("password", "refresh_token")
        ;
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
        endpoints.authenticationManager(this.authenticationManager)
            .accessTokenConverter(accessTokenConverter())
            .userDetailsService(userDetailsService)
            .tokenStore(tokenStore());
    }

    @Bean
    public TokenStore tokenStore() {
        return new JwtTokenStore(accessTokenConverter());
    }

    @Bean
    public JwtAccessTokenConverter accessTokenConverter() {
        JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
        converter.setKeyPair(this.keyPair);
        return converter;
    }
}

That's the main class that is responsible for OAuth2 configuration and there is a noticeable amount of actions happen inside of it. Most of them are borrowed from the official Spring Guide, but few ones are different:

  1. Replaces Basic Authentication and allows you to pass all necessary params as a part of a request body. This is how with Basic Auth request looks like:
POST http://user:password@localhost:6060/oauth/token?grant_type=password&client_id=test-client&client_secret=noonewilleverguess

Even for demos, it's still better to have the following approach, especially when adding one line of config allows us to do so:

POST http://localhost:6060/oauth/token
Content-Type: application/x-www-form-urlencoded
 
username=user&password=password&grant_type=password&client_id=test-client&client_secret=noonewilleverguess
  1. To keep things easier we're specifying OAuth2 client settings in the codebase. However, it's also possible to use an external data source. Refer to Marcos Barbero's post at the end of the article for more examples.

  2. That's where Spring Security 5.x encoder will come into play. However, it's also possible to replace

.secret(passwordEncoder.encode("noonewilleverguess")) with .secret("{noop}noonewilleverguess")to delegate encoding to NoOpPasswordEncoder (more about it here).

  1. Although it's not required to specify scope when requesting a token, it's required to set one during the configuration.

JwkSetEndpoint.class

That's how our Resource Server will communicate to Authorization server to retrieve JWKs and verify that the access token's signature supplied in the Authorization header request from the end-user is genuine.

JwkSetEndpointConfiguration.class

Since Spring Security locks access to all endpoints by default and recently created jwks endpoint is not an exception, it's necessary to allow public access so that the resource server can retrieve necessary data.

WebSecurityConfig.class

In this situation WebSecurityConfig.class is responsible for setting up end users and has nothing to do with OAuth2 config. As we saw earlier, it's possible to replace .password(passwordEncoder.encode("password")) with .password("{noop}password") as well as use external source for the user management.

Resource server setup

There are two main parts when it comes to resource server configuration:

  1. Tell Resource Server where to find JWKs. That's done in the application.yaml file in spring.security.oauth2.resourceserver.jwt.jwk-set-uri property (more theory behind it can be found in the official Spring Security Docs)
  2. Configure access to each endpoint using Spring Security DLS

Test the configuration

Retrieving an access token:

raw request:

POST http://localhost:6060/oauth/token
Content-Type: application/x-www-form-urlencoded

username=user&password=password&grant_type=password&client_id=test-client&client_secret=noonewilleverguess

curl:

response:

Refreshing an access token:

This is where we need to save the value of the refresh_token field of the previous response and supply it in the request:

raw request:

curl:

response:

It looks exactly the same as in the case of retrieving an access token. This gives an ability to indefinitely keep toking alive without need to supply username and password unless refresh token becomes expired.

Accessing secured endpoint on a resource server

Spring OAuth2 Resource Server like majority other frameworks and platforms is configured to accept access token in the Authorization header (this is where access_token field comes into play):

raw request:

curl:

If access was set correctly, the response should be the following:

response:

Conclusion

This concludes our demo. The goal of it is to keep the configuration as simple as possible, but provide necessary tweaks to align with the other products in the field. There are many ways to improve it, for example, substitute hardcoded values (username and password) with an external source. Marcos Barbero wrote a great blog post about more advanced setup - Centralized Authorization with OAuth2 + JWT using Spring Boot 2.