google-auth-library
Version:
Google APIs Authentication Client Library for Node.js
369 lines (368 loc) • 16.3 kB
TypeScript
/// <reference types="node" />
/**
* Copyright 2012 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { AxiosError, AxiosPromise, AxiosRequestConfig, AxiosResponse } from 'axios';
import * as http from 'http';
import { BodyResponseCallback } from './../transporters';
import { AuthClient } from './authclient';
import { Credentials } from './credentials';
import { LoginTicket } from './loginticket';
export declare enum CodeChallengeMethod {
Plain = "plain",
S256 = "S256",
}
export interface GetTokenOptions {
code: string;
codeVerifier?: string;
}
export interface GenerateAuthUrlOpts {
/**
* Recommended. Indicates whether your application can refresh access tokens
* when the user is not present at the browser. Valid parameter values are
* 'online', which is the default value, and 'offline'. Set the value to
* 'offline' if your application needs to refresh access tokens when the user
* is not present at the browser. This value instructs the Google
* authorization server to return a refresh token and an access token the
* first time that your application exchanges an authorization code for
* tokens.
*/
access_type?: string;
/**
* The 'response_type' will always be set to 'CODE'.
*/
response_type?: string;
/**
* The client ID for your application. The value passed into the constructor
* will be used if not provided. You can find this value in the API Console.
*/
client_id?: string;
/**
* Determines where the API server redirects the user after the user
* completes the authorization flow. The value must exactly match one of the
* 'redirect_uri' values listed for your project in the API Console. Note that
* the http or https scheme, case, and trailing slash ('/') must all match.
* The value passed into the constructor will be used if not provided.
*/
redirect_uri?: string;
/**
* Required. A space-delimited list of scopes that identify the resources that
* your application could access on the user's behalf. These values inform the
* consent screen that Google displays to the user. Scopes enable your
* application to only request access to the resources that it needs while
* also enabling users to control the amount of access that they grant to your
* application. Thus, there is an inverse relationship between the number of
* scopes requested and the likelihood of obtaining user consent. The
* OAuth 2.0 API Scopes document provides a full list of scopes that you might
* use to access Google APIs. We recommend that your application request
* access to authorization scopes in context whenever possible. By requesting
* access to user data in context, via incremental authorization, you help
* users to more easily understand why your application needs the access it is
* requesting.
*/
scope?: string[] | string;
/**
* Recommended. Specifies any string value that your application uses to
* maintain state between your authorization request and the authorization
* server's response. The server returns the exact value that you send as a
* name=value pair in the hash (#) fragment of the 'redirect_uri' after the
* user consents to or denies your application's access request. You can use
* this parameter for several purposes, such as directing the user to the
* correct resource in your application, sending nonces, and mitigating
* cross-site request forgery. Since your redirect_uri can be guessed, using a
* state value can increase your assurance that an incoming connection is the
* result of an authentication request. If you generate a random string or
* encode the hash of a cookie or another value that captures the client's
* state, you can validate the response to additionally ensure that the
* request and response originated in the same browser, providing protection
* against attacks such as cross-site request forgery. See the OpenID Connect
* documentation for an example of how to create and confirm a state token.
*/
state?: string;
/**
* Optional. Enables applications to use incremental authorization to request
* access to additional scopes in context. If you set this parameter's value
* to true and the authorization request is granted, then the new access token
* will also cover any scopes to which the user previously granted the
* application access. See the incremental authorization section for examples.
*/
include_granted_scopes?: boolean;
/**
* Optional. If your application knows which user is trying to authenticate,
* it can use this parameter to provide a hint to the Google Authentication
* Server. The server uses the hint to simplify the login flow either by
* prefilling the email field in the sign-in form or by selecting the
* appropriate multi-login session. Set the parameter value to an email
* address or sub identifier, which is equivalent to the user's Google ID.
*/
login_hint?: string;
/**
* Optional. A space-delimited, case-sensitive list of prompts to present the
* user. If you don't specify this parameter, the user will be prompted only
* the first time your app requests access. Possible values are:
*
* 'none' - Donot display any authentication or consent screens. Must not be
* specified with other values.
* 'consent' - Prompt the user for consent.
* 'select_account' - Prompt the user to select an account.
*/
prompt?: string;
/**
* Recommended. Specifies what method was used to encode a 'code_verifier'
* that will be used during authorization code exchange. This parameter must
* be used with the 'code_challenge' parameter. The value of the
* 'code_challenge_method' defaults to "plain" if not present in the request
* that includes a 'code_challenge'. The only supported values for this
* parameter are "S256" or "plain".
*/
code_challenge_method?: CodeChallengeMethod;
/**
* Recommended. Specifies an encoded 'code_verifier' that will be used as a
* server-side challenge during authorization code exchange. This parameter
* must be used with the 'code_challenge' parameter described above.
*/
code_challenge?: string;
}
export interface AuthClientOpts {
authBaseUrl?: string;
tokenUrl?: string;
}
export interface GetTokenCallback {
(err: AxiosError | null, token?: Credentials | null, res?: AxiosResponse | null): void;
}
export interface GetTokenResponse {
tokens: Credentials;
res: AxiosResponse | null;
}
export interface GetAccessTokenCallback {
(err: AxiosError | null, token?: string | null, res?: AxiosResponse | null): void;
}
export interface GetAccessTokenResponse {
token?: string | null;
res?: AxiosResponse | null;
}
export interface RefreshAccessTokenCallback {
(err: AxiosError | null, credentials?: Credentials | null, res?: AxiosResponse | null): void;
}
export interface RefreshAccessTokenResponse {
credentials: Credentials;
res: AxiosResponse | null;
}
export interface RequestMetadataResponse {
headers: http.IncomingHttpHeaders;
res?: AxiosResponse<void> | null;
}
export interface RequestMetadataCallback {
(err: AxiosError | null, headers?: http.IncomingHttpHeaders, res?: AxiosResponse<void> | null): void;
}
export interface GetFederatedSignonCertsCallback {
(err: AxiosError | null, certs?: any, response?: AxiosResponse<void> | null): void;
}
export interface FederatedSignonCertsResponse {
certs: any;
res?: AxiosResponse<void> | null;
}
export interface RevokeCredentialsResult {
success: boolean;
}
export interface VerifyIdTokenOptions {
idToken: string;
audience: string | string[];
maxExpiry?: number;
}
export interface OAuth2ClientOptions {
clientId?: string;
clientSecret?: string;
redirectUri?: string;
authBaseUrl?: string;
tokenUrl?: string;
}
export declare class OAuth2Client extends AuthClient {
private redirectUri?;
private certificateCache;
private certificateExpiry;
protected authBaseUrl?: string;
protected tokenUrl?: string;
_clientId?: string;
_clientSecret?: string;
apiKey: string;
projectId?: string;
/**
* Handles OAuth2 flow for Google APIs.
*
* @param {string=} clientId The authentication client ID.
* @param {string=} clientSecret The authentication client secret.
* @param {string=} redirectUri The URI to redirect to after completing the auth request.
* @param {Object=} opts optional options for overriding the given parameters.
* @constructor
*/
constructor(options: OAuth2ClientOptions);
constructor(clientId?: string, clientSecret?: string, redirectUri?: string, opts?: AuthClientOpts);
/**
* The base URL for auth endpoints.
*/
private static readonly GOOGLE_OAUTH2_AUTH_BASE_URL_;
/**
* The base endpoint for token retrieval.
*/
private static readonly GOOGLE_OAUTH2_TOKEN_URL_;
/**
* The base endpoint to revoke tokens.
*/
private static readonly GOOGLE_OAUTH2_REVOKE_URL_;
/**
* Google Sign on certificates.
*/
private static readonly GOOGLE_OAUTH2_FEDERATED_SIGNON_CERTS_URL_;
/**
* Clock skew - five minutes in seconds
*/
private static readonly CLOCK_SKEW_SECS_;
/**
* Max Token Lifetime is one day in seconds
*/
private static readonly MAX_TOKEN_LIFETIME_SECS_;
/**
* The allowed oauth token issuers.
*/
private static readonly ISSUERS_;
/**
* Generates URL for consent page landing.
* @param {object=} opts Options.
* @return {string} URL to consent page.
*/
generateAuthUrl(opts?: GenerateAuthUrlOpts): string;
/**
* Convenience method to automatically generate a code_verifier, and it's
* resulting SHA256. If used, this must be paired with a S256
* code_challenge_method.
*/
generateCodeVerifier(): {
codeVerifier: string;
codeChallenge: string;
};
/**
* Gets the access token for the given code.
* @param {string} code The authorization code.
* @param {function=} callback Optional callback fn.
*/
getToken(code: string): Promise<GetTokenResponse>;
getToken(options: GetTokenOptions): Promise<GetTokenResponse>;
getToken(code: string, callback: GetTokenCallback): void;
getToken(options: GetTokenOptions, callback: GetTokenCallback): void;
private getTokenAsync(options);
/**
* Refreshes the access token.
* @param {string} refresh_token Existing refresh token.
* @param {function=} callback Optional callback.
* @private
*/
protected refreshToken(refreshToken?: string | null): Promise<GetTokenResponse>;
/**
* Retrieves the access token using refresh token
*
* @deprecated use getRequestMetadata instead.
* @param {function} callback callback
*/
refreshAccessToken(): Promise<RefreshAccessTokenResponse>;
refreshAccessToken(callback: RefreshAccessTokenCallback): void;
private refreshAccessTokenAsync();
/**
* Get a non-expired access token, after refreshing if necessary
*
* @param {function} callback Callback to call with the access token
*/
getAccessToken(): Promise<GetAccessTokenResponse>;
getAccessToken(callback: GetAccessTokenCallback): void;
private getAccessTokenAsync();
/**
* getRequestMetadata obtains auth metadata to be used by requests.
*
* getRequestMetadata is the main authentication interface. It takes an
* optional uri which when present is the endpoint being accessed, and a
* callback func(err, metadata_obj, response) where metadata_obj contains
* authorization metadata fields and response is an optional response object.
*
* In OAuth2Client, metadata_obj has the form.
*
* {Authorization: 'Bearer <access_token_value>'}
*
* @param {string} optUri the Uri being authorized
* @param {function} metadataCb the func described above
*/
getRequestMetadata(url?: string | null): Promise<RequestMetadataResponse>;
getRequestMetadata(url: string | null, callback: RequestMetadataCallback): void;
protected getRequestMetadataAsync(url?: string | null): Promise<RequestMetadataResponse>;
/**
* Revokes the access given to token.
* @param {string} token The existing token to be revoked.
* @param {function=} callback Optional callback fn.
*/
revokeToken(token: string): AxiosPromise<RevokeCredentialsResult>;
revokeToken(token: string, callback: BodyResponseCallback<RevokeCredentialsResult>): void;
/**
* Revokes access token and clears the credentials object
* @param {Function=} callback callback
*/
revokeCredentials(): AxiosPromise<RevokeCredentialsResult>;
revokeCredentials(callback: BodyResponseCallback<RevokeCredentialsResult>): void;
private revokeCredentialsAsync();
/**
* Provides a request implementation with OAuth 2.0 flow.
* If credentials have a refresh_token, in cases of HTTP
* 401 and 403 responses, it automatically asks for a new
* access token and replays the unsuccessful request.
* @param {object} opts Request options.
* @param {function} callback callback.
* @return {Request} Request object
*/
request<T>(opts: AxiosRequestConfig): AxiosPromise<T>;
request<T>(opts: AxiosRequestConfig, callback: BodyResponseCallback<T>): void;
protected requestAsync<T>(opts: AxiosRequestConfig, retry?: boolean): Promise<AxiosResponse<T>>;
/**
* Verify id token is token by checking the certs and audience
* @param {VerifyIdTokenOptions} Object that contains all options.
* @param {function=} callback Callback supplying GoogleLogin if successful
*/
verifyIdToken(options: VerifyIdTokenOptions): Promise<LoginTicket | null>;
verifyIdToken(options: VerifyIdTokenOptions, callback: (err: Error | null, login?: LoginTicket | null) => void): void;
private verifyIdTokenAsync(options);
/**
* Gets federated sign-on certificates to use for verifying identity tokens.
* Returns certs as array structure, where keys are key ids, and values
* are PEM encoded certificates.
* @param {function=} callback Callback supplying the certificates
*/
getFederatedSignonCerts(): Promise<FederatedSignonCertsResponse>;
getFederatedSignonCerts(callback: GetFederatedSignonCertsCallback): void;
getFederatedSignonCertsAsync(): Promise<FederatedSignonCertsResponse>;
/**
* Verify the id token is signed with the correct certificate
* and is from the correct audience.
* @param {string} jwt The jwt to verify (The ID Token in this case).
* @param {array} certs The array of certs to test the jwt against.
* @param {(string|Array.<string>)} requiredAudience The audience to test the jwt against.
* @param {array} issuers The allowed issuers of the jwt (Optional).
* @param {string} maxExpiry The max expiry the certificate can be (Optional).
* @return {LoginTicket} Returns a LoginTicket on verification.
*/
verifySignedJwtWithCerts(jwt: string, certs: {}, requiredAudience: string | string[], issuers?: string[], maxExpiry?: number): LoginTicket;
/**
* This is a utils method to decode a base64 string
* @param {string} b64String The string to base64 decode
* @return {string} The decoded string
*/
decodeBase64(b64String: string): string;
}