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 in both browser and server applications.

Implements

  • IAuthenticationManager

Constructors

Properties

_hostHandler: any
_pendingPortalRequest: any
_pendingTokenRequests: any

Internal object to keep track of pending token requests. Used to prevent duplicate token requests.

_pendingUserRequest: any
_portalInfo: any

Hydrated by a call to getPortal().

_refreshToken: any
_refreshTokenExpires: any
_token: any
_tokenExpires: any
_user: any

Hydrated by a call to getUser().

clientId: string

Client ID being used for authentication if provided in the constructor.

createPostMessageHandler: any

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

federatedServers: any

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.

fetchAuthorizedDomains: any

ensures that the authorizedCrossOriginDomains are obtained from the portal and cached so we can check them later.

Returns

this

getFreshToken: any

Returns an unexpired token for the current portal.

getTokenForServer: any

Validates that a given URL is properly federated with our current portal. Attempts to use the internal federatedServers cache first.

password: string

The currently authenticated user's password if provided in the constructor.

portal: string

The current portal the user is authenticated with.

provider: AuthenticationProvider

The authentication provider to use.

redirectUri: string

A valid redirect URI for this application if provided in the constructor.

refreshRefreshToken: any

Exchanges an unexpired refreshToken for a new one, also updates token and tokenExpires.

refreshTokenTTL: number

Duration of new OAuth 2.0 refresh token validity (in minutes).

refreshWithRefreshToken: any

Refreshes the current token and tokenExpires with refreshToken.

refreshWithUsernameAndPassword: any

Refreshes the current token and tokenExpires with username and password.

server: string

An unfederated ArcGIS Server instance known to recognize credentials supplied manually.

{
server: "https://sampleserver6.arcgisonline.com/arcgis",
token: "SOSlV3v..",
tokenExpires: new Date(1545415669763)
}
ssl: boolean

This value is set to true automatically if the ArcGIS Organization requires that requests be made over https.

tokenDuration: number

Determines how long new tokens requested are valid.

trustedDomains: any

Internal list of 3rd party domains that should receive all cookies (credentials: "include"). Used to for PKI and IWA workflows in high security environments.

username: string

The currently authenticated user if provided in the constructor.

parentMessageHandler: any

Handle the response from the parent

Param: event

DOM Event

Accessors

  • get refreshToken(): string
  • The current token to ArcGIS Online or ArcGIS Enterprise.

    Returns string

  • get refreshTokenExpires(): Date
  • The expiration time of the current refreshToken.

    Returns Date

  • get token(): string
  • The current ArcGIS Online or ArcGIS Enterprise token.

    Returns string

  • get tokenExpires(): Date
  • The expiration time of the current token.

    Returns Date

  • get trustedServers(): {
        [key: string]: {
            expires: Date;
            token: string;
        };
    }
  • Deprecated, use federatedServers instead.

    Returns {
        [key: string]: {
            expires: Date;
            token: string;
        };
    }

    • [key: string]: {
          expires: Date;
          token: string;
      }
      • expires: Date
      • token: string

    Deprecated

Methods

  • 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

    Parameters

    • Optional win: any

    Returns void

  • 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

    Parameters

    • validChildOrigins: string[]

      Array of origins that are allowed to request authentication from the host app

    • Optional win: any

    Returns any

  • Returns the proper [credentials] option for fetch for a given domain. See trusted server. Used internally by underlying request methods to add support for specific security considerations.

    Parameters

    • url: string

      The url of the request

    Returns RequestCredentials

    "include" or "same-origin"

  • Returns information about the currently logged in user's portal. Subsequent calls will not result in additional web traffic.

    session.getPortal()
    .then(response => {
    console.log(portal.name); // "City of ..."
    })

    Parameters

    • Optional requestOptions: IRequestOptions

      Options for the request. NOTE: rawResponse is not supported by this operation.

    Returns Promise<any>

    A Promise that will resolve with the data from the response.

  • Determines the root of the ArcGIS Server or Portal for a given URL.

    Parameters

    • url: string

      the URl to determine the root url for.

    Returns 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.

    Parameters

    • url: string
    • Optional requestOptions: ITokenRequestOptions

    Returns Promise<string>

  • Returns information about the currently logged in user. Subsequent calls will not result in additional web traffic.

    session.getUser()
    .then(response => {
    console.log(response.role); // "org_admin"
    })

    Parameters

    • Optional requestOptions: IRequestOptions

      Options for the request. NOTE: rawResponse is not supported by this operation.

    Returns Promise<IUser>

    A Promise that will resolve with the data from the response.

  • Returns the username for the currently logged in user. 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.

    • 
      

    session.getUsername() .then(response => { console.log(response); // "casey_jones" }) ```

    Returns Promise<string>

  • Manually refreshes the current token and tokenExpires.

    Parameters

    • Optional requestOptions: ITokenRequestOptions

    Returns Promise<UserSession>

  • Returns string

  • Returns authentication in a format useable in the ArcGIS API for JavaScript.

    esriId.registerToken(session.toCredential());
    

    Returns ICredential

    ICredential

  • Get application access information for the current user see validateAppAccess function for details

    Parameters

    • clientId: string

      application client id

    Returns Promise<IAppAccess>

  • Begins a new server-based OAuth 2.0 sign in. This will redirect the user to the ArcGIS Online or ArcGIS Enterprise authorization page.

    Parameters

    • options: IOAuth2Options
    • response: ServerResponse<IncomingMessage>

    Returns void

    Node Only

  • 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.

    Parameters

    • options: IOAuth2Options
    • Optional win: any

    Returns Promise<UserSession>

    Browser Only

  • 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().

    Parameters

    • options: IOAuth2Options
    • Optional win: any

    Returns UserSession

    Browser Only

  • Parameters

    • str: string

    Returns UserSession

  • Completes the server-based OAuth 2.0 sign in process by exchanging the authorizationCode for a access_token.

    Parameters

    • options: IOAuth2Options
    • authorizationCode: string

    Returns Promise<UserSession>

    Node Only

  • Translates authentication from the format used in the ArcGIS API for JavaScript.

    UserSession.fromCredential({
    userId: "jsmith",
    token: "secret"
    });

    Parameters

    • credential: ICredential

    Returns UserSession

    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)

    Parameters

    • parentOrigin: string

      origin of the parent frame. Passed into the embedded application as parentOrigin query param

    • Optional win: any

    Returns Promise<any>

    Browser Only