Skip to content
Draft
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
53 changes: 35 additions & 18 deletions src/auth/backchannel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@

import { JSONApiResponse } from "../lib/models.js";
import { BaseAuthAPI } from "./base-auth-api.js";
import { AuthorizationDetails } from "./oauth.js";

/**
* The response from the authorize endpoint.
Expand Down Expand Up @@ -73,7 +74,7 @@ const getLoginHint = (userId: string, domain: string): string => {
/**
* Options for the authorize request.
*/
export type AuthorizeOptions = {
export interface AuthorizeOptions<TAuthorizationDetails extends AuthorizationDetails = AuthorizationDetails> {
/**
* A human-readable string intended to be displayed on both the device calling /bc-authorize and the user’s authentication device.
*/
Expand Down Expand Up @@ -107,23 +108,21 @@ export type AuthorizeOptions = {
* Optional authorization details to use Rich Authorization Requests (RAR).
* @see https://auth0.com/docs/get-started/apis/configure-rich-authorization-requests
*/
authorization_details?: string;
} & Record<string, string>;
authorization_details?: string | TAuthorizationDetails[];

[key: string]: unknown;
}

type AuthorizeRequest = Omit<AuthorizeOptions, "userId"> &
AuthorizeCredentialsPartial & {
login_hint: string;
};

export interface AuthorizationDetails {
readonly type: string;
readonly [parameter: string]: unknown;
}
authorization_details?: string;
} & Record<string, string>;

/**
* The response from the token endpoint.
*/
export type TokenResponse = {
export interface TokenResponse<TAuthorizationDetails extends AuthorizationDetails = AuthorizationDetails> {
/**
* The access token.
*/
Expand Down Expand Up @@ -152,8 +151,8 @@ export type TokenResponse = {
* Optional authorization details when using Rich Authorization Requests (RAR).
* @see https://auth0.com/docs/get-started/apis/configure-rich-authorization-requests
*/
authorization_details?: AuthorizationDetails[];
};
authorization_details?: TAuthorizationDetails[];
}

/**
* Options for the token request.
Expand All @@ -174,8 +173,12 @@ type TokenRequestBody = AuthorizeCredentialsPartial & {
* Interface for the backchannel authentication.
*/
export interface IBackchannel {
authorize: (options: AuthorizeOptions) => Promise<AuthorizeResponse>;
backchannelGrant: (options: TokenOptions) => Promise<TokenResponse>;
authorize: <TAuthorizationDetails extends AuthorizationDetails = AuthorizationDetails>(
options: AuthorizeOptions<TAuthorizationDetails>,
) => Promise<AuthorizeResponse>;
backchannelGrant: <TAuthorizationDetails extends AuthorizationDetails = AuthorizationDetails>(
options: TokenOptions,
) => Promise<TokenResponse<TAuthorizationDetails>>;
}

const CIBA_GRANT_TYPE = "urn:openid:params:grant-type:ciba";
Expand All @@ -194,9 +197,21 @@ export class Backchannel extends BaseAuthAPI implements IBackchannel {
*
* @throws {Error} - If the request fails.
*/
async authorize({ userId, ...options }: AuthorizeOptions): Promise<AuthorizeResponse> {
async authorize<TAuthorizationDetails extends AuthorizationDetails = AuthorizationDetails>({
userId,
...options
}: AuthorizeOptions<TAuthorizationDetails>): Promise<AuthorizeResponse> {
const { authorization_details, ...authorizeOptions } = options;

if (authorization_details) {
authorizeOptions.authorization_details =
typeof authorization_details === "string"
? authorization_details
: JSON.stringify(authorization_details);
}

const body: AuthorizeRequest = {
...options,
...authorizeOptions,
login_hint: getLoginHint(userId, this.domain),
client_id: this.clientId,
};
Expand Down Expand Up @@ -255,7 +270,9 @@ export class Backchannel extends BaseAuthAPI implements IBackchannel {
* }
* ```
*/
async backchannelGrant({ auth_req_id }: TokenOptions): Promise<TokenResponse> {
async backchannelGrant<TAuthorizationDetails extends AuthorizationDetails = AuthorizationDetails>({
auth_req_id,
}: TokenOptions): Promise<TokenResponse<TAuthorizationDetails>> {
const body: TokenRequestBody = {
client_id: this.clientId,
auth_req_id,
Expand All @@ -274,7 +291,7 @@ export class Backchannel extends BaseAuthAPI implements IBackchannel {
{},
);

const r: JSONApiResponse<TokenResponse> = await JSONApiResponse.fromResponse(response);
const r: JSONApiResponse<TokenResponse<TAuthorizationDetails>> = await JSONApiResponse.fromResponse(response);
return r.data;
}
}
8 changes: 4 additions & 4 deletions src/auth/base-auth-api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
import { BaseAPI, ClientOptions, InitOverrideFunction, JSONApiResponse, RequestOpts } from "../lib/runtime.js";
import { AddClientAuthenticationPayload, addClientAuthentication } from "./client-authentication.js";
import { IDTokenValidator } from "./id-token-validator.js";
import { GrantOptions, TokenSet } from "./oauth.js";
import { AuthorizationDetails, GrantOptions, TokenSet } from "./oauth.js";
import { Auth0ClientTelemetry } from "../lib/middleware/auth0-client-telemetry.js";

export interface AuthenticationClientOptions extends ClientOptions {
Expand Down Expand Up @@ -34,7 +34,7 @@
}
}

function parseErrorBody(body: any): AuthApiErrorResponse {

Check warning on line 37 in src/auth/base-auth-api.ts

View workflow job for this annotation

GitHub Actions / Lint & Format

Unexpected any. Specify a different type

Check warning on line 37 in src/auth/base-auth-api.ts

View workflow job for this annotation

GitHub Actions / Type Check

Unexpected any. Specify a different type
const rawData = JSON.parse(body);
let data: AuthApiErrorResponse;

Expand Down Expand Up @@ -114,14 +114,14 @@
* @private
* Perform an OAuth 2.0 grant.
*/
export async function grant(
export async function grant<TAuthorizationDetails extends AuthorizationDetails = AuthorizationDetails>(
grantType: string,
bodyParameters: Record<string, any>,

Check warning on line 119 in src/auth/base-auth-api.ts

View workflow job for this annotation

GitHub Actions / Lint & Format

Unexpected any. Specify a different type

Check warning on line 119 in src/auth/base-auth-api.ts

View workflow job for this annotation

GitHub Actions / Type Check

Unexpected any. Specify a different type
{ idTokenValidateOptions, initOverrides }: GrantOptions = {},
clientId: string,
idTokenValidator: IDTokenValidator,
request: (context: RequestOpts, initOverrides?: RequestInit | InitOverrideFunction) => Promise<Response>,
): Promise<JSONApiResponse<TokenSet>> {
): Promise<JSONApiResponse<TokenSet<TAuthorizationDetails>>> {
const response = await request(
{
path: "/oauth/token",
Expand All @@ -138,7 +138,7 @@
initOverrides,
);

const res: JSONApiResponse<TokenSet> = await JSONApiResponse.fromResponse(response);
const res: JSONApiResponse<TokenSet<TAuthorizationDetails>> = await JSONApiResponse.fromResponse(response);
if (res.data.id_token) {
await idTokenValidator.validate(res.data.id_token, idTokenValidateOptions);
}
Expand Down
58 changes: 39 additions & 19 deletions src/auth/oauth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,12 @@
import { IDTokenValidateOptions, IDTokenValidator } from "./id-token-validator.js";
import { mtlsPrefix } from "../utils.js";

export interface TokenSet {
export interface AuthorizationDetails {
readonly type: string;
readonly [parameter: string]: unknown;
}

export interface TokenSet<TAuthorizationDetails extends AuthorizationDetails = AuthorizationDetails> {
/**
* The access token.
*/
Expand All @@ -24,6 +29,11 @@
* The duration in secs that the access token is valid.
*/
expires_in: number;
/**
* The authorization details when using Rich Authorization Requests (RAR).
* @see https://auth0.com/docs/get-started/apis/configure-rich-authorization-requests
*/
authorization_details?: TAuthorizationDetails[];
}

export interface GrantOptions {
Expand Down Expand Up @@ -70,7 +80,7 @@
/**
* Allow for any custom property to be sent to Auth0
*/
[key: string]: any;

Check warning on line 83 in src/auth/oauth.ts

View workflow job for this annotation

GitHub Actions / Lint & Format

Unexpected any. Specify a different type

Check warning on line 83 in src/auth/oauth.ts

View workflow job for this annotation

GitHub Actions / Type Check

Unexpected any. Specify a different type
}

export interface AuthorizationCodeGrantWithPKCERequest extends AuthorizationCodeGrantRequest {
Expand All @@ -94,7 +104,9 @@
organization?: string;
}

export interface PushedAuthorizationRequest extends ClientCredentials {
export interface PushedAuthorizationRequest<
TAuthorizationDetails extends AuthorizationDetails = AuthorizationDetails,
> extends ClientCredentials {
/**
* URI to redirect to.
*/
Expand Down Expand Up @@ -157,12 +169,12 @@
/**
* A JSON stringified array of objects. It can carry fine-grained authorization data in OAuth messages as part of Rich Authorization Requests (RAR) {@link https://auth0.com/docs/get-started/authentication-and-authorization-flow/authorization-code-flow/authorization-code-flow-with-rar | Reference}
*/
authorization_details?: string;
authorization_details?: string | TAuthorizationDetails[];

/**
* Allow for any custom property to be sent to Auth0
*/
[key: string]: any;

Check warning on line 177 in src/auth/oauth.ts

View workflow job for this annotation

GitHub Actions / Lint & Format

Unexpected any. Specify a different type

Check warning on line 177 in src/auth/oauth.ts

View workflow job for this annotation

GitHub Actions / Type Check

Unexpected any. Specify a different type
}

export interface PushedAuthorizationResponse {
Expand Down Expand Up @@ -229,7 +241,7 @@
/**
* Allow for any custom property to be sent to Auth0
*/
[key: string]: any;

Check warning on line 244 in src/auth/oauth.ts

View workflow job for this annotation

GitHub Actions / Lint & Format

Unexpected any. Specify a different type

Check warning on line 244 in src/auth/oauth.ts

View workflow job for this annotation

GitHub Actions / Type Check

Unexpected any. Specify a different type
}

export interface RevokeRefreshTokenRequest extends ClientCredentials {
Expand Down Expand Up @@ -359,13 +371,13 @@
* await auth0.oauth.authorizationCodeGrant({ code: 'mycode' });
* ```
*/
async authorizationCodeGrant(
async authorizationCodeGrant<TAuthorizationDetails extends AuthorizationDetails = AuthorizationDetails>(
bodyParameters: AuthorizationCodeGrantRequest,
options: AuthorizationCodeGrantOptions = {},
): Promise<JSONApiResponse<TokenSet>> {
): Promise<JSONApiResponse<TokenSet<TAuthorizationDetails>>> {
validateRequiredRequestParams(bodyParameters, ["code"]);

return grant(
return grant<TAuthorizationDetails>(
"authorization_code",
await this.addClientAuthentication(bodyParameters),
options,
Expand Down Expand Up @@ -396,13 +408,13 @@
* });
* ```
*/
async authorizationCodeGrantWithPKCE(
async authorizationCodeGrantWithPKCE<TAuthorizationDetails extends AuthorizationDetails = AuthorizationDetails>(
bodyParameters: AuthorizationCodeGrantWithPKCERequest,
options: AuthorizationCodeGrantOptions = {},
): Promise<JSONApiResponse<TokenSet>> {
): Promise<JSONApiResponse<TokenSet<TAuthorizationDetails>>> {
validateRequiredRequestParams(bodyParameters, ["code", "code_verifier"]);

return grant(
return grant<TAuthorizationDetails>(
"authorization_code",
await this.addClientAuthentication(bodyParameters),
options,
Expand Down Expand Up @@ -431,13 +443,13 @@
* await auth0.oauth.clientCredentialsGrant({ audience: 'myaudience' });
* ```
*/
async clientCredentialsGrant(
async clientCredentialsGrant<TAuthorizationDetails extends AuthorizationDetails = AuthorizationDetails>(
bodyParameters: ClientCredentialsGrantRequest,
options: { initOverrides?: InitOverride } = {},
): Promise<JSONApiResponse<TokenSet>> {
): Promise<JSONApiResponse<TokenSet<TAuthorizationDetails>>> {
validateRequiredRequestParams(bodyParameters, ["audience"]);

return grant(
return grant<TAuthorizationDetails>(
"client_credentials",
await this.addClientAuthentication(bodyParameters),
options,
Expand Down Expand Up @@ -469,8 +481,16 @@
options: { initOverrides?: InitOverride } = {},
): Promise<JSONApiResponse<PushedAuthorizationResponse>> {
validateRequiredRequestParams(bodyParameters, ["client_id", "response_type", "redirect_uri"]);
const { authorization_details, ...params } = bodyParameters;

if (authorization_details) {
params.authorization_details =
typeof authorization_details === "string"
? authorization_details
: JSON.stringify(authorization_details);
}

const bodyParametersWithClientAuthentication = await this.addClientAuthentication(bodyParameters);
const bodyParametersWithClientAuthentication = await this.addClientAuthentication(params);

const response = await this.request(
{
Expand Down Expand Up @@ -518,13 +538,13 @@
* See https://auth0.com/docs/get-started/authentication-and-authorization-flow/avoid-common-issues-with-resource-owner-password-flow-and-attack-protection
*
*/
async passwordGrant(
async passwordGrant<TAuthorizationDetails extends AuthorizationDetails = AuthorizationDetails>(
bodyParameters: PasswordGrantRequest,
options: GrantOptions = {},
): Promise<JSONApiResponse<TokenSet>> {
): Promise<JSONApiResponse<TokenSet<TAuthorizationDetails>>> {
validateRequiredRequestParams(bodyParameters, ["username", "password"]);

return grant(
return grant<TAuthorizationDetails>(
bodyParameters.realm ? "http://auth0.com/oauth/grant-type/password-realm" : "password",
await this.addClientAuthentication(bodyParameters),
options,
Expand All @@ -550,13 +570,13 @@
* await auth0.oauth.refreshTokenGrant({ refresh_token: 'myrefreshtoken' })
* ```
*/
async refreshTokenGrant(
async refreshTokenGrant<TAuthorizationDetails extends AuthorizationDetails = AuthorizationDetails>(
bodyParameters: RefreshTokenGrantRequest,
options: GrantOptions = {},
): Promise<JSONApiResponse<TokenSet>> {
): Promise<JSONApiResponse<TokenSet<TAuthorizationDetails>>> {
validateRequiredRequestParams(bodyParameters, ["refresh_token"]);

return grant(
return grant<TAuthorizationDetails>(
"refresh_token",
await this.addClientAuthentication(bodyParameters),
options,
Expand Down
27 changes: 25 additions & 2 deletions tests/auth/backchannel.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,7 @@ describe("Backchannel", () => {
expect(receivedRequestExpiry).toBe(999);
});

it("should pass authorization_details to /bc-authorize", async () => {
it("should pass authorization_details to /bc-authorize when provided as string", async () => {
let receivedAuthorizationDetails: { type: string }[] = [];
nock(`https://${opts.domain}`)
.post("/bc-authorize")
Expand All @@ -170,6 +170,29 @@ describe("Backchannel", () => {
expect(receivedAuthorizationDetails[0].type).toBe("test-type");
});

it("should serialize authorization_details to a JSON string when provided as array", async () => {
let rawAuthorizationDetails = "";
nock(`https://${opts.domain}`)
.post("/bc-authorize")
.reply(201, (uri, requestBody, cb) => {
rawAuthorizationDetails = querystring.parse(requestBody as any)["authorization_details"] as string;
cb(null, {
auth_req_id: "test-auth-req-id",
expires_in: 300,
interval: 5,
});
});

await backchannel.authorize({
userId: "auth0|test-user-id",
binding_message: "Test binding message",
scope: "openid",
authorization_details: [{ type: "test-type", actions: ["read"] }],
});

expect(rawAuthorizationDetails).toBe(JSON.stringify([{ type: "test-type", actions: ["read"] }]));
});

it("should pass custom parameters to /bc-authorize", async () => {
let receivedCustomParam = "";
nock(`https://${opts.domain}`)
Expand Down Expand Up @@ -292,7 +315,7 @@ describe("Backchannel", () => {
});

it("should return token response, including authorization_details when available", async () => {
const authorization_details = JSON.stringify([{ type: "test-type" }]);
const authorization_details = [{ type: "test-type" }];
nock(`https://${opts.domain}`).post("/oauth/token").reply(200, {
access_token: "test-access-token",
id_token: "test-id-token",
Expand Down
11 changes: 11 additions & 0 deletions tests/auth/fixtures/oauth.json
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,17 @@
"expires_in": 86400
}
},
{
"scope": "https://test-domain.auth0.com",
"method": "POST",
"path": "/oauth/par",
"body": "client_id=test-client-id&response_type=code&redirect_uri=https%3A%2F%2Fexample-as-string.com&authorization_details=%5B%7B%22type%22%3A%22payment_initiation%22%2C%22actions%22%3A%5B%22write%22%5D%7D%5D&client_secret=test-client-secret",
"status": 200,
"response": {
"request_uri": "https://www.request.uri",
"expires_in": 86400
}
},
{
"scope": "https://test-domain.auth0.com",
"method": "POST",
Expand Down
Loading
Loading