Skip to content

Support JWK Selection Strategy #4

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

GuusArts
Copy link
Owner

@GuusArts GuusArts commented Mar 24, 2025

User description

Closes spring-projectsgh-16170


PR Type

Enhancement


Description

  • Introduced a customizable JWK selection strategy in NimbusJwtEncoder.

  • Added a new setJwkSelector method to configure JWK selection logic.

  • Replaced hardcoded JWK selection logic with a configurable converter.

  • Updated error handling for JWK selection to improve flexibility.


Changes walkthrough 📝

Relevant files
Enhancement
NimbusJwtEncoder.java
Introduced customizable JWK selection strategy                     

oauth2/oauth2-jose/src/main/java/org/springframework/security/oauth2/jwt/NimbusJwtEncoder.java

  • Added a Converter, JWK> for JWK selection.
  • Introduced setJwkSelector method for custom JWK selection logic.
  • Replaced hardcoded JWK selection logic with the new converter.
  • Updated error messages for JWK selection failures.
  • +28/-13 

    Need help?
  • Type /help how to ... in the comments thread for any questions about Qodo Merge usage.
  • Check out the documentation for more information.
  • Closes spring-projectsgh-16170
    
    Signed-off-by: douxiaofeng99 <18600127780@163.com>
    Copy link

    sourcery-ai bot commented Mar 24, 2025

    Reviewer's Guide by Sourcery

    This pull request introduces a JWK selection strategy to the NimbusJwtEncoder. This allows users to specify how to select a JWK when multiple candidates are available for a given signing algorithm. A default strategy is provided that throws an exception if multiple JWKs are found. Users can provide a custom strategy by calling the setJwkSelector method.

    Updated class diagram for NimbusJwtEncoder

    classDiagram
      class NimbusJwtEncoder {
        -JWKSource jwkSource
        -Converter~List~JWK~, JWK~ jwkSelector
        +NimbusJwtEncoder(JWKSource jwkSource)
        +setJwkSelector(Converter~List~JWK~, JWK~ jwkSelector)
        +Jwt encode(JwtEncoderParameters parameters)
        -JWK selectJwk(JwsHeader headers)
        -String serialize(JwsHeader headers, JwtClaimsSet claims, JWK jwk)
      }
      NimbusJwtEncoder -- JWKSource : has
      NimbusJwtEncoder -- Converter : uses
    
    Loading

    File-Level Changes

    Change Details Files
    Introduced a JWK selection strategy to allow users to specify how to select a JWK when multiple candidates are available for a given signing algorithm.
    • Added a jwkSelector field of type Converter<List<JWK>, JWK> to the NimbusJwtEncoder class.
    • Initialized the jwkSelector with a default implementation that throws an exception if multiple JWKs are found or if no JWKs are found.
    • Added a setJwkSelector method to allow users to set a custom JWK selection strategy.
    • Modified the selectJwk method to use the jwkSelector to select a JWK from the list of candidates.
    oauth2/oauth2-jose/src/main/java/org/springframework/security/oauth2/jwt/NimbusJwtEncoder.java

    Tips and commands

    Interacting with Sourcery

    • Trigger a new review: Comment @sourcery-ai review on the pull request.
    • Continue discussions: Reply directly to Sourcery's review comments.
    • Generate a GitHub issue from a review comment: Ask Sourcery to create an
      issue from a review comment by replying to it. You can also reply to a
      review comment with @sourcery-ai issue to create an issue from it.
    • Generate a pull request title: Write @sourcery-ai anywhere in the pull
      request title to generate a title at any time. You can also comment
      @sourcery-ai title on the pull request to (re-)generate the title at any time.
    • Generate a pull request summary: Write @sourcery-ai summary anywhere in
      the pull request body to generate a PR summary at any time exactly where you
      want it. You can also comment @sourcery-ai summary on the pull request to
      (re-)generate the summary at any time.
    • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
      request to (re-)generate the reviewer's guide at any time.
    • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
      pull request to resolve all Sourcery comments. Useful if you've already
      addressed all the comments and don't want to see them anymore.
    • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
      request to dismiss all existing Sourcery reviews. Especially useful if you
      want to start fresh with a new review - don't forget to comment
      @sourcery-ai review to trigger a new review!
    • Generate a plan of action for an issue: Comment @sourcery-ai plan on
      an issue to generate a plan of action for it.

    Customizing Your Experience

    Access your dashboard to:

    • Enable or disable review features such as the Sourcery-generated pull request
      summary, the reviewer's guide, and others.
    • Change the review language.
    • Add, remove or edit custom review instructions.
    • Adjust other review settings.

    Getting Help

    Copy link

    Qodo Merge was enabled for this repository. To continue using it, please link your Git account with your Qodo account here.

    PR Reviewer Guide 🔍

    Here are some key observations to aid the review process:

    ⏱️ Estimated effort to review: 2 🔵🔵⚪⚪⚪
    🧪 No relevant tests
    🔒 No security concerns identified
    ⚡ Recommended focus areas for review

    Null Check

    The null check in setJwkSelector method uses a non-standard style with no spaces around the comparison operator, which differs from the project's usual style. Consider using the Assert utility instead for consistency.

    if(null!=jwkSelector)
    	this.jwkSelector = jwkSelector;
    Error Message

    The error message in the default jwkSelector includes a reference to NimbusJwsEncoder#setJwkSelector which appears to be incorrect - it should reference NimbusJwtEncoder instead.

    "please specify a selector in NimbusJwsEncoder#setJwkSelector",jwks.get(0).getAlgorithm()));

    Copy link

    qodo-merge-pro bot commented Mar 24, 2025

    Qodo Merge was enabled for this repository. To continue using it, please link your Git account with your Qodo account here.

    PR Code Suggestions ✨

    Explore these optional code suggestions:

    CategorySuggestion                                                                                                                                    Impact
    Possible issue
    Fix incorrect class name

    The error message references NimbusJwsEncoder#setJwkSelector but the actual
    class name is NimbusJwtEncoder. This will confuse users trying to follow the
    error message instructions.

    oauth2/oauth2-jose/src/main/java/org/springframework/security/oauth2/jwt/NimbusJwtEncoder.java [90-101]

     private Converter<List<JWK>, JWK> jwkSelector= (jwks)->{
         if (jwks.size() > 1) {
             throw new JwtEncodingException(String.format(
                     "Failed to select a key since there are multiple for the signing algorithm [%s]; " +
    -                        "please specify a selector in NimbusJwsEncoder#setJwkSelector",jwks.get(0).getAlgorithm()));
    +                        "please specify a selector in NimbusJwtEncoder#setJwkSelector",jwks.get(0).getAlgorithm()));
         }
         if (jwks.isEmpty()) {
             throw new JwtEncodingException(
                     String.format(ENCODING_ERROR_MESSAGE_TEMPLATE, "Failed to select a JWK signing key"));
         }
         return jwks.get(0);
     };
    • Apply this suggestion
    Suggestion importance[1-10]: 8

    __

    Why: The error message incorrectly references "NimbusJwsEncoder" instead of "NimbusJwtEncoder", which would confuse users trying to follow the instructions. This is an important fix for user experience and documentation accuracy.

    Medium
    General
    Improve code style consistency

    The null check uses a non-standard style with the null value on the left side of
    the comparison. Additionally, the method is missing braces for the conditional
    block, which is inconsistent with the project's coding style and could lead to
    maintenance issues.

    oauth2/oauth2-jose/src/main/java/org/springframework/security/oauth2/jwt/NimbusJwtEncoder.java [119-122]

     public void setJwkSelector(Converter<List<JWK>, JWK> jwkSelector) {
    -    if(null!=jwkSelector)
    +    if (jwkSelector != null) {
             this.jwkSelector = jwkSelector;
    +    }
     }

    [Suggestion has been applied]

    Suggestion importance[1-10]: 5

    __

    Why: The suggestion improves code style consistency by standardizing the null check format and adding braces to the conditional block, which aligns with common Java coding practices and makes the code more maintainable.

    Low
    • More

    Copy link

    @sourcery-ai sourcery-ai bot left a comment

    Choose a reason for hiding this comment

    The reason will be displayed to describe this comment to others. Learn more.

    Hey @GuusArts - I've reviewed your changes - here's some feedback:

    Overall Comments:

    • Consider using a functional interface instead of Converter<List<JWK>, JWK> for jwkSelector to improve readability.
    • The exception message in the default jwkSelector could be improved to suggest configuring a JwkSelector.
    Here's what I looked at during the review
    • 🟡 General issues: 1 issue found
    • 🟢 Security: all looks good
    • 🟢 Testing: all looks good
    • 🟢 Complexity: all looks good
    • 🟢 Documentation: all looks good

    Sourcery is free for open source - if you like our reviews please consider sharing them ✨
    Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

    Comment on lines +119 to +122
    public void setJwkSelector(Converter<List<JWK>, JWK> jwkSelector) {
    if(null!=jwkSelector)
    this.jwkSelector = jwkSelector;
    }
    Copy link

    Choose a reason for hiding this comment

    The reason will be displayed to describe this comment to others. Learn more.

    suggestion: Clarify handling of a null parameter in setJwkSelector.

    Currently, passing a null value to setJwkSelector results in no change. It may be clearer to either explicitly disallow null (by throwing an exception) or document that null is a no-op to avoid unintentional mistakes by clients.

    Suggested change
    public void setJwkSelector(Converter<List<JWK>, JWK> jwkSelector) {
    if(null!=jwkSelector)
    this.jwkSelector = jwkSelector;
    }
    public void setJwkSelector(Converter<List<JWK>, JWK> jwkSelector) {
    if(jwkSelector == null) {
    throw new IllegalArgumentException("jwkSelector cannot be null");
    }
    this.jwkSelector = jwkSelector;
    }

    Comment on lines +119 to +122
    public void setJwkSelector(Converter<List<JWK>, JWK> jwkSelector) {
    if(null!=jwkSelector)
    this.jwkSelector = jwkSelector;
    }

    Choose a reason for hiding this comment

    The reason will be displayed to describe this comment to others. Learn more.

    Suggestion: Improve code style consistency

    Suggested change
    public void setJwkSelector(Converter<List<JWK>, JWK> jwkSelector) {
    if(null!=jwkSelector)
    this.jwkSelector = jwkSelector;
    }
    public void setJwkSelector(Converter<List<JWK>, JWK> jwkSelector) {
    if (jwkSelector != null) {
    this.jwkSelector = jwkSelector;
    }
    }

    Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
    Projects
    None yet
    Development

    Successfully merging this pull request may close these issues.

    The selectJwk method of NimbusJwtEncoder class should not throw Exception when jwks size great than one
    2 participants