Skip to content

Commit

Permalink
Use an OAuth 2.0 access token for Domain-Wide Delegation
Browse files Browse the repository at this point in the history
  • Loading branch information
sethvargo committed Feb 2, 2024
1 parent 5a50e58 commit 3d25fba
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 10 deletions.
2 changes: 1 addition & 1 deletion dist/main/index.js

Large diffs are not rendered by default.

10 changes: 10 additions & 0 deletions src/client/iamcredentials.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,16 @@ export class IAMCredentialsClient extends Client {
this.#authToken = opts.authToken;
}

// withToken creates a new IAMCredentialsClient that uses the given token for
// authentication. All other parameters are the same.
withToken(token: string): IAMCredentialsClient {
return new IAMCredentialsClient({
logger: this._logger,
universe: this._universe,
authToken: token,
});
}

/**
* generateAccessToken generates a new OAuth 2.0 Access Token for a service
* account.
Expand Down
24 changes: 15 additions & 9 deletions src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -282,10 +282,19 @@ async function main(logger: Logger) {
);
}

// Get the access token. This is required, even for Domain-Wide
// Delegation, because DWD doesn't accept a federated token for
// authentication.
let accessToken = await iamCredentialsClient.generateAccessToken({
serviceAccount,
delegates,
scopes: accessTokenScopes,
lifetime: accessTokenLifetime,
});

// If a subject was provided, use the traditional OAuth 2.0 flow to
// perform Domain-Wide Delegation. Otherwise, use the modern IAM
// Credentials endpoints.
let accessToken;
if (accessTokenSubject) {
if (accessTokenLifetime > 3600) {
logger.info(
Expand All @@ -303,14 +312,11 @@ async function main(logger: Logger) {
);
const signedJWT = await client.signJWT(unsignedJWT);

accessToken = await iamCredentialsClient.generateDomainWideDelegationAccessToken(signedJWT);
} else {
accessToken = await iamCredentialsClient.generateAccessToken({
serviceAccount,
delegates,
scopes: accessTokenScopes,
lifetime: accessTokenLifetime,
});
// Note we use the access token from above, since DWD does not support
// federated tokens.
accessToken = await iamCredentialsClient
.withToken(accessToken)
.generateDomainWideDelegationAccessToken(signedJWT);
}

setSecret(accessToken);
Expand Down

0 comments on commit 3d25fba

Please sign in to comment.