NetDevPack / NetDevPack/Security.Jwt

JwtTokenService on startup creates as many credentials as there are concurrent requests

Open
#65 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
C#
Stars
297
Forks
48
PR merge metrics
No merged PRs in 30d

Description

JwtTokenService is a scoped service and it doesn't have any locking mechanisms.

In case a credential needs to be created (for example on first start or credential expire) it will create as many keys as there are concurrent simultaneous requests.
This is an issue because:

  1. Why my system now has 2 or more keys?
  2. If amount of requests is huge you can create a huge amount of keys. In case you create >AlgorithmsToKeep you will have an issue to validate tokens because JwtServiceValidationHandler will not return the keys to you.

To resolve JwtTokenService might need to become a singleton, resolve IJsonWebKeyStore from a scope and apply some locking.
For optimization you can apply double-locking only if the key is subject to be renewed.

For now I made a workaround like this (somewhere in a singleton returning access tokens):

        await _currentCreds.WaitAsync(cancellationToken);
        try
        {
            var jwtService = httpContext.RequestServices.GetRequiredService<IJwtService>();
            credentials = await jwtService.GetCurrentSigningCredentials();
        }
        finally
        {
            _currentCreds.Release();
        }

This is a bit not ideal as it always locks but better than having lots of tokens created at the same time.

BTW GetCurrentSigningCredentials() I think should also accept CancellationToken as DB store can have some time to create creds and user might already cancel his login?

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with JwtTokenService.GetCurrentSigningCredentials(), then inspect IJsonWebKeyStore and JwtServiceValidationHandler to understand credential creation and key retention. Reproduce concurrent first-start or renewal requests, then verify that only one credential is created, excess keys are not produced, and cancellation behavior is covered if changed.

Written by the indexing model from the issue text.

Assessment

Tech stack
csharp
Domain
authentication, security
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.