Course – LSS – NPI (cat=Spring Security)
announcement - icon

If you're working on a Spring Security (and especially an OAuth) implementation, definitely have a look at the Learn Spring Security course:


1. Overview

In this article, we’re going to show how we can test an API which is secured using OAuth with the Spring MVC test support.

Note: this article is using the Spring OAuth legacy project.

2. Authorization and Resource Server

For a tutorial on how to setup an authorization and resource server, look through this previous article: Spring REST API + OAuth2 + AngularJS.

Our authorization server uses JdbcTokenStore and defined a client with id “fooClientIdPassword” and password “secret”, and supports the password grant type.

The resource server restricts the /employee URL to the ADMIN role.

Starting with Spring Boot version 1.5.0 the security adapter takes priority over the OAuth resource adapter, so in order to reverse the order, we have to annotate the WebSecurityConfigurerAdapter class with @Order(SecurityProperties.ACCESS_OVERRIDE_ORDER).

Otherwise, Spring will attempt to access requested URLs based on the Spring Security rules instead of Spring OAuth rules, and we would receive a 403 error when using token authentication.

3. Defining a Sample API

First, let’s create a simple POJO called Employee with two properties that we will manipulate through the API:

public class Employee {
    private String email;
    private String name;
    // standard constructor, getters, setters

Next, let’s define a controller with two request mappings, for getting and saving an Employee object to a list:

public class EmployeeController {

    private List<Employee> employees = new ArrayList<>();

    public Optional<Employee> getEmployee(@RequestParam String email) {
          .filter(x -> x.getEmail().equals(email)).findAny();

    public void postMessage(@RequestBody Employee employee) {

Keep in mind that in order to make this work, we need an additional JDK8 Jackson module. Otherwise, the Optional class will not be serialized/deserialized properly. The latest version of jackson-datatype-jdk8 can be downloaded from Maven Central.

4. Testing the API

4.1. Setting Up the Test Class

To test our API, we will create a test class annotated with @SpringBootTest that uses the AuthorizationServerApplication class to read the application configuration.

For testing a secured API with Spring MVC test support, we need to inject the WebAppplicationContext and Spring Security Filter Chain beans. We’ll use these to obtain a MockMvc instance before the tests are run:

@SpringBootTest(classes = AuthorizationServerApplication.class)
public class OAuthMvcTest {

    private WebApplicationContext wac;

    private FilterChainProxy springSecurityFilterChain;

    private MockMvc mockMvc;

    public void setup() {
        this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac)

4.2. Obtaining an Access Token

Simply put, an APIs secured with OAuth2 expects to receive a the Authorization header with a value of Bearer <access_token>.

In order to send the required Authorization header, we first need to obtain a valid access token by making a POST request to the /oauth/token endpoint. This endpoint requires an HTTP Basic authentication, with the id and secret of the OAuth client, and a list of parameters specifying the client_id, grant_type, username, and password.

Using Spring MVC test support, the parameters can be wrapped in a MultiValueMap and the client authentication can be sent using the httpBasic method.

Let’s create a method that sends a POST request to obtain the token and reads the access_token value from the JSON response:

private String obtainAccessToken(String username, String password) throws Exception {
    MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
    params.add("grant_type", "password");
    params.add("client_id", "fooClientIdPassword");
    params.add("username", username);
    params.add("password", password);

    ResultActions result 
      = mockMvc.perform(post("/oauth/token")

    String resultString = result.andReturn().getResponse().getContentAsString();

    JacksonJsonParser jsonParser = new JacksonJsonParser();
    return jsonParser.parseMap(resultString).get("access_token").toString();

4.3. Testing GET and POST Requests

The access token can be added to a request using the header(“Authorization”, “Bearer “+ accessToken) method.

Let’s attempt to access one of our secured mappings without an Authorization header and verify that we receive an unauthorized status code:

public void givenNoToken_whenGetSecureRequest_thenUnauthorized() throws Exception {
      .param("email", EMAIL))

We have specified that only users with a role of ADMIN can access the /employee URL. Let’s create a test in which we obtain an access token for a user with USER role and verify that we receive a forbidden status code:

public void givenInvalidRole_whenGetSecureRequest_thenForbidden() throws Exception {
    String accessToken = obtainAccessToken("user1", "pass");
      .header("Authorization", "Bearer " + accessToken)
      .param("email", "[email protected]"))

Next, let’s test our API using a valid access token, by sending a POST request to create an Employee object, then a GET request to read the object created:

public void givenToken_whenPostGetSecureRequest_thenOk() throws Exception {
    String accessToken = obtainAccessToken("admin", "nimda");

    String employeeString = "{\"email\":\"[email protected]\",\"name\":\"Jim\"}";
      .header("Authorization", "Bearer " + accessToken)

      .param("email", "[email protected]")
      .header("Authorization", "Bearer " + accessToken)
      .andExpect(jsonPath("$.name", is("Jim")));

5. Conclusion

In this quick tutorial, we have demonstrated how we can test an OAuth-secured API using the Spring MVC test support.

The full source code of the examples can be found in the GitHub project.

To run the test, the project has an mvc profile that can be executed using the command mvn clean install -Pmvc.

Course – LSS (cat=Security/Spring Security)

I just announced the new Learn Spring Security course, including the full material focused on the new OAuth2 stack in Spring Security:

res – Security (video) (cat=Security/Spring Security)
Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.