Skip to content

Use DELEGATING_ACTOR constant and support audince parameter in token request to support multiple audiences in single audience claim#3029

Open
Bin4yi wants to merge 2 commits intowso2-extensions:masterfrom
Bin4yi:audience-validation
Open

Use DELEGATING_ACTOR constant and support audince parameter in token request to support multiple audiences in single audience claim#3029
Bin4yi wants to merge 2 commits intowso2-extensions:masterfrom
Bin4yi:audience-validation

Conversation

@Bin4yi
Copy link
Copy Markdown

@Bin4yi Bin4yi commented Feb 4, 2026

Proposed changes in this pull request

  • Introduced DELEGATING_ACTOR constant

OAuthAuthzMessageConext.java

  • Introduce audience parameter
  • setup getters and setters for the audience

AbstractAuthorizationGrantHandler.java

  • Only set default audiences if not already specified by grant handler in updateMessageContextToCreateNewToken() function

JWTTokenIssuer.java

  • Set explicitly requested audiences first (if present) in both of buildJWTToken() methods

When should this PR be merged

[Please describe any preconditions that need to be addressed before we
can merge this pull request.]

Follow up actions

[List any possible follow-up actions here; for instance, testing data
migrations, software that we need to install on staging and production
environments.]

Developer Checklist (Mandatory)

  • Complete the Developer Checklist in the related product-is issue to track any behavioral change or migration impact.

Checklist (for reviewing)

General

  • Is this PR explained thoroughly? All code changes must be accounted for in the PR description.
  • Is the PR labeled correctly?

Functionality

  • Are all requirements met? Compare implemented functionality with the requirements specification.
  • Does the UI work as expected? There should be no Javascript errors in the console; all resources should load. There should be no unexpected errors. Deliberately try to break the feature to find out if there are corner cases that are not handled.

Code

  • Do you fully understand the introduced changes to the code? If not ask for clarification, it might uncover ways to solve a problem in a more elegant and efficient way.
  • Does the PR introduce any inefficient database requests? Use the debug server to check for duplicate requests.
  • Are all necessary strings marked for translation? All strings that are exposed to users via the UI must be marked for translation.

Tests

  • Are there sufficient test cases? Ensure that all components are tested individually; models, forms, and serializers should be tested in isolation even if a test for a view covers these components.
  • If this is a bug fix, are tests for the issue in place? There must be a test case for the bug to ensure the issue won’t regress. Make sure that the tests break without the new code to fix the issue.
  • If this is a new feature or a significant change to an existing feature? has the manual testing spreadsheet been updated with instructions for manual testing?

Security

  • Confirm this PR doesn't commit any keys, passwords, tokens, usernames, or other secrets.
  • Are all UI and API inputs run through forms or serializers?
  • Are all external inputs validated and sanitized appropriately?
  • Does all branching logic have a default case?
  • Does this solution handle outliers and edge cases gracefully?
  • Are all external communications secured and restricted to SSL?

Documentation

  • Are changes to the UI documented in the platform docs? If this PR introduces new platform site functionality or changes existing ones, the changes should be documented.
  • Are changes to the API documented in the API docs? If this PR introduces new API functionality or changes existing ones, the changes must be documented.
  • Are reusable components documented? If this PR introduces components that are relevant to other developers (for instance a mixin for a view or a generic form) they should be documented in the Wiki.

Summary by CodeRabbit

Release Notes

  • New Features

    • Added support for delegated access token flows (RFC 8693) with delegating actor claims.
    • Added audiences support in OAuth tokens and JWT access tokens.
    • Introduced delegation request handling in token exchange flows.
    • Enhanced actor propagation logic during token refresh.
  • Bug Fixes

    • Improved token binding revocation to recognize both delegating and impersonating actors.

@CLAassistant
Copy link
Copy Markdown

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you sign our Contributor License Agreement before we can accept your contribution.
You have signed the CLA already but the status is still pending? Let us recheck it.

Comment on lines +305 to +308
// Set explicitly requested audiences first (if present)
if (request.getAudiences() != null && !request.getAudiences().isEmpty()) {
jwtClaimsSetBuilder.audience(request.getAudiences());
}
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Log Improvement Suggestion No: 1

Suggested change
// Set explicitly requested audiences first (if present)
if (request.getAudiences() != null && !request.getAudiences().isEmpty()) {
jwtClaimsSetBuilder.audience(request.getAudiences());
}
// Set explicitly requested audiences first (if present)
if (request.getAudiences() != null && !request.getAudiences().isEmpty()) {
if (log.isDebugEnabled()) {
log.debug("Setting explicitly requested audiences for client: " + request.getClientId() + ", audience count: " + request.getAudiences().size());
}
jwtClaimsSetBuilder.audience(request.getAudiences());
}

Comment on lines +346 to +349
// Set explicitly requested audiences first (if present)
if (request.getAudiences() != null && !request.getAudiences().isEmpty()) {
jwtClaimsSetBuilder.audience(request.getAudiences());
}
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Log Improvement Suggestion No: 2

Suggested change
// Set explicitly requested audiences first (if present)
if (request.getAudiences() != null && !request.getAudiences().isEmpty()) {
jwtClaimsSetBuilder.audience(request.getAudiences());
}
// Set explicitly requested audiences first (if present)
if (request.getAudiences() != null && !request.getAudiences().isEmpty()) {
if (log.isDebugEnabled()) {
log.debug("Setting explicitly requested audiences for consumer: " + request.getConsumerKey() + ", audience count: " + request.getAudiences().size());
}
jwtClaimsSetBuilder.audience(request.getAudiences());
}

Comment on lines +662 to +665
// Only set default audiences if not already specified by grant handler
if (tokReqMsgCtx.getAudiences() == null || tokReqMsgCtx.getAudiences().isEmpty()) {
tokReqMsgCtx.setAudiences(OAuth2Util.getOIDCAudience(consumerKey, oAuthAppBean));
}
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Log Improvement Suggestion No: 3

Suggested change
// Only set default audiences if not already specified by grant handler
if (tokReqMsgCtx.getAudiences() == null || tokReqMsgCtx.getAudiences().isEmpty()) {
tokReqMsgCtx.setAudiences(OAuth2Util.getOIDCAudience(consumerKey, oAuthAppBean));
}
// Only set default audiences if not already specified by grant handler
if (tokReqMsgCtx.getAudiences() == null || tokReqMsgCtx.getAudiences().isEmpty()) {
if (log.isDebugEnabled()) {
log.debug("No audiences specified by grant handler, setting default OIDC audiences for client: " + consumerKey);
}
tokReqMsgCtx.setAudiences(OAuth2Util.getOIDCAudience(consumerKey, oAuthAppBean));
} else {
if (log.isDebugEnabled()) {
log.debug("Using audiences specified by grant handler for client: " + consumerKey + ", audience count: " + tokReqMsgCtx.getAudiences().size());
}
}

Copy link
Copy Markdown
Contributor

@wso2-engineering wso2-engineering bot left a comment

Choose a reason for hiding this comment

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

AI Agent Log Improvement Checklist

⚠️ Warning: AI-Generated Review Comments

  • The log-related comments and suggestions in this review were generated by an AI tool to assist with identifying potential improvements. Purpose of reviewing the code for log improvements is to improve the troubleshooting capabilities of our products.
  • Please make sure to manually review and validate all suggestions before applying any changes. Not every code suggestion would make sense or add value to our purpose. Therefore, you have the freedom to decide which of the suggestions are helpful.

✅ Before merging this pull request:

  • Review all AI-generated comments for accuracy and relevance.
  • Complete and verify the table below. We need your feedback to measure the accuracy of these suggestions and the value they add. If you are rejecting a certain code suggestion, please mention the reason briefly in the suggestion for us to capture it.
Comment Accepted (Y/N) Reason
#### Log Improvement Suggestion No: 1
#### Log Improvement Suggestion No: 2
#### Log Improvement Suggestion No: 3

@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Mar 4, 2026

📝 Walkthrough

Walkthrough

The changes introduce delegation support throughout the OAuth token processing pipeline by adding a new DELEGATING_ACTOR constant, delegation-related fields and methods to message context classes, and updating token issuers, claim providers, and grant handlers to recognize and propagate delegation actor information alongside existing impersonation support.

Changes

Cohort / File(s) Summary
Constants
components/org.wso2.carbon.identity.oauth.common/.../OAuthConstants.java
Added new public constant DELEGATING_ACTOR with value "DELEGATING_ACTOR" for use throughout OAuth delegation flows.
Message Context Classes
components/org.wso2.carbon.identity.oauth/.../OAuthAuthzReqMessageContext.java, components/org.wso2.carbon.identity.oauth/.../OAuthTokenReqMessageContext.java
Added audiences field with getters/setters in authorization context; added isDelegationRequest flag with accessors in token context (note: setter body appears to assign to wrong field).
Token Issuers
components/org.wso2.carbon.identity.oauth/.../AccessTokenIssuer.java, components/org.wso2.carbon.identity.oauth/.../JWTTokenIssuer.java
Extended impersonation logging to handle delegation with delegating actor logging in AccessTokenIssuer; added explicit audiences injection from request into JWT claims in JWTTokenIssuer when audiences are present.
Token Binding & Revocation
components/org.wso2.carbon.identity.oauth/.../TokenBindingExpiryEventHandler.java
Added new validateDelegatingActorInitiatedRevocation() helper method and integrated delegation-based revocation checks with existing impersonation logic (note: method appears duplicated in patch).
Delegation Claim Provider
components/org.wso2.carbon.identity.oauth/.../DelegatedAccessTokenClaimProvider.java
New public class implementing JWTAccessTokenClaimProvider to inject {"act": {"sub": "<delegating_actor>"}} claims into JWT access tokens when delegation is active.
Grant Handlers
components/org.wso2.carbon.identity.oauth/.../AbstractAuthorizationGrantHandler.java, components/org.wso2.carbon.identity.oauth/.../RefreshGrantHandler.java
Added delegation attribute handling in extended attributes and conditional default audience assignment in AbstractAuthorizationGrantHandler; replaced propagateImpersonationInfo() with new propagateActorInfo() method in RefreshGrantHandler to handle both impersonating and delegating actors.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Suggested reviewers

  • piraveena

Poem

🐰 A delegation dance, now set in place,
Actors propagate through OAuth's embrace,
New constants, new claims, audiences flow,
Delegation and impersonation steal the show,
Token issuers leap, claim providers arise! ✨

🚥 Pre-merge checks | ✅ 1 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 7.14% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Description check ⚠️ Warning The PR description is incomplete and does not follow the repository's template structure with required sections like Purpose, Goals, Approach, User Stories, Release Notes, Documentation, etc. Complete the PR description using the full template. The changes extend beyond the stated audience parameter feature to include delegation flow support (DELEGATING_ACTOR constant, delegation-related code in multiple files). Provide details on Purpose, Goals, Approach, Release Notes, Documentation, Security checks, and Testing for all changes introduced.
✅ Passed checks (1 passed)
Check name Status Explanation
Title check ✅ Passed The PR title accurately describes the main changes: adding DELEGATING_ACTOR constant support and enabling multiple audiences in token requests via an audience parameter.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🧹 Nitpick comments (3)
components/org.wso2.carbon.identity.oauth/src/main/java/org/wso2/carbon/identity/oauth2/token/AccessTokenIssuer.java (1)

628-628: Remove leftover review artifact comment.

// ADD THIS BLOCK should not be committed in source.

Proposed cleanup
-            }  else if (tokReqMsgCtx.isDelegationRequest()) {          // ADD THIS BLOCK
+            }  else if (tokReqMsgCtx.isDelegationRequest()) {
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@components/org.wso2.carbon.identity.oauth/src/main/java/org/wso2/carbon/identity/oauth2/token/AccessTokenIssuer.java`
at line 628, In AccessTokenIssuer, remove the stray review artifact comment "//
ADD THIS BLOCK" found in the else-if handling tokReqMsgCtx.isDelegationRequest()
so the code contains only the conditional block; locate the occurrence in the
AccessTokenIssuer class (the else if (tokReqMsgCtx.isDelegationRequest()) line)
and delete the comment text, keeping the conditional and its logic intact and
formatted consistently with surrounding code.
components/org.wso2.carbon.identity.oauth/src/main/java/org/wso2/carbon/identity/oauth2/token/handlers/grant/AbstractAuthorizationGrantHandler.java (1)

626-630: Add a null guard before converting DELEGATING_ACTOR to string.

Line 628 can throw NullPointerException if delegation is marked but the property is absent.

Proposed hardening
-        if (tokReqMsgCtx.isDelegationRequest()) {
+        if (tokReqMsgCtx.isDelegationRequest() && tokReqMsgCtx.getProperty(DELEGATING_ACTOR) != null) {
             accessTokenExtendedAttributes =
                     addExtendedAttribute(DELEGATING_ACTOR, tokReqMsgCtx.getProperty(DELEGATING_ACTOR).toString(),
                     accessTokenExtendedAttributes);
         }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@components/org.wso2.carbon.identity.oauth/src/main/java/org/wso2/carbon/identity/oauth2/token/handlers/grant/AbstractAuthorizationGrantHandler.java`
around lines 626 - 630, The code calls
tokReqMsgCtx.getProperty(DELEGATING_ACTOR).toString() without checking for null,
which can NPE when isDelegationRequest() is true but the property is missing;
update the block in AbstractAuthorizationGrantHandler so you retrieve the
property via tokReqMsgCtx.getProperty(DELEGATING_ACTOR), check it for null (or
instanceof String) before calling toString(), and only call
addExtendedAttribute(DELEGATING_ACTOR, value, accessTokenExtendedAttributes)
when a non-null/value is present; reference tokReqMsgCtx, isDelegationRequest(),
getProperty(DELEGATING_ACTOR), addExtendedAttribute and
accessTokenExtendedAttributes when making the change.
components/org.wso2.carbon.identity.oauth/src/main/java/org/wso2/carbon/identity/oauth2/token/bindings/handlers/TokenBindingExpiryEventHandler.java (1)

380-394: Consolidate actor validation helpers to avoid logic drift.

Line 380 introduces logic that mirrors the existing impersonation validator. A shared helper would keep future actor-type changes consistent.

♻️ Suggested refactor
 private boolean validateImpersonatingActorInitiatedRevocation(
         AccessTokenDO accessTokenDO, String authenticatedSubjectIdentifier) {
-
-    boolean isImpersonationRequest = accessTokenDO.getAccessTokenExtendedAttributes() != null &&
-            accessTokenDO.getAccessTokenExtendedAttributes().getParameters() != null &&
-            accessTokenDO.getAccessTokenExtendedAttributes().getParameters().containsKey(IMPERSONATING_ACTOR);
-    if (isImpersonationRequest) {
-        return Objects.equals(accessTokenDO.getAccessTokenExtendedAttributes()
-                .getParameters().get(IMPERSONATING_ACTOR), authenticatedSubjectIdentifier);
-    }
-    return false;
+    return validateActorInitiatedRevocation(accessTokenDO, authenticatedSubjectIdentifier, IMPERSONATING_ACTOR);
 }
 
 private boolean validateDelegatingActorInitiatedRevocation(
         AccessTokenDO accessTokenDO, String authenticatedSubjectIdentifier) {
-
-    boolean isDelegationRequest = accessTokenDO.getAccessTokenExtendedAttributes() != null &&
-            accessTokenDO.getAccessTokenExtendedAttributes().getParameters() != null &&
-            accessTokenDO.getAccessTokenExtendedAttributes().getParameters()
-                    .containsKey(DELEGATING_ACTOR);
-    if (isDelegationRequest) {
-        return Objects.equals(
-                accessTokenDO.getAccessTokenExtendedAttributes()
-                        .getParameters().get(DELEGATING_ACTOR),
-                authenticatedSubjectIdentifier);
-    }
-    return false;
+    return validateActorInitiatedRevocation(accessTokenDO, authenticatedSubjectIdentifier, DELEGATING_ACTOR);
+}
+
+private boolean validateActorInitiatedRevocation(AccessTokenDO accessTokenDO,
+                                                 String authenticatedSubjectIdentifier,
+                                                 String actorKey) {
+    return accessTokenDO.getAccessTokenExtendedAttributes() != null
+            && accessTokenDO.getAccessTokenExtendedAttributes().getParameters() != null
+            && accessTokenDO.getAccessTokenExtendedAttributes().getParameters().containsKey(actorKey)
+            && Objects.equals(accessTokenDO.getAccessTokenExtendedAttributes()
+            .getParameters().get(actorKey), authenticatedSubjectIdentifier);
 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@components/org.wso2.carbon.identity.oauth/src/main/java/org/wso2/carbon/identity/oauth2/token/bindings/handlers/TokenBindingExpiryEventHandler.java`
around lines 380 - 394, The new validateDelegatingActorInitiatedRevocation
duplicates actor-validation logic; refactor by extracting the common
null-and-parameter-check into a shared helper (e.g.,
validateActorInitiatedRevocation(AccessTokenDO accessTokenDO, String actorKey,
String authenticatedSubjectIdentifier)) and replace
validateDelegatingActorInitiatedRevocation with a one-line call to that helper
using DELEGATING_ACTOR, then update any existing impersonation validator to call
the same helper so both actor types use the identical validation path; ensure
the helper checks accessTokenDO.getAccessTokenExtendedAttributes(), its
getParameters(), presence of actorKey, and equality against
authenticatedSubjectIdentifier.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In
`@components/org.wso2.carbon.identity.oauth/src/main/java/org/wso2/carbon/identity/oauth2/token/handlers/grant/RefreshGrantHandler.java`:
- Around line 326-337: In propagateActorInfo, guard the parameters map returned
by
tokenReqMessageContext.getOauth2AccessTokenReqDTO().getAccessTokenExtendedAttributes().getParameters()
before using it: check whether the params map is null and return early (or skip
actor extraction) if so, then proceed to read OAuthConstants.IMPERSONATING_ACTOR
and call StringUtils.isNotBlank on the retrieved value; this prevents an NPE
when extended attributes exist but their parameters map is absent.

In
`@components/org.wso2.carbon.identity.oauth/src/main/java/org/wso2/carbon/identity/oauth2/token/JWTTokenIssuer.java`:
- Around line 305-312: The explicit audience set via request.getAudiences() is
being overwritten by the scope-based fallback; update the logic in
JWTTokenIssuer so the scope-based jwtClaimsSetBuilder.audience(...) is only
applied when no explicit audiences were provided (i.e., when
request.getAudiences() is null or empty). Concretely, change the condition
around the scope check that uses request.getScope() and AUDIENCE to first verify
request.getAudiences() is null or empty before calling
jwtClaimsSetBuilder.audience(...); apply the same guarded check in the other
similar block handling audiences (the repeated lines referencing
jwtClaimsSetBuilder.audience and request.getScope()).

In
`@components/org.wso2.carbon.identity.oauth/src/main/java/org/wso2/carbon/identity/oauth2/token/OAuthTokenReqMessageContext.java`:
- Around line 223-226: The setter setDelegationRequest is assigning the wrong
field (it sets isImpersonationRequest instead of isDelegationRequest), so the
delegation flag never becomes true; update the method
setDelegationRequest(boolean delegationRequest) to assign the value to
isDelegationRequest (not isImpersonationRequest) so that isDelegationRequest()
reflects the passed value and delegation flow works correctly.

---

Nitpick comments:
In
`@components/org.wso2.carbon.identity.oauth/src/main/java/org/wso2/carbon/identity/oauth2/token/AccessTokenIssuer.java`:
- Line 628: In AccessTokenIssuer, remove the stray review artifact comment "//
ADD THIS BLOCK" found in the else-if handling tokReqMsgCtx.isDelegationRequest()
so the code contains only the conditional block; locate the occurrence in the
AccessTokenIssuer class (the else if (tokReqMsgCtx.isDelegationRequest()) line)
and delete the comment text, keeping the conditional and its logic intact and
formatted consistently with surrounding code.

In
`@components/org.wso2.carbon.identity.oauth/src/main/java/org/wso2/carbon/identity/oauth2/token/bindings/handlers/TokenBindingExpiryEventHandler.java`:
- Around line 380-394: The new validateDelegatingActorInitiatedRevocation
duplicates actor-validation logic; refactor by extracting the common
null-and-parameter-check into a shared helper (e.g.,
validateActorInitiatedRevocation(AccessTokenDO accessTokenDO, String actorKey,
String authenticatedSubjectIdentifier)) and replace
validateDelegatingActorInitiatedRevocation with a one-line call to that helper
using DELEGATING_ACTOR, then update any existing impersonation validator to call
the same helper so both actor types use the identical validation path; ensure
the helper checks accessTokenDO.getAccessTokenExtendedAttributes(), its
getParameters(), presence of actorKey, and equality against
authenticatedSubjectIdentifier.

In
`@components/org.wso2.carbon.identity.oauth/src/main/java/org/wso2/carbon/identity/oauth2/token/handlers/grant/AbstractAuthorizationGrantHandler.java`:
- Around line 626-630: The code calls
tokReqMsgCtx.getProperty(DELEGATING_ACTOR).toString() without checking for null,
which can NPE when isDelegationRequest() is true but the property is missing;
update the block in AbstractAuthorizationGrantHandler so you retrieve the
property via tokReqMsgCtx.getProperty(DELEGATING_ACTOR), check it for null (or
instanceof String) before calling toString(), and only call
addExtendedAttribute(DELEGATING_ACTOR, value, accessTokenExtendedAttributes)
when a non-null/value is present; reference tokReqMsgCtx, isDelegationRequest(),
getProperty(DELEGATING_ACTOR), addExtendedAttribute and
accessTokenExtendedAttributes when making the change.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: e2b5f4d4-0ae1-451b-987d-3bc29f7e5fd5

📥 Commits

Reviewing files that changed from the base of the PR and between 158822f and de9aeff.

📒 Files selected for processing (9)
  • components/org.wso2.carbon.identity.oauth.common/src/main/java/org/wso2/carbon/identity/oauth/common/OAuthConstants.java
  • components/org.wso2.carbon.identity.oauth/src/main/java/org/wso2/carbon/identity/oauth2/authz/OAuthAuthzReqMessageContext.java
  • components/org.wso2.carbon.identity.oauth/src/main/java/org/wso2/carbon/identity/oauth2/token/AccessTokenIssuer.java
  • components/org.wso2.carbon.identity.oauth/src/main/java/org/wso2/carbon/identity/oauth2/token/JWTTokenIssuer.java
  • components/org.wso2.carbon.identity.oauth/src/main/java/org/wso2/carbon/identity/oauth2/token/OAuthTokenReqMessageContext.java
  • components/org.wso2.carbon.identity.oauth/src/main/java/org/wso2/carbon/identity/oauth2/token/bindings/handlers/TokenBindingExpiryEventHandler.java
  • components/org.wso2.carbon.identity.oauth/src/main/java/org/wso2/carbon/identity/oauth2/token/handlers/claims/DelegatedAccessTokenClaimProvider.java
  • components/org.wso2.carbon.identity.oauth/src/main/java/org/wso2/carbon/identity/oauth2/token/handlers/grant/AbstractAuthorizationGrantHandler.java
  • components/org.wso2.carbon.identity.oauth/src/main/java/org/wso2/carbon/identity/oauth2/token/handlers/grant/RefreshGrantHandler.java

Comment on lines +326 to +337
private void propagateActorInfo(OAuthTokenReqMessageContext tokenReqMessageContext) {

log.debug("Checking for actor information in token request");
if (tokenReqMessageContext == null || tokenReqMessageContext.getOauth2AccessTokenReqDTO() == null ||
tokenReqMessageContext.getOauth2AccessTokenReqDTO().getAccessTokenExtendedAttributes() == null) {
return;
}

Map<String, String> params = tokenReqMessageContext.getOauth2AccessTokenReqDTO().getAccessTokenExtendedAttributes().getParameters();

String impersonator = params.get(OAuthConstants.IMPERSONATING_ACTOR);
if (StringUtils.isNotBlank(impersonator)) {
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Guard parameters before actor extraction to prevent NPEs.

On Line 334, getParameters() is used without a null check, and Line 336 dereferences it immediately. This can break refresh token issuance when extended attributes exist but their parameter map is absent.

🛠️ Suggested fix
 private void propagateActorInfo(OAuthTokenReqMessageContext tokenReqMessageContext) {
@@
-    Map<String, String> params = tokenReqMessageContext.getOauth2AccessTokenReqDTO().getAccessTokenExtendedAttributes().getParameters();
+    Map<String, String> params = tokenReqMessageContext.getOauth2AccessTokenReqDTO()
+            .getAccessTokenExtendedAttributes().getParameters();
+    if (params == null || params.isEmpty()) {
+        return;
+    }
 
     String impersonator = params.get(OAuthConstants.IMPERSONATING_ACTOR);
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@components/org.wso2.carbon.identity.oauth/src/main/java/org/wso2/carbon/identity/oauth2/token/handlers/grant/RefreshGrantHandler.java`
around lines 326 - 337, In propagateActorInfo, guard the parameters map returned
by
tokenReqMessageContext.getOauth2AccessTokenReqDTO().getAccessTokenExtendedAttributes().getParameters()
before using it: check whether the params map is null and return early (or skip
actor extraction) if so, then proceed to read OAuthConstants.IMPERSONATING_ACTOR
and call StringUtils.isNotBlank on the retrieved value; this prevents an NPE
when extended attributes exist but their parameters map is absent.

Comment on lines +305 to 312
// Set explicitly requested audiences first (if present)
if (request.getAudiences() != null && !request.getAudiences().isEmpty()) {
jwtClaimsSetBuilder.audience(request.getAudiences());
}

if (request.getScope() != null && Arrays.asList((request.getScope())).contains(AUDIENCE)) {
jwtClaimsSetBuilder.audience(Arrays.asList(request.getScope()));
}
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Explicit audiences can be overwritten by scope-based fallback.

At Line 310 and Line 351, the scope-based audience(...) call can overwrite the explicit audiences set at Line 306-307 and Line 347-348. This breaks the “prefer requested audiences” behavior.

Proposed fix
-        // Set explicitly requested audiences first (if present)
-        if (request.getAudiences() != null && !request.getAudiences().isEmpty()) {
-            jwtClaimsSetBuilder.audience(request.getAudiences());
-        }
-
-        if (request.getScope() != null && Arrays.asList((request.getScope())).contains(AUDIENCE)) {
+        boolean hasExplicitAudiences = request.getAudiences() != null && !request.getAudiences().isEmpty();
+        if (hasExplicitAudiences) {
+            jwtClaimsSetBuilder.audience(request.getAudiences());
+        } else if (request.getScope() != null && Arrays.asList((request.getScope())).contains(AUDIENCE)) {
             jwtClaimsSetBuilder.audience(Arrays.asList(request.getScope()));
         }
-        // Set explicitly requested audiences first (if present)
-        if (request.getAudiences() != null && !request.getAudiences().isEmpty()) {
-            jwtClaimsSetBuilder.audience(request.getAudiences());
-        }
-
-        if (request.getApprovedScope() != null && Arrays.asList((request.getApprovedScope())).contains(AUDIENCE)) {
+        boolean hasExplicitAudiences = request.getAudiences() != null && !request.getAudiences().isEmpty();
+        if (hasExplicitAudiences) {
+            jwtClaimsSetBuilder.audience(request.getAudiences());
+        } else if (request.getApprovedScope() != null
+                && Arrays.asList((request.getApprovedScope())).contains(AUDIENCE)) {
             jwtClaimsSetBuilder.audience(Arrays.asList(request.getApprovedScope()));
         }

Also applies to: 346-353

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@components/org.wso2.carbon.identity.oauth/src/main/java/org/wso2/carbon/identity/oauth2/token/JWTTokenIssuer.java`
around lines 305 - 312, The explicit audience set via request.getAudiences() is
being overwritten by the scope-based fallback; update the logic in
JWTTokenIssuer so the scope-based jwtClaimsSetBuilder.audience(...) is only
applied when no explicit audiences were provided (i.e., when
request.getAudiences() is null or empty). Concretely, change the condition
around the scope check that uses request.getScope() and AUDIENCE to first verify
request.getAudiences() is null or empty before calling
jwtClaimsSetBuilder.audience(...); apply the same guarded check in the other
similar block handling audiences (the repeated lines referencing
jwtClaimsSetBuilder.audience and request.getScope()).

Comment on lines +223 to +226
public void setDelegationRequest(boolean delegationRequest) {

isImpersonationRequest = delegationRequest;
}
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🔴 Critical

Setter updates the wrong flag (delegation never becomes true).

setDelegationRequest currently assigns isImpersonationRequest, so isDelegationRequest() remains false and delegation flow logic breaks.

Proposed fix
     public void setDelegationRequest(boolean delegationRequest) {
-
-        isImpersonationRequest = delegationRequest;
+        isDelegationRequest = delegationRequest;
     }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
public void setDelegationRequest(boolean delegationRequest) {
isImpersonationRequest = delegationRequest;
}
public void setDelegationRequest(boolean delegationRequest) {
isDelegationRequest = delegationRequest;
}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@components/org.wso2.carbon.identity.oauth/src/main/java/org/wso2/carbon/identity/oauth2/token/OAuthTokenReqMessageContext.java`
around lines 223 - 226, The setter setDelegationRequest is assigning the wrong
field (it sets isImpersonationRequest instead of isDelegationRequest), so the
delegation flag never becomes true; update the method
setDelegationRequest(boolean delegationRequest) to assign the value to
isDelegationRequest (not isImpersonationRequest) so that isDelegationRequest()
reflects the passed value and delegation flow works correctly.

@Bin4yi Bin4yi changed the title Support audince parameter in token request to support multiple audiences in single audience claim Use DELEGATING_ACTOR constant and support audince parameter in token request to support multiple audiences in single audience claim Mar 4, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants