@authgear/web
Version:
With Authgear SDK for Single Page Applications (SPA), you can easily integrate authentication features into your app (Angular, Vue, React, or any JavaScript websites). In most cases, it involves just a few lines of code to enable multiple authentication m
873 lines (838 loc) • 26.8 kB
TypeScript
/**
* AuthgearError is the root class of error produced by the SDK.
*
* @public
*/
export declare class AuthgearError extends Error {
/**
* underlyingError is the underlying error.
* The type is unknown because it is possible to throw anything in JavaScript.
* Use ordinary approaches, such as instanceof operator, to identify what it is.
*
* @public
*/
underlyingError?: unknown;
}
/**
* CancelError means cancel.
* If you catch an error and it is instanceof CancelError,
* then the operation was cancelled.
*
* @public
*/
export declare class CancelError extends AuthgearError {
}
/**
* ColorScheme represents the color scheme supported by Authgear.
* A colorscheme is either light or dark. Authgear supports both by default.
*
* @public
*/
export declare enum ColorScheme {
/**
* Force to use the light color scheme in the AuthUI when the project config is "Auto".
*/
Light = "light",
/**
* Force to use the dark color scheme in the AuthUI when the project config is "Auto".
*/
Dark = "dark"
}
/**
* Options for the constructor of a Container.
*
* @public
*/
export declare interface ContainerOptions {
/**
* The name of the container. The name is used as the namespace of `TokenStorage`.
* One use case is to use multiple containers with different names to support signing in multiple accounts.
* @defaultValue "default"
*/
name?: string;
}
/**
* ErrorName contains all possible name in {@link ServerError}
*
* @public
*/
export declare enum ErrorName {
/**
* Indicates that the server does not understand the request (i.e. syntactic error).
* Status code: 400
*/
BadRequest = "BadRequest",
/**
* Indicates that the server understands the request, but refuse to process it (i.e. semantic error).
* Status code: 400
*/
Invalid = "Invalid",
/**
* Indicates that the client does not have valid credentials (i.e. authentication error).
* Status code: 401
*/
Unauthorized = "Unauthorized",
/**
* Indicates that the client's credentials are not allowed for the request (i.e. authorization error).
* Status code: 403
*/
Forbidden = "Forbidden",
/**
* Indicates that the server cannot find the requested resource.
* Status code: 404
*/
NotFound = "NotFound",
/**
* Indicates that the resource is already exists on the server.
* Status code: 409
*/
AlreadyExists = "AlreadyExists",
/**
* Indicates that the client has sent too many requests in a given amount of time.
* Status code: 429
*/
TooManyRequest = "TooManyRequest",
/**
* Indicates that the server encountered an unexpected condition and unable to process the request.
* Status code: 500
*/
InternalError = "InternalError",
/**
* Indicates that the server is not ready to handle the request.
* Status code: 503
*/
ServiceUnavailable = "ServiceUnavailable"
}
/**
* OAuthError represents the oauth error response.
* https://tools.ietf.org/html/rfc6749#section-4.1.2.1
*
* @public
*/
export declare class OAuthError extends AuthgearError {
state?: string;
error: string;
error_description?: string;
error_uri?: string;
constructor({ state, error, error_description, error_uri, }: {
state?: string;
error: string;
error_description?: string;
error_uri?: string;
});
}
/**
* The path of the page in Authgear.
*
* @public
*/
export declare enum Page {
/**
* The path of the settings page in Authgear.
*/
Settings = "/settings",
/**
* The path of the indenties page in Authgear.
*/
Identities = "/settings/identities"
}
/**
* The device secret is not found. This may happen if the "Pre-authenticated URL" feature was not enabled when the user logged in during this session.
* Ask the user to log in again to enable this feature.
*
* @public
*/
export declare class PreAuthenticatedURLDeviceSecretNotFoundError extends PreAuthenticatedURLNotAllowedError {
}
/**
* The user logged in from an older SDK version that does not support the pre-authenticated URL.
* Ask the user to log in again to resolve the problem.
*
* @public
*/
export declare class PreAuthenticatedURLIDTokenNotFoundError extends PreAuthenticatedURLNotAllowedError {
}
/**
* This may happen if the "Pre-authenticated URL" feature was not enabled when the user logged in during this session.
* Ask the user to log in again to enable this feature.
*
* @public
*/
export declare class PreAuthenticatedURLInsufficientScopeError extends PreAuthenticatedURLNotAllowedError {
}
/**
* PreAuthenticatedURLNotAllowedError is the root class of errors related to pre-authenticated URL.
*
* @public
*/
export declare class PreAuthenticatedURLNotAllowedError extends AuthgearError {
}
/**
* Prompt parameter options.
*
* @public
*/
export declare enum PromptOption {
/**
* The `none` prompt is used to sliently authenticate the user without prompting for any action.
* This prompt bypasses the need for `login` and `consent` prompts
* only when the user has previously given consent to the application and has an active session.
*/
None = "none",
/**
* The `login` prompt requires the user to log in to the authentication provider which forces the user to re-authenticate.
*/
Login = "login"
}
/**
* ServerError represents error received from the server.
*
* @public
*/
export declare class ServerError extends AuthgearError {
/**
* Error name.
*
* @remarks
* See {@link ErrorName} for possible values.
* New error names may be added in future.
*/
name: string;
/**
* Error message.
*
* @remarks
* Error messages are provided for convenience, and not stable APIs;
* Consumers should use {@link ServerError.name} or
* {@link ServerError.reason} to distinguish between different errors.
*/
message: string;
/**
* Error reason.
*/
reason: string;
/**
* Additional error information.
*/
info?: unknown;
constructor(message: string, name: string, reason: string, info?: unknown);
}
/**
* The session state.
*
* An freshly constructed instance has the session state "UNKNOWN";
*
* After a call to configure, the session state would become "AUTHENTICATED" if a previous session was found,
* or "NO_SESSION" if such session was not found.
*
* Please refer to {@link SessionStateChangeReason} for more information.
*
* @public
*/
export declare enum SessionState {
Unknown = "UNKNOWN",
NoSession = "NO_SESSION",
Authenticated = "AUTHENTICATED"
}
/**
* The reason why SessionState is changed.
*
* These reasons can be thought of as the transition of a SessionState, which is described as follows:
*
* ```
* LOGOUT / INVALID / CLEAR
* +----------------------------------------------+
* v |
* State: UNKNOWN ----- NO_TOKEN ----> State: NO_SESSION ---- AUTHENTICATED -----> State: AUTHENTICATED
* | ^
* +--------------------------------------------------------------------------------+
* FOUND_TOKEN
* ```
* @public
*/
export declare enum SessionStateChangeReason {
NoToken = "NO_TOKEN",
FoundToken = "FOUND_TOKEN",
Authenticated = "AUTHENTICATED",
Logout = "LOGOUT",
Invalid = "INVALID",
Clear = "CLEAR"
}
/**
* The actions that can be performed in Authgear settings page.
*
* @public
*/
export declare enum SettingsAction {
/**
* Change password in Authgear settings page.
*/
ChangePassword = "change_password",
/**
* Delete account in Authgear settings page.
*/
DeleteAccount = "delete_account"
}
/**
* TokenStorage is an interface controlling when refresh tokens are stored.
* Normally you do not need to implement this interface.
* You can use one of those implementations provided by the SDK.
*
* @public
*/
export declare interface TokenStorage {
/**
* Stores a refresh token for a give namespace to the storage.
*/
setRefreshToken(namespace: string, refreshToken: string): Promise<void>;
/**
* Retrieves the refresh token associated with a specific namespace in the storage.
*/
getRefreshToken(namespace: string): Promise<string | null>;
/**
* Deletes the refresh token for the specified namespace in the storage.
*/
delRefreshToken(namespace: string): Promise<void>;
}
/**
* TransientTokenStorage stores the refresh token in memory.
* The refresh token is forgotten as soon as the user quits the app, or
* the app was killed by the system.
* When the app launches again next time, no refresh token is found.
* The user is considered unauthenticated.
* This implies the user needs to authenticate over again on every app launch.
*
* @public
*/
export declare class TransientTokenStorage implements TokenStorage {
private keyMaker;
private storageDriver;
constructor();
setRefreshToken(namespace: string, refreshToken: string): Promise<void>;
getRefreshToken(namespace: string): Promise<string | null>;
delRefreshToken(namespace: string): Promise<void>;
}
/**
* UserInfo is the result of fetchUserInfo.
* It contains `sub` which is the User ID,
* as well as OIDC standard claims like `email`,
* see https://openid.net/specs/openid-connect-core-1_0.html#StandardClaims.
*
* In addition to these standard claims, it may include custom claims
* defined by Authgear to support additional functionality like `isVerified`.
*
* @public
*/
export declare interface UserInfo {
sub: string;
isVerified: boolean;
isAnonymous: boolean;
canReauthenticate: boolean;
roles?: string[];
raw: Record<string, unknown>;
customAttributes: Record<string, unknown>;
email?: string;
emailVerified?: boolean;
phoneNumber?: string;
phoneNumberVerified?: boolean;
preferredUsername?: string;
familyName?: string;
givenName?: string;
middleName?: string;
name?: string;
nickname?: string;
picture?: string;
profile?: string;
website?: string;
gender?: string;
birthdate?: string;
zoneinfo?: string;
locale?: string;
address?: {
formatted?: string;
streetAddress?: string;
locality?: string;
region?: string;
postalCode?: string;
country?: string;
};
}
/**
* @public
*/
export declare const VERSION: string;
export { }
/**
* Auth UI authorization options
*
* @public
*/
export declare interface AuthenticateOptions {
/**
* The value should be a valid Redirect URI to which the response will be sent after authentication.
* You must also add a Redirect URI in Authgear Poral via the Redirect URI section of your Authgear Application.
*/
redirectURI: string;
/**
* OAuth 2.0 state value.
*/
state?: string;
/**
* Custom state. Use this parameter to provide parameters from the client application to Custom UI. The string in xState can be accessed by the Custom UI.
*
* Ignore this parameter if default AuthUI is used.
*/
xState?: string;
/**
* OIDC prompt parameter.
*
* Prompt parameter will be used for Authgear authorization, it will also be forwarded to the underlying SSO providers.
*
* For Authgear, currently, only login is supported. Other unsupported values will be ignored.
*
* For the underlying SSO providers, some providers only support a single value rather than a list.
* The first supported value will be used for that case.
* e.g. Azure Active Directory
*
*/
prompt?: PromptOption[] | PromptOption;
/**
* UI locale tags. You can use this parameter to set the display language for Auth UI.
*
* First, enable the language you want to change to in Authgear Portal (Your project \> UI Settings \> click on the settings icon beside Language.)
*
* For example, to change the language for Auth UI to Hong Kong,
* set the value for uiLocales to ["zh-HK"] after enabling "Chinese (Hong Kong)" in Authgear Portal.
*/
uiLocales?: string[];
/**
* Initial page to open. Valid values are 'login' and 'signup'.
*/
page?: string;
/**
* Auto-redirect the user to the OAuth provider. You can set the value for each OAuth provider in Authgear portal via
* Authentication \> Social / Enterprise Login.
*
* For example, to auto-redirect your users to sign in with Google, first, set the alias for Sign in with Google to "google" in Authgear portal,
* then set oauthProviderAlias to "google".
*/
oauthProviderAlias?: string;
/**
* Authentication flow group
*/
authenticationFlowGroup?: string;
}
/**
* Result of authorization.
*
* @public
*/
export declare interface AuthenticateResult {
/**
* OAuth 2.0 state value.
*/
state?: string;
/**
* UserInfo.
*/
userInfo: UserInfo;
}
/**
* @public
*/
export declare interface ConfigureOptions {
/**
* The OAuth client ID.
*/
clientID: string;
/**
* The endpoint.
*/
endpoint: string;
/**
* sessionType indicates how session is supposed to be stored.
* This must match the server side configuration.
*
* If your backend is a server-side rendering website or webapp,
* then you should use cookie.
*
* Normally, you need to set up a custom domain so that
* your backend and Authgear can both read and write cookie in the same root domain.
* You also need to tell the SDK cookie is being used, by specifying "cookie" here.
*
* If not specified, default to "refresh_token".
*/
sessionType?: "cookie" | "refresh_token";
/**
* Single-sign-on (SSO) is defined as login once, logged in all apps.
* When isSSOEnabled is true, users only need to enter their authentication credentials once.
* When the user login the second app, they will see the continue screen so that they can log in with just a click.
* Logout from one app will also logout from all the apps.
*
* This flag is used when sessionType is "refresh_token" only.
* When sessionType is "cookie", sessions are shared among subdomains and this flag is not needed.
* @defaultValue false
*/
isSSOEnabled?: boolean;
}
/**
* Default container.
*
* @remarks
* This is a global shared container, provided for convenience.
*
* @public
*/
declare const defaultContainer: WebContainer;
export default defaultContainer;
/**
* Auth UI anonymous user promotion options
*
* @public
*/
export declare interface PromoteOptions {
/**
* The value should be a valid Redirect URI to which the response will be sent after authentication.
* You must also add a Redirect URI in Authgear Poral via the Redirect URI section of your Authgear Application.
*/
redirectURI: string;
/**
* OAuth 2.0 state value.
*/
state?: string;
/**
* Custom state. Use this parameter to provide parameters from the client application to Custom UI. The string in xState can be accessed by the Custom UI.
*
* Ignore this parameter if default AuthUI is used.
*/
xState?: string;
/**
* UI locale tags. You can use this parameter to set the display language for Auth UI.
*
* First, enable the language you want to change to in Authgear Portal (Your project \> UI Settings \> click on the settings icon beside Language.)
*
* For example, to change the language for Auth UI to Hong Kong,
* set the value for uiLocales to ["zh-HK"] after enabling "Chinese (Hong Kong)" in Authgear Portal.
*/
uiLocales?: string[];
}
/**
* Options for reauthentication
* @public
*/
export declare interface ReauthenticateOptions {
/**
* The value should be a valid Redirect URI to which the response will be sent after authentication.
* You must also add a Redirect URI in Authgear Poral via the Redirect URI section of your Authgear Application.
*/
redirectURI: string;
/**
* OAuth 2.0 state value.
*/
state?: string;
/**
* Custom state. Use this parameter to provide parameters from the client application to Custom UI. The string in xState can be accessed by the Custom UI.
*
* Ignore this parameter if default AuthUI is used.
*/
xState?: string;
/**
* UI locale tags. You can use this parameter to set the display language for Auth UI.
*
* First, enable the language you want to change to in Authgear Portal (Your project \> UI Settings \> click on the settings icon beside Language.)
*
* For example, to change the language for Auth UI to Hong Kong,
* set the value for uiLocales to ["zh-HK"] after enabling "Chinese (Hong Kong)" in Authgear Portal.
*/
uiLocales?: string[];
/**
* OIDC max_age
*/
maxAge?: number;
/**
* Authentication flow group
*/
authenticationFlowGroup?: string;
}
/**
* Result of reauthentication
*
* @public
*/
export declare interface ReauthenticateResult {
/**
* OAuth 2.0 state value.
*/
state?: string;
/**
* UserInfo.
*/
userInfo: UserInfo;
}
/**
* @public
*/
export declare interface SettingOptions {
/**
* UI locale tags. You can use this parameter to set the display language for Auth UI.
*
* First, enable the language you want to change to in Authgear Portal (Your project \> UI Settings \> click on the settings icon beside Language.)
*
* For example, to change the language for Auth UI to Hong Kong,
* set the value for uiLocales to ["zh-HK"] after enabling "Chinese (Hong Kong)" in Authgear Portal.
*/
uiLocales?: string[];
/**
* Indicates whether to open the settings page in the same tab
*/
openInSameTab?: boolean;
}
/**
* Auth UI settings action options
*
* @public
*/
export declare interface SettingsActionOptions {
/**
* The value should be a valid Redirect URI to which the response will be sent after authentication.
* You must also add a Redirect URI in Authgear Poral via the Redirect URI section of your Authgear Application.
*/
redirectURI: string;
/**
* OAuth 2.0 state value.
*/
state?: string;
/**
* Custom state. Use this parameter to provide parameters from the client application to Custom UI. The string in xState can be accessed by the Custom UI.
*
* Ignore this parameter if default AuthUI is used.
*/
xState?: string;
/**
* UI locale tags. You can use this parameter to set the display language for Auth UI.
*
* First, enable the language you want to change to in Authgear Portal (Your project \> UI Settings \> click on the settings icon beside Language.)
*
* For example, to change the language for Auth UI to Hong Kong,
* set the value for uiLocales to ["zh-HK"] after enabling "Chinese (Hong Kong)" in Authgear Portal.
*/
uiLocales?: string[];
}
/**
* WebContainer is the entrypoint of the SDK.
* An instance of a container allows the user to authenticate, reauthenticate, etc.
*
* Every container has a name.
* The default name of a container is `default`.
* If your app supports multi login sessions, you can use multiple containers with different names.
* You are responsible for managing the list of names in this case.
*
* @public
*/
export declare class WebContainer {
/**
* @public
*/
sessionType: "cookie" | "refresh_token";
/**
* @public
*/
delegate?: WebContainerDelegate;
/**
*
* Unique ID for this container.
* @defaultValue "default"
*
* @public
*/
get name(): string;
set name(name: string);
/**
* OIDC client ID
*
* @public
*/
get clientID(): string | undefined;
set clientID(clientID: string | undefined);
/**
* Is SSO enabled
*
* @public
*/
get isSSOEnabled(): boolean;
set isSSOEnabled(isSSOEnabled: boolean);
/**
*
* @public
*/
get sessionState(): SessionState;
set sessionState(sessionState: SessionState);
/**
*
* @public
*/
get accessToken(): string | undefined;
set accessToken(accessToken: string | undefined);
constructor(options?: ContainerOptions);
/**
* getIDTokenHint() returns the ID token for the OIDC id_token_hint parameter.
*
* @public
*/
getIDTokenHint(): string | undefined;
/**
* canReauthenticate() reports whether the current user can reauthenticate.
* The information comes from the ID token and the ID token is NOT verified.
*
* @public
*/
canReauthenticate(): boolean;
/**
* getAuthTime() reports the last time the user was authenticated.
* The information comes from the ID token and the ID token is NOT verified.
*
* @public
*/
getAuthTime(): Date | undefined;
/**
* refreshIDToken() asks the server to issue an ID token with latest claims.
* After refreshing, getIDTokenHint() and canReauthenticate() may return up-to-date value.
*
* @public
*/
refreshIDToken(): Promise<void>;
/**
* configure() configures the container with the client ID and the endpoint.
* It also does local IO to retrieve the refresh token.
* It only obtains the refresh token locally and no network call will
* be triggered. So the session state maybe outdated for some reason, e.g.
* user session is revoked. fetchUserInfo should be called to obtain the
* latest user session state.
*
* configure() can be called more than once if it failed.
* Otherwise, it is NOT recommended to call it more than once.
*
* @public
*/
configure(options: ConfigureOptions): Promise<void>;
/**
* Start authentication by redirecting to the authorization endpoint.
*/
startAuthentication(options: AuthenticateOptions): Promise<void>;
/**
* Start settings action "change_password" by redirecting to the authorization endpoint.
*
* @public
*/
startChangePassword(options: SettingsActionOptions): Promise<void>;
/**
* Start settings action "delete_account" by redirecting to the authorization endpoint.
*
* @public
*/
startDeleteAccount(options: SettingsActionOptions): Promise<void>;
/**
* Start reauthentication by redirecting to the authorization endpoint.
*/
startReauthentication(options: ReauthenticateOptions): Promise<void>;
/**
* Start promote anonymous user by redirecting to the authorization endpoint.
*/
startPromoteAnonymousUser(options: PromoteOptions): Promise<void>;
/**
* Finish authentication.
*
* It may reject with OAuthError.
*/
finishAuthentication(): Promise<AuthenticateResult>;
/**
* Finish reauthentication.
*
* It may reject with OAuthError.
*/
finishReauthentication(): Promise<ReauthenticateResult>;
/**
* Finish settings action "change_password".
*
* It may reject with OAuthError.
*
* @public
*/
finishChangePassword(): Promise<void>;
/**
* Finish settings action "delete_account".
*
* It may reject with OAuthError.
*
* @public
*/
finishDeleteAccount(): Promise<void>;
/**
* Finish promote anonymous user.
*
* It may reject with OAuthError.
*/
finishPromoteAnonymousUser(): Promise<ReauthenticateResult>;
open(page: Page, options?: SettingOptions): Promise<void>;
/**
* Logout.
*
* @remarks
* If `force` parameter is set to `true`, all potential errors (e.g. network
* error) would be ignored.
*
* `redirectURI` is required. User will be redirected to the uri after they
* have logged out.
*
* @param options - Logout options
*/
logout(options?: {
force?: boolean;
redirectURI: string;
}): Promise<void>;
/**
* Authenticate as an anonymous user.
*/
authenticateAnonymously(): Promise<AuthenticateResult>;
private _logoutRefreshToken;
private _logoutCookie;
private _redirectToEndSessionEndpoint;
/**
* Make authorize URL makes authorize URL based on options.
*
* This function will be used if developer wants to redirection in their own
* code.
*/
makeAuthorizeURL(options: AuthenticateOptions): Promise<string>;
/**
* Fetch user info.
*/
fetchUserInfo(): Promise<UserInfo>;
/**
* @public
*/
refreshAccessTokenIfNeeded(): Promise<void>;
/**
* Fetch function for you to call your application server.
* The fetch function will include Authorization header in your application
* request, and handle refresh access token automatically.
*
* @public
*/
fetch(input: RequestInfo, init?: RequestInit): Promise<Response>;
}
/**
* @public
*/
export declare interface WebContainerDelegate {
/**
* This callback will be called when the session state is changed.
*
* For example, when the user logs out, the new state is "NO_SESSION"
* and the reason is "LOGOUT".
*
* @public
*/
onSessionStateChange: (container: WebContainer, reason: SessionStateChangeReason) => void;
}
export { }