forked from sst/openauth
-
Notifications
You must be signed in to change notification settings - Fork 0
add grant-type assertions for jwt-bearer #6
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
nullfunc
wants to merge
26
commits into
defang
Choose a base branch
from
add-jwt-assertion-grant-type
base: defang
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+644
−37
Open
Changes from all commits
Commits
Show all changes
26 commits
Select commit
Hold shift + click to select a range
11b1227
add gitlab and github actions oidc
nullfunc 57af85e
add grant-type for jwt assertion
nullfunc af53876
type enforcement updates
nullfunc c58ec05
error update
nullfunc e132d52
add gitlab and github actions oidc
nullfunc 4329d2b
add grant-type for jwt assertion
nullfunc 3e51d8d
type enforcement updates
nullfunc b8d187d
error update
nullfunc f196406
update gitlabs with oidc provider
nullfunc a210b19
Merge remote-tracking branch 'refs/remotes/origin/add-jwt-assertion-g…
nullfunc ec7834c
assert jwt-bearer
nullfunc 4fe5d3c
update tests
nullfunc 01fbc60
add trusted issuer check for jwt assertions
nullfunc d8b30bd
oidc provider and jwt assertion grant-types
nullfunc 966e6f5
remove trailing '/' from github issuer
nullfunc 15576b5
jwt grant updates to pass provider name
nullfunc a09fba3
fix missing param in test data
nullfunc 5e2f4f5
revert bun.lockb to original
nullfunc 977dd9d
auto: format code
github-actions[bot] 27477fe
update hono and exports/imports
nullfunc c6b227d
update to dependencies
nullfunc 3f6812e
review updates
nullfunc 44f971b
auto: format code
github-actions[bot] 7fe77c5
ignore audience if not defined. for github CI JWT the aud varies by r…
nullfunc 6cf959d
auto: format code
github-actions[bot] dcdb969
handle decode failure for better error
nullfunc File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,149 @@ | ||
# JWT Bearer Token Validation | ||
|
||
## Overview | ||
|
||
When using the `urn:ietf:params:oauth:grant-type:jwt-bearer` grant type, OpenAuth automatically validates JWT signatures using JWKS and calls your success callback to handle the validated JWT claims. | ||
|
||
## Validation Process | ||
|
||
1. **JWT decoding**: OpenAuth decodes the JWT assertion to extract claims | ||
2. **OIDC provider matching**: Finds a matching OIDC provider based on the JWT issuer | ||
3. **JWT signature verification**: Automatically fetches the issuer's JWKS and verifies the JWT signature using the provider's `verifyIdToken()` method | ||
4. **Success callback**: Your success callback receives the validated JWT claims | ||
5. **Token generation**: Return `ctx.subject()` to generate final access/refresh tokens | ||
|
||
## Configuration | ||
|
||
Configure `oidcProviders` for each JWT issuer you want to accept: | ||
|
||
```typescript | ||
import { issuer } from "@openauthjs/openauth" | ||
import { OidcProvider } from "@openauthjs/openauth/provider/oidc" | ||
import { GitHubProvider } from "@openauthjs/openauth/provider/github" | ||
|
||
const app = issuer({ | ||
// OIDC providers for JWT bearer validation | ||
oidcProviders: { | ||
gitlab: OidcProvider({ | ||
clientID: "https://gitlab.com", // Must match JWT 'aud' claim | ||
issuer: "https://gitlab.com", // Must match JWT 'iss' claim | ||
provider: "gitlab" // Provider type identifier | ||
}), | ||
github: OidcProvider({ | ||
clientID: "github-actions", | ||
issuer: "https://token.actions.githubusercontent.com", | ||
provider: "github" | ||
}) | ||
}, | ||
|
||
// Regular OAuth providers for interactive login | ||
providers: { | ||
github: GitHubProvider({ | ||
clientId: process.env.GITHUB_CLIENT_ID!, | ||
clientSecret: process.env.GITHUB_CLIENT_SECRET! | ||
}) | ||
}, | ||
|
||
subjects: { /* your subjects */ }, | ||
storage: /* your storage */, | ||
|
||
success: async (ctx, value) => { | ||
// Handle regular OAuth providers | ||
if (value.provider === "github") { | ||
const providerData = await getGithubData(value.tokenset.access) | ||
const { user } = await upsertUser(providerData) | ||
return ctx.subject("user", { | ||
id: user.id, | ||
tenant: user.defaultTenant, | ||
hasura: { | ||
"x-hasura-allowed-roles": ["user"], | ||
"x-hasura-default-role": "user", | ||
"x-hasura-user-id": user.id, | ||
}, | ||
externalTenants: user.tenants.map(t => t.id), | ||
githubOrgs: providerData.orgs?.map(org => org.name) | ||
}, { | ||
subject: user.id | ||
}) | ||
} | ||
|
||
// Handle JWT bearer tokens | ||
if (!value.tokenset) { | ||
console.log("JWT Bearer token from:", value.issuer) | ||
console.log("JWT claims:", value.claims) | ||
|
||
// The JWT signature is already validated by OpenAuth using JWKS | ||
// Map different issuers to appropriate subjects | ||
|
||
if (value.issuer === "https://gitlab.com") { | ||
// JWT from GitLab CI/CD pipeline | ||
return ctx.subject("service", { | ||
id: value.subject, | ||
issuer: value.issuer, | ||
}) | ||
} | ||
|
||
if (value.issuer === "https://token.actions.githubusercontent.com") { | ||
// JWT from GitHub CI Action | ||
return ctx.subject("service", { | ||
id: value.subject, | ||
issuer: value.issuer, | ||
}) | ||
} | ||
|
||
// Default: map to API user if no specific handling | ||
return ctx.subject("api_user", { | ||
id: value.subject, | ||
issuer: value.issuer, | ||
audience: value.audience | ||
}) | ||
} | ||
|
||
throw new Error(`Unsupported provider: ${value.provider}`) | ||
} | ||
}) | ||
``` | ||
|
||
## Token Exchange Flow | ||
|
||
1. **Client sends JWT assertion**: A client makes a POST request to `/token` with: | ||
|
||
```http | ||
grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer&assertion=<jwt_token> | ||
``` | ||
|
||
2. **OIDC provider matching**: OpenAuth finds the matching OIDC provider by comparing the JWT `iss` claim with configured provider issuers | ||
|
||
3. **Signature verification**: OpenAuth uses the matched OIDC provider to verify the JWT signature (automatically fetches JWKS) | ||
|
||
4. **Success callback**: OpenAuth calls your success callback with: | ||
|
||
```typescript | ||
{ | ||
provider: string, // OIDC provider type (from config.type) | ||
claims: JWTPayload, // Full JWT claims object | ||
issuer: string, // The JWT issuer (iss claim) | ||
subject: string, // The JWT subject (sub claim) | ||
audience: string // The JWT audience (aud claim) | ||
} | ||
``` | ||
|
||
5. **Token generation**: Return `ctx.subject()` to generate final access/refresh tokens | ||
|
||
## Security Considerations | ||
|
||
**OIDC provider configuration acts as allowlist:** | ||
|
||
- **Explicit trust**: Only JWTs from configured `oidcProviders` are accepted | ||
- **Automatic validation**: JWT signature verification is handled automatically | ||
- **No additional issuer validation needed**: The OIDC provider matching already ensures trusted issuers | ||
- **JWKS fetching**: OpenAuth automatically fetches and caches JWKS for signature verification | ||
|
||
**Best practices:** | ||
|
||
- **Configure specific issuers**: Only add OIDC providers for issuers you trust | ||
- **Match audience claims**: Ensure JWT `aud` claim matches your `clientID` configuration | ||
- **Validate additional claims**: Check roles, scopes, or custom claims in the success callback | ||
- **Use specific types**: Create different subject types for different use cases (users vs services) | ||
- **Log JWT usage**: Monitor bearer token usage for security auditing | ||
- **Handle claim validation**: Throw clear errors for missing or invalid claims |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
InvalidJWTError
is a bit too specific. Lots of other reasons why this could fail.