Globus SDK for JavaScript
    Preparing search index...

    Class AuthorizationManager

    Provides management of Globus authorization context for your application.

    • Handles the OAuth protcol flow (via PKCE)
    • Token lifecycle management
    • Common errors (e.g., ConsentRequired, authorization_requirements)

    Once you configure your instance, you can determine the authenticated state using manager.authenticated.

    To prompt a user to authenticate, call manager.login() on user interaction – this will initiate the OAuth protocol flow with your configured client and scopes, resulting in an initial redirect to Globus Auth.

    Once the user authenticates with Globus Auth, they will be redirected to your application using the configured redirect URL. On this URL, you will need to call manager.handleCodeRedirect (using a manager instance configured in the same manner that initiated the manager.login() call) to complete the PKCE flow, exchanging the provided code for a valid token, or tokens.

    All tokens managed by the AuthorizationManager instance can be found on manager.token.

    The AuthorizationManager expects your Globus Application to be registered as an OAuth public client. In this Globus Web Application, this option is referenced as "Register a thick client or script that will be installed and run by users on their devices".

    import { authorization } from "globus/sdk";

    const manager = authorization.create({
    // Your registered Globus Application client ID.
    client: '...',
    // The redirect URL for your application; Where you will call `manager.handleCodeRedirect()`
    redirect: 'https://example.com/callback',
    // Known scopes required by your application.
    scopes: 'urn:globus:auth:scope:transfer.api.globus.org:all',
    });

    Once you have an instance of an AuthorizationManager, it can be passed to any service method as ServiceMethodOptions.manager or SDKOptions.manager option. The service method will determine if a token is required to make the request and will use the AuthorizationManager to retrieve the token.

    import { transfer } from "globus/sdk";
    const manager = authorization.create({ ... });
    const result = await (
    await globus.transfer.endpointSearch({
    query: { filter_fulltext: "Globus"},
    manager
    })
    ).json();
    Index
    events: {
        authenticated: Event<
            "authenticated",
            { isAuthenticated: boolean; token?: auth.TokenResponse },
        >;
        revoke: Event<"revoke", TokenRevocationResult>;
    } = ...

    Type Declaration

    • authenticated: Event<"authenticated", { isAuthenticated: boolean; token?: auth.TokenResponse }>

      Emitted when the authenticated state changes. AuthorizationManager.events#authenticated

    • revoke: Event<"revoke", TokenRevocationResult>

      Emitted when the user revokes their authentication. AuthorizationManager.events#revoke

    storage: Storage

    The storage system used by the AuthorizationManager.

    Storage

    tokens: TokenManager
    • Complete an authorization code flow started with startAuthorization(): validate the state, exchange the code for tokens, and add them to the instance (without resetting existing tokens).

      Parameters

      • request: Pick<AuthorizationRequest, "state" | "code_verifier" | "redirect_uri">

        The value returned by startAuthorization().

      • callback: URLSearchParams | URL | { code: string; state?: string | null }

        The code (and state) received on the redirect. A URL or URLSearchParams of the redirect can be provided directly, in which case it must include the expected state. When a { code } object is provided, state is validated if present, and can be omitted when the user copies the code from the Globus Auth "auth code" page.

      • Optionaloptions: { includeConsentedScopes?: boolean }
        • OptionalincludeConsentedScopes?: boolean

          Return tokens for all scopes the user has consented to for the client.

      Returns Promise<auth.TokenResponse>

      An Error if the redirect contains an error or the state does not match, or an OAuthTokenError if the code could not be exchanged.

    • Get a token for a resource server that is valid for at least minValidityMs, refreshing it if necessary (and possible).

      • When the stored token is valid for at least minValidityMs, it is returned as-is.
      • Otherwise, when the token has a refresh_token, it is refreshed (see refreshToken – one refresh at a time per resource server) and the new token is returned.
      • When the token can't be refreshed (no refresh_token, or the refresh fails), the stored token is returned if it is not yet expired, otherwise null.
      • Tokens without expiration metadata (stored before 4.3.0) are returned as-is.

      An expired token is never returned.

      Parameters

      • resourceServer: string

        The resource server of the token, e.g., transfer.api.globus.org.

      • Optionaloptions: { minValidityMs?: number; throwOnError?: boolean }
        • OptionalminValidityMs?: number

          The minimum number of milliseconds the token should be valid for.

        • OptionalthrowOnError?: boolean

          When true, a failed refresh throws an OAuthTokenError instead of falling back to the stored token or null. null is still returned when there is no stored token.

      Returns Promise<StoredToken | null>

      const token = await manager.getToken('transfer.api.globus.org', { minValidityMs: 30_000 });
      if (!token) {
      // The user needs to authenticate.
      }
      0
      
    • This method will attempt to complete the PKCE protocol flow.

      Parameters

      • options: {
            additionalParams?: { [key: string]: string };
            includeConsentedScopes?: boolean;
            shouldReplace?: boolean;
        } = ...

      Returns Promise<any>

    • Process a well-formed ConsentRequired error response from a Globus service and redirect the user to the Globus Auth login page with the necessary parameters.

      Parameters

      Returns Promise<void>

    • Handle an error response from a Globus service in the context of this AuthorizationManager. This method will introspect the response and attempt to handle any errors that should result in some additional Globus Auth interaction.

      Parameters

      • response: Record<string, unknown>

        The error response from a Globus service.

      • Optionaloptions: true | { additionalParams?: { [key: string]: string }; execute?: true }

        Options for handling the error response. If a boolean is provided, this will be treated as the options.execute value.

        • true
        • { additionalParams?: { [key: string]: string }; execute?: true }
          • OptionaladditionalParams?: { [key: string]: string }

            Additional query parameters to be included with the transport generated URL.

          • Optionalexecute?: true

            Whether to execute the handler immediately.

      Returns Promise<void>

    • Handle an error response from a Globus service in the context of this AuthorizationManager. This method will introspect the response and attempt to handle any errors that should result in some additional Globus Auth interaction.

      Parameters

      • response: Record<string, unknown>

        The error response from a Globus service.

      • Optionaloptions: false | { additionalParams?: { [key: string]: string }; execute?: false }

        Options for handling the error response. If a boolean is provided, this will be treated as the options.execute value.

        • false
        • { additionalParams?: { [key: string]: string }; execute?: false }
          • OptionaladditionalParams?: { [key: string]: string }

            Additional query parameters to be included with the transport generated URL.

          • Optionalexecute?: false

            Whether to execute the handler immediately.

      Returns Promise<() => Promise<void>>

    • Initiate the login process by redirecting to the Globus Auth login page.

      IMPORTANT: This method will reset the instance state before initiating the login process, including clearing all tokens from storage. If you need to maintain the current state, use the AuthorizationManager.prompt() method.

      Parameters

      • options: { additionalParams: {} } = ...

      Returns Promise<unknown>

      Passing parameters to the transport.
      const result = await manager.login({
      additionalParams: {
      redirect_uri: '/oauth/redirect-uri-runtime-override',
      },
      });
    • Prompt the user to authenticate with Globus Auth.

      Parameters

      • Optionaloptions: Partial<TransportOptions>

      Returns Promise<unknown>

      Passing parameters to the transport.
      const result = await manager.prompt({
      additionalParams: {
      redirect_uri: '/oauth/redirect-uri-runtime-override',
      },
      });
    • Use the refresh_token attribute of a token to obtain a new access token.

      Only one refresh request is made at a time for a resource server; concurrent calls for the same resource server will receive the result of the in-flight request.

      If the response omits a refresh_token, the existing refresh token is preserved.

      Parameters

      • token: auth.TokenWithRefresh

        The well-formed token with a refresh_token attribute.

      • options: { throwOnError: true }
        • throwOnError: true

          When true, an OAuthTokenError is thrown when the token cannot be refreshed, instead of resolving null. Use this to distinguish a refused refresh (error.requiresReauthentication) from an outage (error.status >= 500) or a network error (error.status === undefined).

      Returns Promise<auth.TokenResponse>

      The token response, or null if the token could not be refreshed (unless throwOnError is set).

    • Use the refresh_token attribute of a token to obtain a new access token.

      Only one refresh request is made at a time for a resource server; concurrent calls for the same resource server will receive the result of the in-flight request.

      If the response omits a refresh_token, the existing refresh token is preserved.

      Parameters

      • token: auth.TokenWithRefresh

        The well-formed token with a refresh_token attribute.

      • Optionaloptions: { throwOnError?: boolean }
        • OptionalthrowOnError?: boolean

          When true, an OAuthTokenError is thrown when the token cannot be refreshed, instead of resolving null. Use this to distinguish a refused refresh (error.requiresReauthentication) from an outage (error.status >= 500) or a network error (error.status === undefined).

      Returns Promise<auth.TokenResponse | null>

      The token response, or null if the token could not be refreshed (unless throwOnError is set).

    • Reset the authenticated state and clear all tokens from storage. This method does not emit the revoke event. If you need to emit the revoke event, use the AuthorizationManager.revoke method.

      Returns void

    • Revoke all of the available tokens (access tokens and refresh tokens), call AuthorizationManager.reset, and emit the revoke event.

      The instance is always reset (all tokens are removed from storage), and the revoke event is always emitted, even when one or more revocation requests fail. Failed revocations are reported in the resolved value (and the revoke event payload) so they can be logged or retried.

      Returns Promise<TokenRevocationResult>

      AuthorizationManager.events#revoke

      AuthorizationManager.reset

    • Start an authorization code flow (with PKCE) without using a browser transport, e.g., in a CLI, a local MCP server, or a desktop application.

      This method only builds the authorization request; it does not navigate, open a browser, or modify the instance state. Direct the user to the returned url, then pass the returned request, along with the code (and state) received on the redirect, to completeAuthorization().

      Unlike login(), the instance is not reset; tokens obtained with completeAuthorization() are added to the existing tokens, so this can be used to request additional consents.

      Parameters

      Returns Promise<AuthorizationRequest>

      const request = await manager.startAuthorization();
      console.log(`Please log in: ${request.url}`);
      const code = await readCodeFromStdin();
      await manager.completeAuthorization(request, { code });
      const request = await manager.startAuthorization({ redirect: 'http://127.0.0.1:8080/callback' });
      openBrowser(request.url);
      // ...in the HTTP handler for `/callback`:
      await manager.completeAuthorization(request, new URL(req.url, 'http://127.0.0.1:8080'));