Testing an OAuth Secured API with Spring MVC

本文展示如何使用Spring MVC测试支持来测试受OAuth保护的API,包括设置测试类、获取访问令牌及测试GET和POST请求。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

I just announced the newSpring Security 5 modules (primarily focused on OAuth2) in the course:

>> CHECK OUT LEARN SPRING SECURITY

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.

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:

1

2

3

4

5

6

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:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

@Controller

public class EmployeeController {

 

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

 

    @GetMapping("/employee")

    @ResponseBody

    public Optional<Employee> getEmployee(@RequestParam String email) {

        return employees.stream()

          .filter(x -> x.getEmail().equals(email)).findAny();

    }

 

    @PostMapping("/employee")

    @ResponseStatus(HttpStatus.CREATED)

    public void postMessage(@RequestBody Employee employee) {

        employees.add(employee);

    }

}

Keep in mind that in order to make this work, we need an additional JDK8 Jackson module. Otherwise, the Optionalclass 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 AuthorizationServerApplicationclass 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:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

@RunWith(SpringRunner.class)

@WebAppConfiguration

@SpringBootTest(classes = AuthorizationServerApplication.class)

public class OAuthMvcTest {

 

    @Autowired

    private WebApplicationContext wac;

 

    @Autowired

    private FilterChainProxy springSecurityFilterChain;

 

    private MockMvc mockMvc;

 

    @Before

    public void setup() {

        this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac)

          .addFilter(springSecurityFilterChain).build();

    }

}

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_idgrant_typeusername, 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:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

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")

        .params(params)

        .with(httpBasic("fooClientIdPassword","secret"))

        .accept("application/json;charset=UTF-8"))

        .andExpect(status().isOk())

        .andExpect(content().contentType("application/json;charset=UTF-8"));

 

    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:

1

2

3

4

5

6

@Test

public void givenNoToken_whenGetSecureRequest_thenUnauthorized() throws Exception {

    mockMvc.perform(get("/employee")

      .param("email", EMAIL))

      .andExpect(status().isUnauthorized());

}

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:

1

2

3

4

5

6

7

8

@Test

public void givenInvalidRole_whenGetSecureRequest_thenForbidden() throws Exception {

    String accessToken = obtainAccessToken("user1", "pass");

    mockMvc.perform(get("/employee")

      .header("Authorization", "Bearer " + accessToken)

      .param("email", "jim@yahoo.com"))

      .andExpect(status().isForbidden());

}

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:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

@Test

public void givenToken_whenPostGetSecureRequest_thenOk() throws Exception {

    String accessToken = obtainAccessToken("admin", "nimda");

 

    String employeeString = "{\"email\":\"jim@yahoo.com\",\"name\":\"Jim\"}";

         

    mockMvc.perform(post("/employee")

      .header("Authorization", "Bearer " + accessToken)

      .contentType(application/json;charset=UTF-8)

      .content(employeeString)

      .accept(application/json;charset=UTF-8))

      .andExpect(status().isCreated());

 

    mockMvc.perform(get("/employee")

      .param("email", "jim@yahoo.com")

      .header("Authorization", "Bearer " + accessToken)

      .accept("application/json;charset=UTF-8"))

      .andExpect(status().isOk())

      .andExpect(content().contentType(application/json;charset=UTF-8))

      .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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值