@esri/arcgis-rest-auth
Version:
Authentication helpers for @esri/arcgis-rest-js.
497 lines (496 loc) • 19.2 kB
TypeScript
/// <reference types="node" />
/**
* /generateToken returns a token that cannot be refreshed.
*
* oauth2/token can return a token *and* a refreshToken.
* up until the refreshToken expires, you can use it (and a clientId)
* to fetch fresh credentials without a username and password.
*
* the catch is that this 'authorization_code' flow is only utilized
* by server based OAuth 2 Node.js applications that call /authorize first.
*/
import * as http from "http";
import { IRequestOptions, IAuthenticationManager, ITokenRequestOptions } from "@esri/arcgis-rest-request";
import { IUser } from "@esri/arcgis-rest-types";
import { IAppAccess } from "./validate-app-access";
export declare type AuthenticationProvider = "arcgis" | "facebook" | "google" | "github" | "apple";
/**
* Represents a [credential](https://developers.arcgis.com/javascript/latest/api-reference/esri-identity-Credential.html)
* object used to access a secure ArcGIS resource.
*/
export interface ICredential {
expires: number;
server: string;
ssl: boolean;
token: string;
userId: string;
}
/**
* Options for static OAuth 2.0 helper methods on `UserSession`.
*/
export interface IOAuth2Options {
/**
* Client ID of your application. Can be obtained by registering an application
* on [ArcGIS for Developers](https://developers.arcgis.com/documentation/core-concepts/security-and-authentication/signing-in-arcgis-online-users/#registering-your-application),
* [ArcGIS Online](http://doc.arcgis.com/en/arcgis-online/share-maps/add-items.htm#ESRI_SECTION1_0D1B620254F745AE84F394289F8AF44B) or on your instance of ArcGIS Enterprise.
*/
clientId: string;
/**
* A valid URL to redirect to after a user authorizes your application. Can be set on [ArcGIS for Developers](https://developers.arcgis.com/documentation/core-concepts/security-and-authentication/signing-in-arcgis-online-users/#registering-your-application),
* [ArcGIS Online](http://doc.arcgis.com/en/arcgis-online/share-maps/add-items.htm#ESRI_SECTION1_0D1B620254F745AE84F394289F8AF44B) or on your instance of ArcGIS Enterprise.
*/
redirectUri: string;
/**
* The ArcGIS Online or ArcGIS Enterprise portal you want to use for authentication. Defaults to `https://www.arcgis.com/sharing/rest` for the ArcGIS Online portal.
*/
portal?: string;
/**
* ArcGIS Authentication is used by default. Specifying an alternative will take users directly to the corresponding provider's OAuth page.
*/
provider?: AuthenticationProvider;
/**
* The requested validity in minutes for a token. Defaults to 20160 (two weeks).
*/
expiration?: number;
/**
* Duration (in minutes) that a token will be valid. Defaults to 20160 (two weeks).
*
* @deprecated use 'expiration' instead
*/
duration?: number;
/**
* Determines whether to open the authorization window in a new tab/window or in the current window.
*
* @browserOnly
*/
popup?: boolean;
/**
* The window features passed to [window.open()](https://developer.mozilla.org/en-US/docs/Web/API/Window/open) when `popup` is true. Defaults to `height=400,width=600,menubar=no,location=yes,resizable=yes,scrollbars=yes,status=yes`
*
* @browserOnly
*/
popupWindowFeatures?: string;
/**
* Duration (in minutes) that a refresh token will be valid.
*
* @nodeOnly
*/
refreshTokenTTL?: number;
/**
* The locale assumed to render the login page.
*
* @browserOnly
*/
locale?: string;
/**
* Applications can specify an opaque value for this parameter to correlate the authorization request sent with the received response. By default, clientId is used.
*
* @browserOnly
*/
state?: string;
[key: string]: any;
}
/**
* Options for the `UserSession` constructor.
*/
export interface IUserSessionOptions {
/**
* Client ID of your application. Can be obtained by registering an application
* on [ArcGIS for Developers](https://developers.arcgis.com/documentation/core-concepts/security-and-authentication/signing-in-arcgis-online-users/#registering-your-application),
* [ArcGIS Online](http://doc.arcgis.com/en/arcgis-online/share-maps/add-items.htm#ESRI_SECTION1_0D1B620254F745AE84F394289F8AF44B) or on your instance of ArcGIS Enterprise.
*/
clientId?: string;
/**
* A valid URL to redirect to after a user authorizes your application. Can be set on [ArcGIS for Developers](https://developers.arcgis.com/documentation/core-concepts/security-and-authentication/signing-in-arcgis-online-users/#registering-your-application),
* [ArcGIS Online](http://doc.arcgis.com/en/arcgis-online/share-maps/add-items.htm#ESRI_SECTION1_0D1B620254F745AE84F394289F8AF44B) or on your instance of ArcGIS Enterprise.
*/
redirectUri?: string;
/**
* OAuth 2.0 refresh token from a previous user session.
*/
refreshToken?: string;
/**
* Expiration date of the `refreshToken`
*/
refreshTokenExpires?: Date;
/**
* The authenticated user's username. Guaranteed to be unique across ArcGIS Online or your instance of ArcGIS Enterprise.
*/
username?: string;
/**
* Password for this user. Used in CLI apps where users cannot do OAuth 2.0.
*/
password?: string;
/**
* OAuth 2.0 access token from a previous user session.
*/
token?: string;
/**
* Expiration date for the `token`
*/
tokenExpires?: Date;
/**
* The ArcGIS Online or ArcGIS Enterprise portal you want to use for authentication. Defaults to `https://www.arcgis.com/sharing/rest` for the ArcGIS Online portal.
*/
portal?: string;
/**
* This value is set to true automatically if the ArcGIS Organization requires that requests be made over https.
*/
ssl?: boolean;
/**
* ArcGIS Authentication is used by default. Specifying an alternative will take users directly to the corresponding provider's OAuth page.
*/
provider?: AuthenticationProvider;
/**
* Duration of requested token validity in minutes. Used when requesting tokens with `username` and `password` or when validating the identity of unknown servers. Defaults to two weeks.
*/
tokenDuration?: number;
/**
* Duration (in minutes) that a refresh token will be valid.
*/
refreshTokenTTL?: number;
/**
* An unfederated ArcGIS Server instance known to recognize credentials supplied manually.
* ```js
* {
* server: "https://sampleserver6.arcgisonline.com/arcgis",
* token: "SOSlV3v..",
* tokenExpires: new Date(1545415669763)
* }
* ```
*/
server?: string;
}
/**
* ```js
* import { UserSession } from '@esri/arcgis-rest-auth';
* UserSession.beginOAuth2({
* // register an app of your own to create a unique clientId
* clientId: "abc123",
* redirectUri: 'https://yourapp.com/authenticate.html'
* })
* .then(session)
* // or
* new UserSession({
* username: "jsmith",
* password: "123456"
* })
* // or
* UserSession.deserialize(cache)
* ```
* Used to authenticate both ArcGIS Online and ArcGIS Enterprise users. `UserSession` includes helper methods for [OAuth 2.0](/arcgis-rest-js/guides/browser-authentication/) in both browser and server applications.
*/
export declare class UserSession implements IAuthenticationManager {
/**
* The current ArcGIS Online or ArcGIS Enterprise `token`.
*/
get token(): string;
/**
* The expiration time of the current `token`.
*/
get tokenExpires(): Date;
/**
* The current token to ArcGIS Online or ArcGIS Enterprise.
*/
get refreshToken(): string;
/**
* The expiration time of the current `refreshToken`.
*/
get refreshTokenExpires(): Date;
/**
* Deprecated, use `federatedServers` instead.
*
* @deprecated
*/
get trustedServers(): {
[key: string]: {
token: string;
expires: Date;
};
};
/**
* Begins a new browser-based OAuth 2.0 sign in. If `options.popup` is `true` the
* authentication window will open in a new tab/window and the function will return
* Promise<UserSession>. Otherwise, the user will be redirected to the
* authorization page in their current tab/window and the function will return `undefined`.
*
* @browserOnly
*/
static beginOAuth2(options: IOAuth2Options, win?: any): Promise<UserSession> | undefined;
/**
* Completes a browser-based OAuth 2.0 sign in. If `options.popup` is `true` the user
* will be returned to the previous window. Otherwise a new `UserSession`
* will be returned. You must pass the same values for `options.popup` and
* `options.portal` as you used in `beginOAuth2()`.
*
* @browserOnly
*/
static completeOAuth2(options: IOAuth2Options, win?: any): UserSession;
/**
* Request session information from the parent application
*
* When an application is embedded into another application via an IFrame, the embedded app can
* use `window.postMessage` to request credentials from the host application. This function wraps
* that behavior.
*
* The ArcGIS API for Javascript has this built into the Identity Manager as of the 4.19 release.
*
* Note: The parent application will not respond if the embedded app's origin is not:
* - the same origin as the parent or *.arcgis.com (JSAPI)
* - in the list of valid child origins (REST-JS)
*
*
* @param parentOrigin origin of the parent frame. Passed into the embedded application as `parentOrigin` query param
* @browserOnly
*/
static fromParent(parentOrigin: string, win?: any): Promise<any>;
/**
* Begins a new server-based OAuth 2.0 sign in. This will redirect the user to
* the ArcGIS Online or ArcGIS Enterprise authorization page.
*
* @nodeOnly
*/
static authorize(options: IOAuth2Options, response: http.ServerResponse): void;
/**
* Completes the server-based OAuth 2.0 sign in process by exchanging the `authorizationCode`
* for a `access_token`.
*
* @nodeOnly
*/
static exchangeAuthorizationCode(options: IOAuth2Options, authorizationCode: string): Promise<UserSession>;
static deserialize(str: string): UserSession;
/**
* Translates authentication from the format used in the [ArcGIS API for JavaScript](https://developers.arcgis.com/javascript/).
*
* ```js
* UserSession.fromCredential({
* userId: "jsmith",
* token: "secret"
* });
* ```
*
* @returns UserSession
*/
static fromCredential(credential: ICredential): UserSession;
/**
* Handle the response from the parent
* @param event DOM Event
*/
private static parentMessageHandler;
/**
* Client ID being used for authentication if provided in the `constructor`.
*/
readonly clientId: string;
/**
* The currently authenticated user if provided in the `constructor`.
*/
readonly username: string;
/**
* The currently authenticated user's password if provided in the `constructor`.
*/
readonly password: string;
/**
* The current portal the user is authenticated with.
*/
readonly portal: string;
/**
* This value is set to true automatically if the ArcGIS Organization requires that requests be made over https.
*/
readonly ssl: boolean;
/**
* The authentication provider to use.
*/
readonly provider: AuthenticationProvider;
/**
* Determines how long new tokens requested are valid.
*/
readonly tokenDuration: number;
/**
* A valid redirect URI for this application if provided in the `constructor`.
*/
readonly redirectUri: string;
/**
* Duration of new OAuth 2.0 refresh token validity (in minutes).
*/
readonly refreshTokenTTL: number;
/**
* An unfederated ArcGIS Server instance known to recognize credentials supplied manually.
* ```js
* {
* server: "https://sampleserver6.arcgisonline.com/arcgis",
* token: "SOSlV3v..",
* tokenExpires: new Date(1545415669763)
* }
* ```
*/
readonly server: string;
/**
* Hydrated by a call to [getUser()](#getUser-summary).
*/
private _user;
/**
* Hydrated by a call to [getPortal()](#getPortal-summary).
*/
private _portalInfo;
private _token;
private _tokenExpires;
private _refreshToken;
private _refreshTokenExpires;
private _pendingUserRequest;
private _pendingPortalRequest;
/**
* Internal object to keep track of pending token requests. Used to prevent
* duplicate token requests.
*/
private _pendingTokenRequests;
/**
* Internal list of tokens to 3rd party servers (federated servers) that have
* been created via `generateToken`. The object key is the root URL of the server.
*/
private federatedServers;
/**
* Internal list of 3rd party domains that should receive all cookies (credentials: "include").
* Used to for PKI and IWA workflows in high security environments.
*/
private trustedDomains;
private _hostHandler;
constructor(options: IUserSessionOptions);
/**
* Returns authentication in a format useable in the [ArcGIS API for JavaScript](https://developers.arcgis.com/javascript/).
*
* ```js
* esriId.registerToken(session.toCredential());
* ```
*
* @returns ICredential
*/
toCredential(): ICredential;
/**
* Returns information about the currently logged in [user](https://developers.arcgis.com/rest/users-groups-and-items/user.htm). Subsequent calls will *not* result in additional web traffic.
*
* ```js
* session.getUser()
* .then(response => {
* console.log(response.role); // "org_admin"
* })
* ```
*
* @param requestOptions - Options for the request. NOTE: `rawResponse` is not supported by this operation.
* @returns A Promise that will resolve with the data from the response.
*/
getUser(requestOptions?: IRequestOptions): Promise<IUser>;
/**
* Returns information about the currently logged in user's [portal](https://developers.arcgis.com/rest/users-groups-and-items/portal-self.htm). Subsequent calls will *not* result in additional web traffic.
*
* ```js
* session.getPortal()
* .then(response => {
* console.log(portal.name); // "City of ..."
* })
* ```
*
* @param requestOptions - Options for the request. NOTE: `rawResponse` is not supported by this operation.
* @returns A Promise that will resolve with the data from the response.
*/
getPortal(requestOptions?: IRequestOptions): Promise<any>;
/**
* Returns the username for the currently logged in [user](https://developers.arcgis.com/rest/users-groups-and-items/user.htm). Subsequent calls will *not* result in additional web traffic. This is also used internally when a username is required for some requests but is not present in the options.
*
* * ```js
* session.getUsername()
* .then(response => {
* console.log(response); // "casey_jones"
* })
* ```
*/
getUsername(): Promise<string>;
/**
* Gets an appropriate token for the given URL. If `portal` is ArcGIS Online and
* the request is to an ArcGIS Online domain `token` will be used. If the request
* is to the current `portal` the current `token` will also be used. However if
* the request is to an unknown server we will validate the server with a request
* to our current `portal`.
*/
getToken(url: string, requestOptions?: ITokenRequestOptions): Promise<string>;
/**
* Get application access information for the current user
* see `validateAppAccess` function for details
*
* @param clientId application client id
*/
validateAppAccess(clientId: string): Promise<IAppAccess>;
toJSON(): IUserSessionOptions;
serialize(): string;
/**
* For a "Host" app that embeds other platform apps via iframes, after authenticating the user
* and creating a UserSession, the app can then enable "post message" style authentication by calling
* this method.
*
* Internally this adds an event listener on window for the `message` event
*
* @param validChildOrigins Array of origins that are allowed to request authentication from the host app
*/
enablePostMessageAuth(validChildOrigins: string[], win?: any): any;
/**
* For a "Host" app that has embedded other platform apps via iframes, when the host needs
* to transition routes, it should call `UserSession.disablePostMessageAuth()` to remove
* the event listener and prevent memory leaks
*/
disablePostMessageAuth(win?: any): void;
/**
* Manually refreshes the current `token` and `tokenExpires`.
*/
refreshSession(requestOptions?: ITokenRequestOptions): Promise<UserSession>;
/**
* Determines the root of the ArcGIS Server or Portal for a given URL.
*
* @param url the URl to determine the root url for.
*/
getServerRootUrl(url: string): string;
/**
* Returns the proper [`credentials`] option for `fetch` for a given domain.
* See [trusted server](https://enterprise.arcgis.com/en/portal/latest/administer/windows/configure-security.htm#ESRI_SECTION1_70CC159B3540440AB325BE5D89DBE94A).
* Used internally by underlying request methods to add support for specific security considerations.
*
* @param url The url of the request
* @returns "include" or "same-origin"
*/
getDomainCredentials(url: string): RequestCredentials;
/**
* Return a function that closes over the validOrigins array and
* can be used as an event handler for the `message` event
*
* @param validOrigins Array of valid origins
*/
private createPostMessageHandler;
/**
* Validates that a given URL is properly federated with our current `portal`.
* Attempts to use the internal `federatedServers` cache first.
*/
private getTokenForServer;
/**
* Returns an unexpired token for the current `portal`.
*/
private getFreshToken;
/**
* Refreshes the current `token` and `tokenExpires` with `username` and
* `password`.
*/
private refreshWithUsernameAndPassword;
/**
* Refreshes the current `token` and `tokenExpires` with `refreshToken`.
*/
private refreshWithRefreshToken;
/**
* Exchanges an unexpired `refreshToken` for a new one, also updates `token` and
* `tokenExpires`.
*/
private refreshRefreshToken;
/**
* ensures that the authorizedCrossOriginDomains are obtained from the portal and cached
* so we can check them later.
*
* @returns this
*/
private fetchAuthorizedDomains;
}