In the first lab we extended an existing Microservice to an OAuth 2.0 and OpenID Connect 1.0 compliant Resource Server. Target of this lab is to add automated security tests for this Microservice.
Testing is an important topic. The DevOps culture also propagates the Automate All The Things. This applies to writing and automating tests as well.
The important point here is to write the right tests. A well-known approach is shown as part of the Test-Pyramid by Mike Cohn.
Most tests should be written as easy unit tests, this type of testing is quite cheap and provides fast feedback if things are still working as expected or anything has been broken.
Integration tests (aka tests on the service layer) are a bit more effort, often these tests depend on a runtime environment like a Java EE or Spring container. Typically, these tests run significantly slower and are often causing long CI/CD waiting times.
The tests with most effort are acceptance tests, UI tests or end2end tests which do a complete test of the application from api to data access layer. These tests run very long and are expensive to write and to maintain.
If you want to get more into this topic then check out this very good article for The Practical Test Pyramid.
In this lab we will write tests on the first layer (a unit test) and on the second layer (a security integration test).
Learning Targets
In this lab we will add security tests for an OAuth2/OIDC compliant resource server.
We will NOT use Keycloak as identity provider for this.
The tests run without the requirement of an identity provider.
In lab 4 you will learn how to:
How to write automated tests simulating a bearer token authentication using JSON web tokens (JWT)
How to write automated tests to verify authorization based on JWT.
Folder Contents
In the folder of lab 2 you find 2 applications:
library-server-initial: This is the application we will use as starting point for this lab
library-server-complete: This application is the completed reference for this lab
Start the Lab
In this lab we will implement:
A unit test to verify the LibraryUserJwtAuthenticationConverter.
An integration test to verify correct authentication & authorization for the books API using JWT
Please start this lab with project located in lab4/library-server-initial.
Unit Test
To implement the unit test open the existing class LibraryUserJwtAuthenticationConverterTest and add the missing parts of the test.
Now do the same for the integration test. Open the existing class BookApiJwtAuthorizationTest and add the missing parts.
packagecom.example.library.server.api;importcom.example.library.server.DataInitializer;importcom.example.library.server.api.resource.BookResource;importcom.fasterxml.jackson.databind.ObjectMapper;importorg.junit.jupiter.api.BeforeEach;importorg.junit.jupiter.api.DisplayName;importorg.junit.jupiter.api.Nested;importorg.junit.jupiter.api.Test;importorg.junit.jupiter.api.extension.ExtendWith;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.boot.test.context.SpringBootTest;importorg.springframework.http.MediaType;importorg.springframework.security.core.authority.SimpleGrantedAuthority;importorg.springframework.security.oauth2.jwt.Jwt;importorg.springframework.test.annotation.DirtiesContext;importorg.springframework.test.context.junit.jupiter.SpringExtension;importorg.springframework.test.web.servlet.MockMvc;importorg.springframework.test.web.servlet.setup.MockMvcBuilders;importorg.springframework.web.context.WebApplicationContext;importjava.util.Collections;importjava.util.UUID;importstaticorg.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.delete;importstaticorg.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.get;importstaticorg.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.post;importstaticorg.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.put;importstaticorg.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.jwt;importstaticorg.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity;importstaticorg.springframework.test.web.servlet.result.MockMvcResultMatchers.status;@ExtendWith(SpringExtension.class)@SpringBootTest@DirtiesContext@DisplayName("Verify book api")classBookApiJwtAuthorizationTest { @AutowiredprivateWebApplicationContext context;privateMockMvc mockMvc;privatefinalObjectMapper objectMapper =newObjectMapper(); @BeforeEachvoidsetup() {this.mockMvc=MockMvcBuilders.webAppContextSetup(context).apply(springSecurity()).build(); } @DisplayName("can authorize to") @NestedclassCanAuthorize { @Test @DisplayName("get list of books")voidverifyGetBooks() throwsException {mockMvc.perform(get("/books").with(jwt())).andExpect(status().isOk()); } @Test @DisplayName("get single book")voidverifyGetBook() throwsException {Jwt jwt =Jwt.withTokenValue("token").header("alg","none").claim("sub","bwanye").claim("groups",newString[] {"library_user"}).build(); mockMvc.perform(get("/books/{bookId}",DataInitializer.BOOK_CLEAN_CODE_IDENTIFIER).with(jwt(jwt))).andExpect(status().isOk()); } @Test @DisplayName("delete a book")voidverifyDeleteBook() throwsException { mockMvc.perform(delete("/books/{bookId}",DataInitializer.BOOK_DEVOPS_IDENTIFIER).with(jwt().authorities(newSimpleGrantedAuthority("ROLE_LIBRARY_CURATOR")))).andExpect(status().isNoContent()); } @Test @DisplayName("create a new book")voidverifyCreateBook() throwsException {BookResource bookResource =newBookResource(UUID.randomUUID(),"1234566","title","description",Collections.singletonList("Author"),false,null); mockMvc.perform(post("/books").contentType(MediaType.APPLICATION_JSON).content(objectMapper.writeValueAsString(bookResource)).with(jwt().authorities(newSimpleGrantedAuthority("ROLE_LIBRARY_CURATOR")))).andExpect(status().isCreated()); } @Test @DisplayName("update a book")voidverifyUpdateBook() throwsException {BookResource bookResource =newBookResource(DataInitializer.BOOK_SPRING_ACTION_IDENTIFIER,"9781617291203","Spring in Action: Covers Spring 5","Spring in Action, Fifth Edition is a hands-on guide to the Spring Framework, "+"updated for version 4. It covers the latest features, tools, and practices "+"including Spring MVC, REST, Security, Web Flow, and more. You'll move between "+"short snippets and an ongoing example as you learn to build simple and efficient "+"J2EE applications. Author Craig Walls has a special knack for crisp and "+"entertaining examples that zoom in on the features and techniques you really need.",Collections.singletonList("Craig Walls"),false,null); mockMvc.perform(put("/books/{bookId}",DataInitializer.BOOK_SPRING_ACTION_IDENTIFIER).contentType(MediaType.APPLICATION_JSON).content(objectMapper.writeValueAsString(bookResource)).with(jwt().authorities(newSimpleGrantedAuthority("ROLE_LIBRARY_CURATOR")))).andExpect(status().isOk()); } } @DisplayName("cannot authorize to") @NestedclassCannotAuthorize { @Test @DisplayName("get list of books")voidverifyGetBooksUnAuthenticated() throwsException {mockMvc.perform(get("/books")).andExpect(status().isUnauthorized()); } @Test @DisplayName("get single book")voidverifyGetBook() throwsException { mockMvc.perform(get("/books/{bookId}",DataInitializer.BOOK_CLEAN_CODE_IDENTIFIER)).andExpect(status().isUnauthorized()); } @Test @DisplayName("delete a book")voidverifyDeleteBookUnAuthorized() throwsException { mockMvc.perform(delete("/books/{bookId}",DataInitializer.BOOK_DEVOPS_IDENTIFIER)).andExpect(status().isUnauthorized()); } @Test @DisplayName("delete a book with wrong role")voidverifyDeleteBookWrongRole() throwsException { mockMvc.perform(delete("/books/{bookId}",DataInitializer.BOOK_DEVOPS_IDENTIFIER).with(jwt().authorities(newSimpleGrantedAuthority("ROLE_LIBRARY_USER")))).andExpect(status().isForbidden()); } @Test @DisplayName("create a new book")voidverifyCreateBookUnAuthorized() throwsException {BookResource bookResource =newBookResource(UUID.randomUUID(),"1234566","title","description",Collections.singletonList("Author"),false,null); mockMvc.perform(post("/books").contentType(MediaType.APPLICATION_JSON).content(objectMapper.writeValueAsString(bookResource))).andExpect(status().isUnauthorized()); } @Test @DisplayName("update a book")voidverifyUpdateBookUnAuthorized() throwsException {BookResource bookResource =newBookResource(DataInitializer.BOOK_SPRING_ACTION_IDENTIFIER,"9781617291203","Spring in Action: Covers Spring 5","Spring in Action, Fifth Edition is a hands-on guide to the Spring Framework, "+"updated for version 4. It covers the latest features, tools, and practices "+"including Spring MVC, REST, Security, Web Flow, and more. You'll move between "+"short snippets and an ongoing example as you learn to build simple and efficient "+"J2EE applications. Author Craig Walls has a special knack for crisp and "+"entertaining examples that zoom in on the features and techniques you really need.",Collections.singletonList("Craig Walls"),false,null); mockMvc.perform(put("/books/{bookId}",DataInitializer.BOOK_SPRING_ACTION_IDENTIFIER).contentType(MediaType.APPLICATION_JSON).content(objectMapper.writeValueAsString(bookResource))).andExpect(status().isUnauthorized()); } }}
Please also have a look at the other tests as well in the reference solution.
This ends lab 4. In the next lab 5 we will use a testing JWT server that works using self-signed JWT.
To continue with the JWT testing server please continue at Lab 5.