How should automated test for endpoints that need user context be written?

Viewed 119

Some of our endpoints that change data need user context. Our API uses OpenIdConnect for authentication. The automated API test suit uses the client credentials flow and hence does not have a user context. So i was wondering how are such problems solved elsewhere? how do you make such endpoints testable? Our UI uses the authorisation code flow.

What i tried already is thinking about the resource owner credentials grant and setup a service user for tests but our OAuth server has 2FA enabled and there is no way to pass on the TOTP code.

1 Answers

I agree with you that this is tricky. One option that can be useful in test environments is to use a mock Authorization Server, via a tool such as Wiremock. This will mean you can bypass 2FA etc, since that is not what you want to test.

Tests will then define canned responses from the Authorization Server, which the API under test uses, without needing any code changes. These responses can include a specific user in a JWT token that you create yourself, and also a JWKS payload that the API uses to validate tokens.

WIREMOCK EXAMPLE

My Node.js API shows an example of mocking an Authorization Server for testing, which might give you some ideas for your own solution. The API is temporarily configured to point to Wiremock endpoint instead of the real Authorization Server.

Related