Testing an OAuth Secured API with Spring MVC

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.

基于STM32F407,使用DFS算法实现最短迷宫路径检索,分为三种模式:1.DEBUG模式,2. 训练模式,3. 主程序模式 ,DEBUG模式主要分析bug,测量必要数据,训练模式用于DFS算法训练最短路径,并将最短路径以链表形式存储Flash, 主程序模式从Flash中….zip项目工程资源经过严格测试可直接运行成功且功能正常的情况才上传,可轻松复刻,拿到资料包后可轻松复现出一样的项目,本人系统开发经验充足(全领域),有任何使用问题欢迎随时与我联系,我会及时为您解惑,提供帮助。 【资源内容】:包含完整源码+工程文件+说明(如有)等。答辩评审平均分达到96分,放心下载使用!可轻松复现,设计报告也可借鉴此项目,该资源内项目代码都经过测试运行成功,功能ok的情况下才上传的。 【提供帮助】:有任何使用问题欢迎随时与我联系,我会及时解答解惑,提供帮助 【附带帮助】:若还需要相关开发工具、学习资料等,我会提供帮助,提供资料,鼓励学习进步 【项目价值】:可用在相关项目设计中,皆可应用在项目、毕业设计、课程设计、期末/期中/大作业、工程实训、大创等学科竞赛比赛、初期项目立项、学习/练手等方面,可借鉴此优质项目实现复刻,设计报告也可借鉴此项目,也可基于此项目来扩展开发出更多功能 下载后请首先打开README文件(如有),项目工程可直接复现复刻,如果基础还行,也可在此程序基础上进行修改,以实现其它功能。供开源学习/技术交流/学习参考,勿用于商业用途。质量优质,放心下载使用。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值