Skip to content

Instantly share code, notes, and snippets.

@codeaid
Last active October 1, 2020 12:27
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save codeaid/1deacf28ab56cea3b715e83e520aae32 to your computer and use it in GitHub Desktop.
Save codeaid/1deacf28ab56cea3b715e83e520aae32 to your computer and use it in GitHub Desktop.
Base TypeScript type definitions for @okta/okta-auth-js v2.5.0
/* tslint:disable:max-classes-per-file */
declare module '@okta/okta-auth-js' {
// Custom HTTP request handler implementation.
export type OktaHttpRequestClient = (
method: string,
url: string,
args: Array<any>,
) => Promise<string>;
// Authorization response mode.
export type OktaTokenResponseMode = 'form_post' | 'fragment' | 'okta_post_message' | 'query';
// Response type determining the authorization flow.
export type OktaTokenResponseType = 'code' | 'id_token' | 'token';
// List of token event types.
export type OktaTokenEventType = 'error' | 'expired' | 'renewed';
// List of token storage backends.
export type OktaTokenStorageType = 'cookie' | 'localStorage' | 'sessionStorage';
// Union including a list of reserved scopes as well as enabling usage of custom ones. .
export type OktaScope =
| 'address'
| 'email'
| 'groups'
| 'offline_access'
| 'openid'
| 'phone'
| 'profile'
| string;
export class OktaOAuthError extends Error {
public readonly errorCode: string;
public readonly errorSummary: string;
public readonly message: string;
public readonly name: string;
}
export class OktaAuthApiError extends Error {
public readonly errorCauses: Array<string>;
public readonly errorCode: string;
public readonly errorId: string;
public readonly errorLink: string;
public readonly errorSummary: string;
public readonly message: string;
public readonly name: string;
}
export class OktaAuthPollStopError extends Error {
public readonly message: string;
public readonly name: string;
}
export class OktaAuthSdkError extends Error {
public readonly errorCauses: Array<string>;
public readonly errorCode: string;
public readonly errorId: string;
public readonly errorLink: string;
public readonly errorSummary: string;
public readonly message: string;
public readonly name: string;
}
type OktaError = OktaOAuthError | OktaAuthApiError | OktaAuthPollStopError | OktaAuthSdkError;
// Type describing list of reserved OpenID scopes as well as enabling usage of custom ones.
export interface OktaTokenClaims {
aud?: string;
cid?: string;
exp?: number;
groups?: Array<string>;
iat?: number;
iss?: string;
jti?: string;
scp?: Array<OktaScope>;
sub?: string;
uid?: string;
ver?: number;
[key: srirng]: any;
}
// Object representing an Okta authorization token.
export interface OktaToken {
accessToken?: string;
authorizeUrl: string;
claims: OktaTokenClaims;
clientId: string;
expiresAt: number;
idToken?: string;
issuer: string;
scopes: Array<string>;
}
// Object representing options available for use with the token handler methods.
export interface OktaTokenOptions {
// A nonce that will be validated in an id_token. This is usually only provided
// during redirect flows to obtain an authorization code that will be exchanged for an
// id_token. Defaults to a random string.
nonce?: string;
// Specifies how the authorization response should be returned. You will generally not need
// to set this unless you want to override the default values for token.getWithRedirect().
responseMode?: OktaTokenResponseMode;
// Specifies response type for OIDC authentication.
responseType?: OktaTokenResponseType | Array<OktaTokenResponseType>;
// Specifies what information should be available in the returned id_token or access_token.
scopes?: Array<OktaScope>;
// Specify an Okta session token to skip repeated authentication when the user is already
// authenticated using the authentication flow.
sessionToken?: string;
// Specify a state that will be validated in an OAuth response. This is usually only
// provided during redirect flows to obtain an authorization code. Defaults to a random
// string.
state?: string;
}
export interface OktaTokenHandler {
/**
* Generate a token without prompting the user to log in when a session token has previously
* been obtained from the authorization flows or a session already exists.
*
* @param {OktaTokenOptions} options Request options
*/
getWithoutPrompt(options?: OktaTokenOptions): any;
/**
* Generate a token by displaying a popup window.
*
* @param {OktaTokenOptions} options Request options
*/
getWithPopup(options?: OktaTokenOptions): any;
/**
* Generate a token by redirecting to Okta.
*
* @param {OktaTokenOptions} options Request options
*/
getWithRedirect(options?: OktaTokenOptions): any;
/**
* Parse the access or ID token from the specified URL. If an ID token is present, it will
* be verified and validated before being available for use.
*
* @param {string} url Source authentication redirect URL
*/
parseFromUrl(url?: string): Promise<OktaToken>;
/**
* Decode a raw ID token into a token object
*
* @param {string} tokenStr Serialized JWT token
*/
decode(tokenStr: string);
/**
* Manually verify the validity of an ID token's claims and check the signature on browsers
* that support web cryptography
*
* @param {OktaToken} token An ID token to verify.
* @param {OktaOptions} options Optional object to assert ID token claim values. Defaults to
* the configuration passed in during client instantiation.
*/
verify(token: OktaToken, options?: OktaOptions);
}
type OktaTokenErrorEventHandler = (error: OktaError) => void;
type OktaTokenExpiredEventHandler = (key: string, token: OktaToken) => void;
type OktaTokenRenewedEventHandler = (
key: string,
newToken: OktaToken,
oldToken: OktaToken,
) => void;
export interface OktaTokenManager {
/**
* After receiving an access_token or id_token, add it to the token manager to manage token
* expiration and renew operations. When a token is added to the token manager, it is
* automatically renewed when it expires.
*
* @param {string} key Unique key to store the token in the token manager
* @param {OktaToken} token Token object that will be added
*/
add(key: string, token: OktaToken): Promise<void>;
/**
* Get a token that you have previously added to the token manager with the given key
*
* @param {string} key Key for the token you want to get
*/
get(key: string): Promise<OktaToken | undefined>;
/**
* Remove a token from the token manager with the given key
*
* @param {string} key Key for the token you want to remove
*/
remove(key: string): Promise<void>;
/**
* Remove all tokens from the token manager
*/
clear(): Promise<void>;
/**
* Manually renew a token before it expires
*
* @param {string} key Key for the token you want to renew
*/
renew(key: string): Promise<OktaToken>;
/**
* Subscribe to an event published by the token manager
*
* @param {OktaTokenEventType} event Event to subscribe to
* @param {Function} callback Function to call when the event is triggered
* @param {any} context Optional context to bind the callback to
*/
on(event: 'error', callback: OktaTokenErrorEventHandler, context?: any): void;
on(event: 'expired', callback: OktaTokenExpiredEventHandler, context?: any): void;
on(event: 'renewed', callback: OktaTokenRenewedEventHandler, context?: any): void;
/**
* Unsubscribe from token manager events. If no callback is provided, removes all
* listeners from the event.
*
* @param {OktaTokenEventType} event Event to unsubscribe from
* @param {Function} callback Optional callback that was used to subscribe to the event
*/
off(event: OktaTokenEventType, callback?: (...args: Array<any>) => void): void;
}
// Object representing all required and optional Okta client options.
export interface OktaOptions {
// Custom URL to perform the OIDC flow. Defaults to the issuer plus "/v1/authorize".
authorizeUrl?: string;
// Client ID pre-registered with Okta for the OIDC authentication flow.
clientId: string;
// Custom HTTP request implementation.
httpRequestClient?: OktaHttpRequestClient;
// ID token signatures are validated by default when token.getWithoutPrompt,
// token.getWithPopup, token.getWithRedirect, and token.verify are called. To disable ID
// token signature validation for these methods, set this value to true.
ignoreSignature?: boolean;
// Custom issuer to perform the flow (defaults to the base URL parameter if not provided).
// If you are using this SDK to implement an OIDC flow, the only required configuration
// option is issuer.
issuer?: string;
// The URL that is redirected to when using token.getWithRedirect.
// This must be pre-registered as part of client registration.
// If no redirectUri is provided, defaults to the current origin.
redirectUri?: string;
// This configuration option can be included only when instantiating Okta Auth JS.
tokenManager?: {
// Manually control token renewal.
autoRenew?: boolean;
// Prevent cookies from being stored on an HTTP connection.
secure?: boolean;
// Specify the type of storage for tokens.
storage?: OktaTokenStorageType;
};
// If you’re using this SDK only for communicating with the Authentication API, you instead
// need to set the URL for your Okta Domain.
url?: string;
// Specify a custom user info URL. Defaults to the issuer plus "/v1/userinfo".
userinfoUrl?: string;
}
// Main Okta client class.
export class OktaAuth {
// Token handler
public readonly token: OktaTokenHandler;
// Token manager
public readonly tokenManager: OktaTokenManager;
/**
* Class constructor
*
* @param {OktaOptions} options Client options
*/
public constructor(options: OktaOptions);
}
export default OktaAuth;
}
@codeaid
Copy link
Author

codeaid commented May 15, 2019

Usage

import OktaClient, { OktaOptions, OktaToken } from '@okta/okta-auth-js';

const client = new OktaClient({ ... });

@thehme
Copy link

thehme commented Nov 6, 2019

@codeaid did you mean do say import OktaAuth from '@okta/okta-auth-js';? I added these type definitions to a file I have in /Typings/@okta/okta-auth-js/index.d.ts

I have a constructor in my code like this:

    constructor() {
        this.oktaAuth = new OktaAuth({
            url: process.env.OKTA_URL as string
        });
    }

and a method that tries to use the verify method like this:

        const oktaToken: OktaToken = {
            accessToken: recoveryToken
        }
        const transaction = await this.oktaAuth.token.verify(oktaToken);

I get this error:

Thrown:
TypeError: okta_auth_js_1.default is not a constructor

It seems related to the type definitions, am using them incorrectly?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment