Skip to content

Add SDK methods for agent sub organization auth#11

Merged
HasiniSama merged 6 commits into
asgardeo:mainfrom
HasiniSama:agent-organization-auth
May 15, 2026
Merged

Add SDK methods for agent sub organization auth#11
HasiniSama merged 6 commits into
asgardeo:mainfrom
HasiniSama:agent-organization-auth

Conversation

@HasiniSama
Copy link
Copy Markdown
Contributor

@HasiniSama HasiniSama commented May 15, 2026

Purpose

$subject

New method introduced:

  • get_org_authorization_url(scopes, org_discovery_type, value, ...): Builds an authorization URL targeting a specific sub-organization, identified by org ID, handle, org parameter, or email domain discovery.
  • get_org_authorization_url_with_pkce(...) : Same as above, with PKCE (S256) for public clients.
  • switch_token_to_organization(token, switching_organization, scopes): Exchanges an existing access token for one scoped to a target sub-organization using the organization_switch grant type.
  • get_organization_agent_token(switching_organization, agent_scopes, org_scopes,...) : To directly get the switched organization token without calling get_agent_token.

Issue: wso2/product-is#27526

Summary by CodeRabbit

  • New Features

    • Organization-scoped authorization URL generation with multiple discovery options and PKCE variant (returns verifier).
    • Organization agent token acquisition and token switching via an organization-switch grant.
    • Reserved-query-parameter protection when building authorization URLs.
  • Bug Fixes

    • Improved error handling and logging for delegated sign-in/OBO flows (exception chaining retained).
  • Documentation

    • Expanded README and API reference with new auth flows, examples, and method docs.

Review Change Stack

@HasiniSama HasiniSama changed the title Add SDK method for agent sub organization auth Add SDK methods for agent sub organization auth May 15, 2026
Comment thread packages/asgardeo-ai/src/asgardeo_ai/agent_auth_manager.py Outdated
Comment thread packages/asgardeo-ai/src/asgardeo_ai/agent_auth_manager.py Outdated
Comment thread packages/asgardeo-ai/src/asgardeo_ai/agent_auth_manager.py Outdated
Comment thread packages/asgardeo-ai/src/asgardeo_ai/agent_auth_manager.py Outdated
@HasiniSama
Copy link
Copy Markdown
Contributor Author

@CodeRabbit review

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented May 15, 2026

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented May 15, 2026

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 84235101-04a7-404d-bc81-ccb2c92b9a44

📥 Commits

Reviewing files that changed from the base of the PR and between f44640e and f123650.

📒 Files selected for processing (2)
  • packages/asgardeo-ai/README.md
  • packages/asgardeo-ai/src/asgardeo_ai/agent_auth_manager.py
✅ Files skipped from review due to trivial changes (1)
  • packages/asgardeo-ai/README.md
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/asgardeo-ai/src/asgardeo_ai/agent_auth_manager.py

📝 Walkthrough

Walkthrough

Adds organization-scoped authorization URL builders (standard + PKCE), methods to obtain and switch agent tokens into sub-organizations, token client support for an organization_switch grant, and corresponding README/API documentation updates.

Changes

Organization-Scoped Authentication

Layer / File(s) Summary
Organization Token Grant Type Support
packages/asgardeo/src/asgardeo/auth/client.py, packages/asgardeo-ai/src/asgardeo_ai/agent_auth_manager.py
AsgardeoTokenClient.get_token adds organization_switch grant handling (validates token and switching_organization, includes them in the request, and forwards optional scope). File header copyright ranges updated.
Organization Discovery Types & Authorization URL Builders
packages/asgardeo-ai/src/asgardeo_ai/agent_auth_manager.py
Adds OrgDiscoveryType literal and AgentAuthManager.get_org_authorization_url(...) plus get_org_authorization_url_with_pkce(...) to build /oauth2/authorize URLs from discovery type + value, scope, state, optional resource, conditional fidp=OrganizationSSO (unless isEnhancedOrgAuth), optional requested_actor, PKCE challenge handling, reserved-key protection for **kwargs, and returns (auth_url, state) or (auth_url, state, code_verifier).
Organization Token Switching Orchestration
packages/asgardeo-ai/src/asgardeo_ai/agent_auth_manager.py
Adds get_organization_agent_token(...) (validates switching_organization, fetches agent token, delegates to switch_token_to_organization(...)) and switch_token_to_organization(...) which calls token client with grant_type=organization_switch and optional scope. CIBA OBO error handling updated to log stack traces and re-raise with chaining.
Docs: README & API Reference
packages/asgardeo-ai/README.md
Expands README with more detailed feature bullets, updated Quick Start examples (including auth_code and OBO exchange), and an extended API Reference documenting new AgentAuthManager constructor and methods.

🎯 4 (Complex) | ⏱️ ~45 minutes

Sequence Diagram

sequenceDiagram
  participant Client
  participant AgentAuthManager
  participant AsgardeoTokenClient
  participant AuthServer
  Client->>AgentAuthManager: request org auth URL / initiate agent token flow
  AgentAuthManager->>AsgardeoTokenClient: get_agent_token(agent_scopes)
  AsgardeoTokenClient->>AuthServer: token request (client credentials)
  AuthServer->>AsgardeoTokenClient: returns agent token
  AgentAuthManager->>AsgardeoTokenClient: get_token(grant_type=organization_switch, token, switching_organization, scope)
  AsgardeoTokenClient->>AuthServer: organization_switch token request
  AuthServer->>AsgardeoTokenClient: returns org-scoped token
  AsgardeoTokenClient->>AgentAuthManager: org-scoped token
  AgentAuthManager->>Client: returns org-scoped token / auth URL (+code_verifier if PKCE)
Loading

🐰 Authorization flows now dance with org discovery bright,
Where tokens switch their scope with PKCE's cryptic might,
Sub-organizations join the fray with state and resource true,
The Asgardeo rabbit hops through auth mechanisms new! 🌟

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Description check ⚠️ Warning The PR description covers the Purpose and outlines the new methods introduced, but lacks several required template sections including Goals, Approach, User Stories, Release Note, Documentation, Training, Certification, Marketing, Automation Tests, Security Checks, Samples, and other sections. Complete the PR description by adding the missing required sections from the template, particularly Goals, Approach, User Stories, Release Note, and Documentation sections.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and specifically describes the main change: adding SDK methods for agent sub-organization authentication, which aligns with the primary objective of the pull request.
Docstring Coverage ✅ Passed Docstring coverage is 91.67% which is sufficient. The required threshold is 80.00%.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@packages/asgardeo-ai/src/asgardeo_ai/agent_auth_manager.py`:
- Around line 263-273: The code raises ValueError for unsupported org discovery
types; replace those with the SDK's ValidationError so input validation is
consistent—specifically, change the raise ValueError(...) in the auth parameter
construction logic (the block handling org_discovery_type that sets
auth_params["orgId"/"orgHandle"/"org"/"login_hint"]) to raise ValidationError
with the same message, and make the identical change in the second occurrence
around lines 325-335; locate these in AgentAuthManager (the method that builds
auth_params / handles org_discovery_type) and substitute ValidationError for
ValueError in both places.
- Around line 540-544: The current except block catches a broad Exception and
re-raises TokenError losing the original traceback; replace the generic catch
with either specific exception types you expect (instead of bare Exception) or,
if you must catch Exception, log the full traceback (logger.error(...,
exc_info=True)) and re-raise a chained exception using "raise
TokenError(f'Organization switch failed: {e}') from e" so the original cause is
preserved; update the block around TokenError/ValidationError handling in the
same method where logger.error is called.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 8ff1fc2c-a813-43f8-b7ae-5b4e79cdbca8

📥 Commits

Reviewing files that changed from the base of the PR and between 259814c and 9e63b92.

📒 Files selected for processing (2)
  • packages/asgardeo-ai/src/asgardeo_ai/agent_auth_manager.py
  • packages/asgardeo/src/asgardeo/auth/client.py

Comment thread packages/asgardeo-ai/src/asgardeo_ai/agent_auth_manager.py Outdated
Comment thread packages/asgardeo-ai/src/asgardeo_ai/agent_auth_manager.py Outdated
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: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@packages/asgardeo-ai/src/asgardeo_ai/agent_auth_manager.py`:
- Line 320: The call auth_params.update(kwargs) allows callers to overwrite
SDK-managed auth fields; change this to merge only non-reserved keys by
filtering kwargs against the SDK-owned reserved set (which must include org
selector keys, fidp, requested_actor and PKCE fields), i.e., build a new dict of
kwargs items where key not in reserved and then update auth_params with that;
also apply the same guarded merge in the PKCE branch (the code path that sets
code_challenge/code_challenge_method) and add "code_challenge" and
"code_challenge_method" to the reserved set so callers cannot override those
values.
- Around line 262-273: The _build_org_discovery_params function must reject
blank or whitespace-only discovery_value before constructing params; add
validation at the start of _build_org_discovery_params (accepting
org_discovery_type: OrgDiscoveryType, discovery_value: str) that strips
discovery_value and raises ValidationError for empty strings, so callers like
the org ID/handle/org/emailDomain branches never produce keys with empty values;
keep the existing match cases and error handling for unsupported
org_discovery_type.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 17ea2f76-44ef-4358-b7a6-549cb71921f6

📥 Commits

Reviewing files that changed from the base of the PR and between 9e63b92 and f44640e.

📒 Files selected for processing (2)
  • packages/asgardeo-ai/src/asgardeo_ai/agent_auth_manager.py
  • packages/asgardeo/src/asgardeo/auth/client.py
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/asgardeo/src/asgardeo/auth/client.py

Comment thread packages/asgardeo-ai/src/asgardeo_ai/agent_auth_manager.py Outdated
Comment thread packages/asgardeo-ai/src/asgardeo_ai/agent_auth_manager.py
Comment thread packages/asgardeo-ai/src/asgardeo_ai/agent_auth_manager.py Outdated
@HasiniSama HasiniSama force-pushed the agent-organization-auth branch from f69165b to f123650 Compare May 15, 2026 12:46
@HasiniSama HasiniSama merged commit 409ec5f into asgardeo:main May 15, 2026
2 checks passed
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.

3 participants