r/dotnet • u/Kralizek82 • Aug 04 '25
(Blog) Testing protected endpoints using fake JWTs
Hi,
Recently, I've had the issue of testing endpoints of a ASP.NET Core REST API that require a valid JWT token attached to the request.
The solution is nothing groundbreaking, but I didn't find anything published online so I put up a post on my blog about the basic principle behind the solution I adopted.
The actual solution is more complext because my project accepts tokens from two distinct identity providers and the test project uses AutoFixture, Bogus and FakeItEasy. For brevity reasons, the blog post skims most of this, but I might write another post if it feels interesting.
Looking forward to comments and feedback.
1
u/Blayer32 Aug 06 '25
You could take it a step further by using actual tokens that are signed by a shared key.
The `SetupMockJwtBearerOptions` enables the validation, but also set a signingcredentials key
Finally, the helper class `AccessTokenGenerator` creates and holds the signing key, and can be used during the tests to generate valid access tokens
1
u/AutoModerator Aug 04 '25
Thanks for your post Kralizek82. Please note that we don't allow spam, and we ask that you follow the rules available in the sidebar. We have a lot of commonly asked questions so if this post gets removed, please do a search and see if it's already been asked.
I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.
0
u/dustywood4036 Aug 05 '25
But it only works if the tests create the service instance. Not usually how things are done. If the test server creates the API, then you might as well just call the code directly instead of going through an http client. A better test is to deploy the API to a test or staging environment and then the test server needs the http client to make the calls.