Testing JWT Auth&Authz

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.

Test Pyramid

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:

  1. How to write automated tests simulating a bearer token authentication using JSON web tokens (JWT)

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

LibraryUserJwtAuthenticationConverterTest

Integration Test

Now do the same for the integration test. Open the existing class BookApiJwtAuthorizationTest and add the missing parts.

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.

Last updated

Was this helpful?