Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions src/client/auth.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -366,6 +366,31 @@ describe("OAuth Authorization", () => {
expect(authorizationUrl.searchParams.has("scope")).toBe(false);
});

it("includes state parameter when provided", async () => {
const { authorizationUrl } = await startAuthorization(
"https://auth.example.com",
{
clientInformation: validClientInfo,
redirectUrl: "http://localhost:3000/callback",
state: "foobar",
}
);

expect(authorizationUrl.searchParams.get("state")).toBe("foobar");
});

it("excludes state parameter when not provided", async () => {
const { authorizationUrl } = await startAuthorization(
"https://auth.example.com",
{
clientInformation: validClientInfo,
redirectUrl: "http://localhost:3000/callback",
}
);

expect(authorizationUrl.searchParams.has("state")).toBe(false);
});

it("uses metadata authorization_endpoint when provided", async () => {
const { authorizationUrl } = await startAuthorization(
"https://auth.example.com",
Expand Down
14 changes: 14 additions & 0 deletions src/client/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,11 @@ export interface OAuthClientProvider {
*/
get clientMetadata(): OAuthClientMetadata;

/**
* Returns a OAuth2 state parameter.
*/
state?(): string | Promise<string>;

/**
* Loads information about this OAuth client, as registered already with the
* server, or returns `undefined` if the client is not registered with the
Expand Down Expand Up @@ -162,10 +167,13 @@ export async function auth(
}
}

const state = provider.state ? await provider.state() : undefined;

// Start new authorization flow
const { authorizationUrl, codeVerifier } = await startAuthorization(authorizationServerUrl, {
metadata,
clientInformation,
state,
redirectUrl: provider.redirectUrl,
scope: scope || provider.clientMetadata.scope,
});
Expand Down Expand Up @@ -301,11 +309,13 @@ export async function startAuthorization(
clientInformation,
redirectUrl,
scope,
state,
}: {
metadata?: OAuthMetadata;
clientInformation: OAuthClientInformation;
redirectUrl: string | URL;
scope?: string;
state?: string;
},
): Promise<{ authorizationUrl: URL; codeVerifier: string }> {
const responseType = "code";
Expand Down Expand Up @@ -347,6 +357,10 @@ export async function startAuthorization(
);
authorizationUrl.searchParams.set("redirect_uri", String(redirectUrl));

if (state) {
authorizationUrl.searchParams.set("state", state);
}

if (scope) {
authorizationUrl.searchParams.set("scope", scope);
}
Expand Down