Skip to main content
Version: 2.x (Latest)

Functions

@authorizerdev/authorizer-js SDK comes with bunch of utility functions, that you can use to perform various operations without worrying about the API details.


Table of Contents

These functions can be invoked using the Authorizer instance:

const authRef = new Authorizer({
authorizerURL: 'YOUR_AUTHORIZER_INSTANCE_URL',
redirectURL: window.location.origin,
clientID: 'YOUR_CLIENT_ID',
})

- authorize

Function to auto login from browser using the builtin UI of authorizer. It checks for session, if available returns the token information, else redirects to login page.

  • It supports PKCE flow. This will help user to perform authentication and authorization in safe memory and prevent from CSRF attack. It also enables perform authorization with safety on mobile applications (Tried and tested with Expo AuthSession)

  • It supports Implicit Flow

It accepts JSON object as a parameter with following keys

KeyDescriptionRequired
response_typeWhat type of response you want. It supports code & token as response types. Default value is tokenfalse
response_modeResponse is required in which format. Supports 2 forms query (returns redirect url with response in query string) and web_message (returns html page with data embedded in JS). Default its value is queryfalse
use_refresh_tokenWhether to include refresh token in response or notfalse

If session exists following keys are returned in data object.

Response

KeyDescription
access_tokenaccessToken that frontend application can use for further authorized requests
expires_intimestamp when the current token is going to expire, so that frontend can request for new access token
id_tokenJWT token holding the user information
refresh_tokenWhen scope includes offline_access, Long living token is returned which can be used to get new access tokens. This is rotated with each request

Sample Usage

const { data, errors } = await authRef.authorize({
response_type: 'code',
response_mode: 'query',
})

- browserLogin

Function to silently check for an existing browser session (via getSession) and return its tokens. If no session exists it falls back to redirecting the browser to the hosted login app ({authorizerURL}/app), the same fallback authorize uses when the iframe check fails. Browser-only; it takes no parameters.

Sample Usage

const { data, errors } = await authRef.browserLogin()
if (data?.access_token) {
// an existing session was found
}

- getToken

Function to exchange credentials for tokens at /oauth/token. This call always goes over REST regardless of the client's configured protocol (see Protocols & Admin API).

Supports 4 grant types: authorization_code (default), refresh_token, client_credentials (RFC 6749 §4.4), and token exchange (RFC 8693, urn:ietf:params:oauth:grant-type:token-exchange).

Server-side only: client_credentials and token exchange are machine/service flows for trusted server-side code. Never ship client_secret, client_assertion, or subject/actor tokens in a browser bundle.

It accepts JSON object as a parameter with following keys

KeyDescriptionRequired
grant_typeauthorization_code, refresh_token, client_credentials, or urn:ietf:params:oauth:grant-type:token-exchange. Default is authorization_codefalse
code_verifierCode verifier to verify against the code_challenge sent in authorize request. Required if authorization_code flow is used (handled automatically by the SDK).false
codeCode returned form authorize request is sent to make sure it is follow up of same requestfalse
refresh_tokenRefresh token used to get the new access token. Required in case of refresh_token grant typefalse
client_secretService-account secret. Used with client_credentials. Server-side only.false
scopeSpace-delimited OAuth2 scope. Omit for client_credentials to get the service account's full allowed scope set.false
client_assertionRFC 7523 JWT-bearer client credential (secretless workload identity: K8s SA tokens, SPIFFE JWT-SVIDs, cloud OIDC tokens).false
client_assertion_typeType of client_assertion. Use the exported CLIENT_ASSERTION_TYPE_JWT_BEARER constant.false
subject_tokenThe authority being exercised (the user's token). Required for token exchange.false
subject_token_typeType of subject_token. Use the exported TOKEN_TYPE_ACCESS_TOKEN / TOKEN_TYPE_JWT constants.false
actor_tokenThe acting agent's token; its presence selects the delegation profile. Used for token exchange.false
actor_token_typeType of actor_token.false
resourceRFC 8707 resource indicator the issued token should be audience-bound to.false

If session exists following keys are returned in the data object.

Response

KeyDescription
access_tokenaccessToken that frontend application can use for further authorized requests
expires_intimestamp when the current token is going to expire, so that frontend can request for new access token
id_tokenJWT token holding the user information. Only issued on user grants (authorization_code / refresh_token) — absent for client_credentials and token exchange
refresh_tokenWhen scope includes offline_access, Long living token is returned which can be used to get new access tokens. This is rotated with each request
token_typeToken type, e.g. Bearer
scopeGranted scope. Returned by client_credentials and token exchange grants
issued_token_typeThe token type URN issued. Returned by the token exchange grant (RFC 8693 §2.2)

Sample Usage

// for web apps
const { data, errors } = await authRef.getToken({
response_type: 'code',
response_mode: 'query',
})

// for mobile applications / desktop apps
const { data, errors } = await authRef.getToken({
grant_type: 'refresh_token',
refresh_token:
'your refresh_token from login (should store in memmory such as store, variables)',
})

// server-side machine-to-machine (client_credentials) — never in a browser bundle
const { data, errors } = await authRef.getToken({
grant_type: 'client_credentials',
client_secret: 'YOUR_CLIENT_SECRET',
})

- signup

Function to sign-up user using email and password.

It accepts JSON object as a parameter with the following keys

KeyDescriptionRequired
emailEmail address of usertrue
passwordPassword that user wants to settrue
confirm_passwordValue same as password to make sure that its user and not robottrue
given_nameFirst name of the userfalse
family_nameLast name of the userfalse
pictureProfile picture URLfalse
rolesArray of string with valid roles. Defaults to [user] if not configuredfalse
middle_namemiddle name of userfalse
nicknamenick name of userfalse
gendergender of userfalse
birthdatebirthdate of userfalse
phone_numberphone number of userfalse
redirect_uriURL where user should be redirected after loginfalse
scopeList of openID scopes. If not present default scopes ['openid', 'email', 'profile', 'offline_access'] is usedfalse
stateOpaque state string round-tripped through the flow. Auto-generated by the SDK if omittedfalse
app_dataArbitrary JSON object of application-specific data stored on the userfalse

Following is the response for the signup in the data object

Response

KeyDescription
messageSuccess / Error message from server
access_tokenaccessToken that frontend application can use for further authorized requests
expires_intimestamp when the current token is going to expire, so that frontend can request for new access token
id_tokenJWT token holding the user information
refresh_tokenWhen scope includes offline_access, Long living token is returned which can be used to get new access tokens. This is rotated with each request
userUser object with its profile keys mentioned above. This is only returned if DISABLE_EMAIL_NOTIFICATION is set to true in environment variables
should_show_email_otp_screenIs set to true if email based multi factor authentication is enabled
should_show_mobile_otp_screenIs set to true if mobiled based multi factor authentication is enabled
should_show_totp_screenIs set to true if totp based multi factor authentication is enabled
should_offer_webauthn_mfa_verifyIs set to true if the user should be offered to verify with an existing passkey as their second factor
should_offer_webauthn_mfa_setupIs set to true if the user should be offered to enroll a passkey as their second factor
should_offer_email_otp_mfa_setupIs set to true if the user should be offered email-OTP MFA enrollment
should_offer_sms_otp_mfa_setupIs set to true if the user should be offered SMS-OTP MFA enrollment
authenticator_scanner_imageIf totp registration is pending it sends base64 encoded image string that can be rendered by totp app scanners like Google Authentication
authenticator_secretIf totp registration is pending, then this secret can be used for registration instead of image on authenticator apps
authenticator_recovery_codesIf totp registration is pending, then recovery codes are sent using which totp can be accessed again

Sample Usage

const { data, errors } = await authRef.signup({
email: 'foo@bar.com',
password: 'test',
confirm_password: 'test',
scope: ['offline_access'], // for refresh token
})

- login

Function to login user using email and password.

It accepts JSON object as a parameter with the following keys

KeyDescriptionRequired
emailEmail address of userfalse
phone_numberPhone number of user (alternative to email)false
passwordPassword of usertrue
rolesRoles of user that he/she wants to login with. It accepts array of string. Defaults to [user] role if not configuredfalse
scopeList of openID scopes. If not present default scopes ['openid', 'email', 'profile'] is usedfalse
stateOpaque state string round-tripped through the flowfalse

Either email or phone_number is required.

Following is the response for login in the data object

Response

KeyDescription
messageError / Success message from server
access_tokenaccessToken that frontend application can use for further authorized requests
expires_intimestamp when the current token is going to expire, so that frontend can request for new access token
id_tokenJWT token holding the user information
refresh_tokenWhen scope includes offline_access, Long living token is returned which can be used to get new access tokens. This is rotated with each request
userUser object with all the basic profile information
should_show_email_otp_screenIs set to true if email based multi factor authentication is enabled
should_show_mobile_otp_screenIs set to true if mobiled based multi factor authentication is enabled
should_show_totp_screenIs set to true if totp based multi factor authentication is enabled
should_offer_webauthn_mfa_verifyIs set to true if the user should be offered to verify with an existing passkey as their second factor
should_offer_webauthn_mfa_setupIs set to true if the user should be offered to enroll a passkey as their second factor
should_offer_email_otp_mfa_setupIs set to true if the user should be offered email-OTP MFA enrollment
should_offer_sms_otp_mfa_setupIs set to true if the user should be offered SMS-OTP MFA enrollment
authenticator_scanner_imageIf totp registration is pending it sends base64 encoded image string that can be rendered by totp app scanners like Google Authentication
authenticator_secretIf totp registration is pending, then this secret can be used for registration instead of image on authenticator apps
authenticator_recovery_codesIf totp registration is pending, then recovery codes are sent using which totp can be accessed again

Sample Usage

const { data, errors } = await authRef.login({
email: 'foo@bar.com',
password: 'test',
})

- verifyEmail

Function to verify email address of user when they signup.

It accepts JSON object as a parameter with following keys

KeyDescriptionRequired
tokenToken sent for verifying usertrue
stateOpaque state string round-tripped through the flowfalse

This mutation returns AuthResponse type with the following keys in the data object

Response

KeyDescription
messageSuccess / Error message from server
access_tokenaccessToken that frontend application can use for further authorized requests
expires_intimestamp when the current token is going to expire, so that frontend can request for new access token
id_tokenJWT token holding the user information
refresh_tokenWhen scope includes offline_access, Long living token is returned which can be used to get new access tokens. This is rotated with each request
userUser object with its profile keys mentioned above.
should_show_email_otp_screenIs set to true if email based multi factor authentication is enabled
should_show_mobile_otp_screenIs set to true if mobiled based multi factor authentication is enabled
should_show_totp_screenIs set to true if totp based multi factor authentication is enabled
should_offer_webauthn_mfa_verifyIs set to true if the user should be offered to verify with an existing passkey as their second factor
should_offer_webauthn_mfa_setupIs set to true if the user should be offered to enroll a passkey as their second factor
should_offer_email_otp_mfa_setupIs set to true if the user should be offered email-OTP MFA enrollment
should_offer_sms_otp_mfa_setupIs set to true if the user should be offered SMS-OTP MFA enrollment
authenticator_scanner_imageIf totp registration is pending it sends base64 encoded image string that can be rendered by totp app scanners like Google Authentication
authenticator_secretIf totp registration is pending, then this secret can be used for registration instead of image on authenticator apps
authenticator_recovery_codesIf totp registration is pending, then recovery codes are sent using which totp can be accessed again

Sample Usage

const { data, errors } = await authRef.verifyEmail({
token: `some_token`,
})

- resendVerifyEmail

Function to resend the verification email to a user who signed up but hasn't verified their email yet.

It accepts JSON object as a parameter with following keys

KeyDescriptionRequired
emailEmail address to resend the verification totrue
identifierVerification identifier (basic_signup)true
stateOpaque state string round-tripped through the flowfalse

It returns the following keys in response data object

Response

KeyDescription
messageSuccess / Error message from server

Sample Usage

const { data, errors } = await authRef.resendVerifyEmail({
email: 'foo@bar.com',
identifier: 'basic_signup',
})

- getProfile

Function to get profile of user. This function makes an authorized request, hence if it is used from the browser the HTTP cookie is sent if user has logged in else you need to pass headers object.

It accepts the optional JSON object as parameter, you can pass the HTTP Headers there.

KeyDescriptionRequired
AuthorizationAuthorization header passed to the server. It needs Bearer access_token as its valuetrue

It returns the following keys in response data object

Response

KeyDescription
iduser unique identifier
emailemail address of user
email_verifieddetermine if email is verified or not
given_namefirst name of user
family_namelast name of user
middle_namemiddle name of user
nicknamenick name of user
preferred_usernamepreferred username of user
gendergender of user
birthdatebirthdate of user
phone_numberphone number of user
phone_number_verifieddetermine if phone number is verified or not
pictureprofile picture URL
signup_methodsmethods using which user have signed up, eg: google,github
rolesuser roles
created_attimestamp at which the user entry was created
updated_attimestamp at which the user entry was updated
revoked_timestamptimestamp at which access was revoked, if any
is_multi_factor_auth_enabledwhether the user has multi-factor authentication enabled
has_skipped_mfa_setup_attimestamp at which the user skipped MFA setup, if any
mfa_locked_attimestamp at which MFA was locked for the user, if any
enrolled_mfa_methodslist of MFA methods the user has enrolled (e.g. totp, webauthn)
app_dataarbitrary JSON object of application-specific data on the user

Sample Usage

// from browser if HTTP cookie is present
const { data, errors } = await authRef.getProfile()

// from NodeJS / if HTTP cookie is not used
const { data, errors } = await authRef.getProfile({
Authorization: `Bearer ${token}`,
})

- updateProfile

Function to update profile of user. This function makes an authorized request, hence if it is used from the browser the HTTP cookie is sent if user has logged in else you need to pass headers object.

It accepts 2 JSON object as its parameters.

  1. data - User data that needs to be updated
  2. headers - To pass Authorization header

Here are the keys that data object accepts

KeyDescriptionRequired
given_nameNew first name of the userfalse
family_nameNew last name of the userfalse
middle_nameNew middle name of the userfalse
nicknameNew nickname of the userfalse
genderNew gender of the userfalse
birthdateNew birthdate of the userfalse
phone_numberNew phone number of the userfalse
pictureNew profile picture URL of the userfalse
emailNew email of th user. This will logout the user and send the new verification mail to user if DISABLE_EMAIL_NOTIFICATION is set to falsefalse
old_passwordIn case if user wants to change password they need to specify the older password here. In this scenario new_password and confirm_new_password will be required.false
new_passwordNew password that user wants to set. In this scenario old_password and confirm_new_password will be requiredfalse
confirm_new_passwordValue same as the new password to make sure it matches the password entered by user. In this scenario old_password and new_password will be requiredfalse
is_multi_factor_auth_enabledToggle whether MFA is enabled for the userfalse
app_dataArbitrary JSON object of application-specific data stored on the userfalse

Note: earlier versions of this doc referred to these password fields as newPassword / confirmNewPassword (camelCase) — the SDK and server both expect the snake_case new_password / confirm_new_password shown above.

Here is sample of headers object

KeyDescriptionRequired
AuthorizationAuthorization header passed to the server. It needs Bearer access_token as its valuetrue

It returns the following keys in response data object

Response

KeyDescription
messageSuccess / Error message from server

Sample Usage

const { data, errors } = await authRef.updateProfile(
{
given_name: `bob`,
},
{
Authorization: `Bearer some_token`,
},
)

- forgotPassword

Function that can be used in case if user has forgotten their password. Forgot password is 2 step process.

Step 1: Send email to registered user Step 2: Reset password.

This function is Step 1 process.

It accepts JSON object as parameter with the following keys

Note: You will need a SMTP server with an email address and password configured as authorizer environment using which system can send emails.

KeyDescriptionRequired
emailEmail for which password needs to be changedfalse
phone_numberPhone number for which password needs to be changed (alternative to email)false
redirect_uriURL where user should be redirected after resetting password. Defaults to the client's configured redirectURLfalse
stateOpaque state string round-tripped through the flow. Auto-generated by the SDK if omittedfalse

Either email or phone_number is required.

It returns the following keys in response data object

Response

KeyDescription
messageSuccess / Error message from server
should_show_mobile_otp_screenShow OTP screen if mobile login is used

Sample Usage

const { data, errors } = await authRef.forgotPassword({
email: 'foo@bar.com',
})

- resetPassword

Function to reset password. This is the step 2 of forgot password process.

It accepts JSON object as a parameter with following keys

KeyDescriptionRequired
tokenToken sent to the user by email in step 1 (forgotPassword)false
otpOTP sent to the user by SMS in step 1, if mobile-based reset is usedfalse
phone_numberPhone number the OTP was sent to. Required if otp is usedfalse
passwordNew password to settrue
confirm_passwordValue same as password to make sure it matchestrue

Either token (email flow) or otp + phone_number (mobile flow) is required, along with password and confirm_password.

It returns the following keys in response data object

Response

KeyDescription
messageSuccess / Error message from server

Sample Usage

const { data, errors } = await authRef.resetPassword({
token: `some_token`,
password: 'newPass123',
confirm_password: 'newPass123',
})

- oauthLogin

Function to login using OAuth Providers. This is mainly used in browser as user is redirect to respective oauth platform.

Note only enabled oauth providers can be used here. To get the information about enabled oauth provider you can use getMetaData function

It accepts the following positional arguments:

ArgumentDescriptionRequired
oauthProviderOne of apple, github, google, facebook, linkedin, twitter, microsoft, twitch, roblox, discordtrue
rolesArray of role strings to log in withfalse
redirect_uriURL to redirect to after the OAuth flow completes. Defaults to the client's configured redirectURLfalse
stateOpaque state string round-tripped through the flow. Auto-generated by the SDK if omittedfalse

Sample Usage

await authRef.oauthLogin('google')

// login with specific role(s)
await authRef.oauthLogin('google', ['admin'])

// override the redirect_uri
await authRef.oauthLogin('github', undefined, 'https://your-app.example.com/callback')

- magicLinkLogin

Function to perform password less login.

Note: You will need a SMTP server with an email address and password configured as authorizer environment using which system can send emails.

KeyDescriptionRequired
emailEmail using which user needs to logintrue
rolesList of valid valid roles using which user needs to loginfalse
scopeList of openID scopes. If not present default scopes ['openid', 'email', 'profile'] is usedfalse
redirect_uriURL where user should be redirected after loginfalse
stateOpaque state string round-tripped through the flow. Auto-generated by the SDK if omittedfalse

It returns the following keys in response data object

Response

KeyDescription
messageSuccess / Error message from server

Sample Usage

const { data, errors } = await authRef.magicLinkLogin({
email: 'foo@bar.com',
})

- getMetaData

Function to get meta information about your authorizer instance. eg, version, configurations, etc

It returns the following keys in response data object

Response

KeyDescription
versionAuthorizer version that is currently deployed
client_idIdentifier of your instance
is_google_login_enabledIt gives information if google login is configured or not
is_github_login_enabledIt gives information if github login is configured or not
is_facebook_login_enabledIt gives information if facebook login is configured or not
is_linkedin_login_enabledIt gives information if linkedin login is configured or not
is_apple_login_enabledIt gives information if apple login is configured or not
is_discord_login_enabledIt gives information if discord login is configured or not
is_twitter_login_enabledIt gives information if twitter login is configured or not
is_microsoft_login_enabledIt gives information if microsoft login is configured or not
is_twitch_login_enabledIt gives information if twitch login is configured or not
is_roblox_login_enabledIt gives information if roblox login is configured or not
is_email_verification_enabledIt gives information if email verification is enabled or not
is_basic_authentication_enabledIt gives information, if basic auth is enabled or not
is_magic_link_login_enabledIt gives information if password less login is enabled or not
is_sign_up_enabledIt gives information if new sign ups are allowed
is_strong_password_enabledIt gives information if strong password policy is enforced
is_multi_factor_auth_enabledIt gives information if multi-factor authentication is enabled
is_mobile_basic_authentication_enabledIt gives information if mobile (phone number) basic auth is enabled
is_phone_verification_enabledIt gives information if phone verification is enabled
is_totp_mfa_enabledIt gives information if TOTP is available as an MFA method
is_email_otp_mfa_enabledIt gives information if email OTP is available as an MFA method
is_sms_otp_mfa_enabledIt gives information if SMS OTP is available as an MFA method
is_webauthn_enabledIt gives information if WebAuthn/passkeys are available as an MFA method
is_mfa_enforcedIt gives information if MFA is enforced for all users
is_org_discovery_enabledIt gives information if home-realm/org discovery is enabled

Sample Usage

const { data, errors } = await authRef.getMetaData()

- getSession

Function to get session information. This function makes an authorized request, hence if it is used from the browser the HTTP cookie is sent if user has logged in else you need to pass headers object.

It accepts the optional JSON object as parameter, you can pass the HTTP Headers there. Optionally you can also pass a SessionQueryRequest object ({ roles?: string[], scope?: string[] }) as the second argument to validate roles / scope against the session.

KeyDescriptionRequired
AuthorizationAuthorization header passed to the server. It needs Bearer some_token as its valuefalse

It returns the following keys in response data object

Response

KeyDescription
messageError / Success message from server
access_tokenaccessToken that frontend application can use for further authorized requests
expires_intimestamp when the current token is going to expire, so that frontend can request for new access token
id_tokenJWT token holding the user information
refresh_tokenWhen scope includes offline_access, Long living token is returned which can be used to get new access tokens. This is rotated with each request
userUser object with all the basic profile information
should_show_email_otp_screenIs set to true if email based multi factor authentication is enabled
should_show_mobile_otp_screenIs set to true if mobiled based multi factor authentication is enabled
should_show_totp_screenIs set to true if totp based multi factor authentication is enabled
should_offer_webauthn_mfa_verifyIs set to true if the user should be offered to verify with an existing passkey as their second factor
should_offer_webauthn_mfa_setupIs set to true if the user should be offered to enroll a passkey as their second factor
should_offer_email_otp_mfa_setupIs set to true if the user should be offered email-OTP MFA enrollment
should_offer_sms_otp_mfa_setupIs set to true if the user should be offered SMS-OTP MFA enrollment
authenticator_scanner_imageIf totp registration is pending it sends base64 encoded image string that can be rendered by totp app scanners like Google Authentication
authenticator_secretIf totp registration is pending, then this secret can be used for registration instead of image on authenticator apps
authenticator_recovery_codesIf totp registration is pending, then recovery codes are sent using which totp can be accessed again

Sample Usage

// from browser with HTTP Cookie
const { data, errors } = await authRef.getSession()

// role validation with http cookie — the second argument is a SessionQueryRequest object, not a bare string
const { data, errors } = await authRef.getSession(null, { roles: ['admin'] })

// from NodeJS / if HTTP cookie is not used
const { data, errors } = await authRef.getSession(
{
Authorization: `Bearer some_token`,
},
{ roles: ['admin'] },
)

- revokeToken

Function to revoke refresh token. It accepts json object as its parameter with following keys

JSON Object

KeyDescriptionRequired
refresh_tokenRefresh token to be revokedtrue

It returns the following keys in response data object

Response

KeyDescription
messageSuccess message

Sample Usage

const { data, errors } = await authRef.revokeToken({
refresh_token: 'foo',
})

- logout

Function to logout user. This function makes an authorized request, hence if it is used from the browser the HTTP cookie is sent if user has logged in else you need to pass headers object.

It accepts the optional JSON object as parameter, you can pass the HTTP Headers there.

KeyDescriptionRequired
AuthorizationAuthorization header passed to the server. It needs Bearer some_token as its valuefalse

It returns the following keys in response data object

Response

KeyDescription
messageSuccess / Error message from server

Sample Usage

// from browser with HTTP Cookie
const { data, errors } = await authRef.logout()

// from NodeJS / if HTTP cookie is not used
const { data, errors } = await authRef.logout({
Authorization: `Bearer some_token`,
})

- validateJWTToken

Function to validate jwt tokens.

It expects the JSON object as parameter with following parameters

KeyDescriptionRequired
token_typeType of token that needs to be validated. It can be one of access_token, refresh_token or id_tokentrue
tokenJwt token stringtrue
rolesArray of roles to validate jwt token forfalse

It returns the following keys in response data object

Response

KeyDescription
is_validBoolean indicating if given token was valid or not
claimsDecoded JWT claims of the validated token

Sample Usage

const { data, errors } = await authRef.validateJWTToken({
token_type: `access_token`,
token: `some jwt token string`,
})

- validateSession

Function to validate cookie / browser session.

It expects the JSON object as parameter with following parameters

KeyDescriptionRequired
cookiebrowser session cookie value. If not present it will need coookie present in header as https cookiefalse
rolesArray of roles to validate jwt token forfalse

It returns the following keys in response data object

Response

KeyDescription
is_validBoolean indicating if given token was valid or not
userUser object with all the basic profile information

Sample Usage

const { data, errors } = await authRef.validateSession({
cookie: ``,
})

- checkPermissions

Function to evaluate one or more fine-grained authorization (FGA) permission checks against the embedded OpenFGA engine, in a single call. results come back in the same order as checks and echo each pair.

This function makes an authorized request, hence from the browser the HTTP cookie is sent automatically if the user has logged in. From NodeJS pass the Authorization header as the optional second argument.

The subject defaults to the caller's token. An optional user ("type:id", or a bare id treated as user:<id>) is honored only for super-admins or when it equals the caller's own token subject; anything else is rejected by the server — never silently ignored.

For complete worked scenarios — Express middleware, list filtering, and tuple lifecycle — see Authorization recipes.

It accepts 2 JSON objects as its parameters.

  1. data - Permission checks to evaluate
  2. headers - To pass Authorization header (optional in the browser)

Here are the keys that the data object accepts

KeyDescriptionRequired
checksArray of checks, each { relation, object, contextual_tuples? }. contextual_tuples (array of { user, relation, object }) are evaluated for that check only and never persistedtrue
userSubject override ("type:id", or a bare id treated as user:<id>). Honored only for super-admins or self; defaults to the callerfalse

It returns the following keys in response data object

Response

KeyDescription
resultsOne result per supplied check, in order, each { relation, object, allowed } echoing the checked pair

Sample Usage

const { data, errors } = await authRef.checkPermissions(
{
checks: [
{ relation: 'can_view', object: 'document:1' },
{ relation: 'can_edit', object: 'document:1' },
],
},
{ Authorization: `Bearer ${token}` }, // omit in the browser to use the cookie
);

if (data?.results?.[0]?.allowed) {
// caller may view document:1
}

// "What-if" check with contextual tuples (evaluated for this call only):
const { data: whatIf } = await authRef.checkPermissions(
{
checks: [
{
relation: 'can_view',
object: 'document:1',
contextual_tuples: [
{ user: 'user:1b9d…', relation: 'viewer', object: 'document:1' },
],
},
],
},
{ Authorization: `Bearer ${token}` },
);

- listPermissions

Function to list which objects of a given type the subject holds a relation on — ideal for filtering a list page down to what the user may see ("which object_types can I relation?"). Subject resolution follows the same rules as checkPermissions.

It accepts 2 JSON objects as its parameters.

  1. data - Relation / object type to enumerate
  2. headers - To pass Authorization header (optional in the browser)

Here are the keys that the data object accepts

KeyDescriptionRequired
relationRelation to list for (e.g. can_view)true
object_typeObject type to enumerate (e.g. document)true
userSubject override ("type:id", or a bare id treated as user:<id>). Honored only for super-admins or selffalse

It returns the following keys in response data object

Response

KeyDescription
objectsDistinct fully-qualified ids of the objects the subject holds the relation on, e.g. ["document:1"]

Sample Usage

const { data, errors } = await authRef.listPermissions(
{ relation: 'can_view', object_type: 'document' },
{ Authorization: `Bearer ${token}` },
);
// data?.objects => ['document:1', 'document:7', ...]

- verifyOtp

Function to verify OTP sent to the user when they login.

It accepts JSON object as a parameter with following keys

KeyDescriptionRequired
emailEmail address of userfalse
phone_numberPhone number of userfalse
otpOTP (One Time Password) sent to user email addresstrue
is_totpSet to true when verifying/enrolling a TOTP code instead of an email/SMS OTPfalse
stateOpaque state string round-tripped through the flowfalse

Either email or phone_number is required

It returns the following keys in response data object

Response

KeyDescription
messageError / Success message from server
access_tokenaccessToken that frontend application can use for further authorized requests
expires_intimestamp when the current token is going to expire, so that frontend can request for new access token
id_tokenJWT token holding the user information
refresh_tokenWhen scope includes offline_access, Long living token is returned which can be used to get new access tokens. This is rotated with each request
userUser object with all the basic profile information
should_show_email_otp_screenIs set to true if email based multi factor authentication is enabled
should_show_mobile_otp_screenIs set to true if mobiled based multi factor authentication is enabled
should_show_totp_screenIs set to true if totp based multi factor authentication is enabled
should_offer_webauthn_mfa_verifyIs set to true if the user should be offered to verify with an existing passkey as their second factor
should_offer_webauthn_mfa_setupIs set to true if the user should be offered to enroll a passkey as their second factor
should_offer_email_otp_mfa_setupIs set to true if the user should be offered email-OTP MFA enrollment
should_offer_sms_otp_mfa_setupIs set to true if the user should be offered SMS-OTP MFA enrollment
authenticator_scanner_imageIf totp registration is pending it sends base64 encoded image string that can be rendered by totp app scanners like Google Authentication
authenticator_secretIf totp registration is pending, then this secret can be used for registration instead of image on authenticator apps
authenticator_recovery_codesIf totp registration is pending, then recovery codes are sent using which totp can be accessed again

Sample Usage

const { data, errors } = await authRef.verifyOtp({
email: 'foo@bar.com',
otp: 'AB123C',
})

- resendOtp

Function to resend OTP to the user.

It accepts JSON object as a parameter with following keys

KeyDescriptionRequired
emailEmail address of userfalse
phone_numberPhone number of userfalse
stateOpaque state string round-tripped through the flowfalse

Either email or phone_number is required

It returns the following keys in response data object

Response

KeyDescription
messageError / Success message from server

Sample Usage

const { data, errors } = await authRef.resendOtp({
email: 'foo@bar.com',
})

- deactivateAccount

Function to deactivate user account. This function makes an authorized request, hence if it is used from the browser the HTTP cookie is sent if user has logged in else you need to pass headers object.

It accepts 1 JSON object as its parameters.

  1. headers - To pass Authorization header

Here is sample of headers object

KeyDescriptionRequired
AuthorizationAuthorization header passed to the server. It needs Bearer access_token as its valuetrue

It returns the following keys in response data object

Response

KeyDescription
messageSuccess / Error message from server

Sample Usage

const { data, errors } = await authRef.deactivateAccount({
Authorization: `Bearer some_token`,
})

- skipMfaSetup

Function to skip a first-time MFA enrollment offer mid login (the should_offer_* gate) when the user has a completed-login state to fall back to. Returns the full AuthResponse/token shape (same as login/signup), since skipping completes the gate.

It accepts JSON object as a parameter with following keys

KeyDescriptionRequired
emailEmail address of userfalse
phone_numberPhone number of userfalse
stateOpaque state string round-tripped through the flowfalse

Sample Usage

const { data, errors } = await authRef.skipMfaSetup({
email: 'foo@bar.com',
})

- lockMfa

Function to lock multi-factor authentication for a user by email or phone number.

It accepts JSON object as a parameter with following keys

KeyDescriptionRequired
emailEmail address of userfalse
phone_numberPhone number of userfalse

It returns the following keys in response data object

Response

KeyDescription
messageSuccess / Error message from server

Sample Usage

const { data, errors } = await authRef.lockMfa({
email: 'foo@bar.com',
})

- emailOtpMfaSetup

Function to enroll email-OTP as a multi-factor authentication method — sends an OTP to the user's email to be verified with verifyOtp.

It accepts an optional JSON object as a parameter with following keys

KeyDescriptionRequired
emailEmail address of userfalse
phone_numberPhone number of userfalse

It returns the following keys in response data object

Response

KeyDescription
messageSuccess / Error message from server

Sample Usage

const { data, errors } = await authRef.emailOtpMfaSetup()

- smsOtpMfaSetup

Function to enroll SMS-OTP as a multi-factor authentication method — sends an OTP to the user's phone number to be verified with verifyOtp.

It accepts an optional JSON object as a parameter with following keys

KeyDescriptionRequired
emailEmail address of userfalse
phone_numberPhone number of userfalse

It returns the following keys in response data object

Response

KeyDescription
messageSuccess / Error message from server

Sample Usage

const { data, errors } = await authRef.smsOtpMfaSetup()

- totpMfaSetup

Function to generate a fresh TOTP secret/QR code/recovery-codes for the caller to enroll as an MFA method — the TOTP twin of emailOtpMfaSetup/smsOtpMfaSetup. Unlike those, nothing is sent anywhere: the enrollment payload comes back directly in the response, so the caller scans/enters it, then completes enrollment via verifyOtp({ is_totp: true, otp: '...' }).

It accepts an optional JSON object as a parameter with following keys

KeyDescriptionRequired
emailEmail address of userfalse
phone_numberPhone number of userfalse

It returns the following keys in response data object

Response

KeyDescription
messageSuccess / Error message from server
should_show_totp_screenBoolean indicating the TOTP enrollment screen should be shown
authenticator_scanner_imageBase64 encoded QR image that can be scanned by authenticator apps like Google Authenticator
authenticator_secretSecret that can be entered manually instead of scanning the QR image
authenticator_recovery_codesRecovery codes that can be used to regain TOTP access if the device is lost

Sample Usage

const { data, errors } = await authRef.totpMfaSetup()
// render data.authenticator_scanner_image, then:
await authRef.verifyOtp({ is_totp: true, otp: '123456' })

WebAuthn / Passkeys

The following methods drive WebAuthn passkey registration and login. The low-level webauthn* methods talk to the server only (GraphQL or REST; the REST routes landed in server 2.4.0) and expect/return the opaque JSON strings the WebAuthn spec defines; the higher-level registerPasskey/loginWithPasskey* helpers additionally drive the browser's navigator.credentials ceremony for you and are what most apps should use directly.

- webauthnRegistrationOptions

Function to fetch passkey registration ceremony options from the server.

ArgumentDescriptionRequired
emailEmail of the user to register a passkey for (MFA-session-cookie path only)false
phoneNumberPhone number of the user (MFA-session-cookie path only)false

Response

KeyDescription
optionsOpaque JSON string (PublicKeyCredentialCreationOptionsJSON) to pass to the browser's WebAuthn API

Sample Usage

const { data, errors } = await authRef.webauthnRegistrationOptions()

- webauthnRegistrationVerify

Function to verify a completed passkey registration ceremony.

KeyDescriptionRequired
credentialOpaque JSON string (RegistrationResponseJSON) returned by the browser's WebAuthn ceremonytrue
nameFriendly name to store for this credentialfalse
emailOnly used on the MFA-session-cookie path (registering a passkey mid login-time MFA offer)false
phone_numberOnly used on the MFA-session-cookie pathfalse
stateOpaque state string round-tripped through the flowfalse

Returns the full AuthResponse/token shape: on the MFA-session-cookie path this also completes the gate, so access_token and friends are populated exactly like verifyOtp/skipMfaSetup. On the ordinary authenticated-settings-page path access_token is always null — the caller already has one.

Sample Usage

const { data, errors } = await authRef.webauthnRegistrationVerify({
credential: credentialJSON,
name: 'My laptop',
})

- webauthnLoginOptions

Function to fetch passkey login (assertion) ceremony options from the server.

ArgumentDescriptionRequired
emailScopes the ceremony to one account's own passkeys. Omit for usernameless (discoverable-credential) loginfalse

Response

KeyDescription
optionsOpaque JSON string (PublicKeyCredentialRequestOptionsJSON) to pass to the browser's WebAuthn API

Sample Usage

const { data, errors } = await authRef.webauthnLoginOptions()

- webauthnLoginVerify

Function to verify a completed passkey login (assertion) ceremony.

KeyDescriptionRequired
credentialOpaque JSON string (AuthenticationResponseJSON) returned by the browser's WebAuthn ceremonytrue
stateOpaque state string round-tripped through the flowfalse

Returns the full AuthResponse/token shape, same as login.

Sample Usage

const { data, errors } = await authRef.webauthnLoginVerify({
credential: credentialJSON,
})

- webauthnCredentials

Function to list the caller's enrolled passkeys. Takes no parameters.

Response (array of)

KeyDescription
idCredential id
nameFriendly name for the credential
transportsTransports the authenticator advertised (e.g. internal, usb)
created_atTimestamp the credential was registered
updated_atTimestamp the credential was last updated
last_used_atTimestamp the credential was last used to log in

Sample Usage

const { data, errors } = await authRef.webauthnCredentials()

- webauthnDeleteCredential

Function to delete one of the caller's enrolled passkeys by id.

ArgumentDescriptionRequired
idId of the credential to deletetrue

Response

KeyDescription
messageSuccess / Error message from server

Sample Usage

const { data, errors } = await authRef.webauthnDeleteCredential('credential-id')

- registerPasskey

High-level helper that drives a full passkey registration ceremony end to end: fetch options from the server (webauthnRegistrationOptions), prompt the platform authenticator via the browser's WebAuthn API, then verify (webauthnRegistrationVerify). Normally requires an authenticated session (a passkey is added to the caller's own account) — pass mfaSetup to instead authenticate via the MFA session cookie mid a login-time MFA offer.

ArgumentDescriptionRequired
nameFriendly name to store for this credentialfalse
mfaSetup{ email?, phoneNumber?, state? } — only used to authenticate via the MFA-session-cookie pathfalse

Sample Usage

const { data, errors } = await authRef.registerPasskey('My laptop')

- loginWithPasskey

High-level helper that drives a full passkey login ceremony end to end. Omit email for a usernameless (discoverable-credential) login; pass it to scope the ceremony to one account's own passkeys (the MFA-alternative flow).

ArgumentDescriptionRequired
emailScopes the ceremony to one account's own passkeysfalse
opts{ mediation?: CredentialMediationRequirement, signal?: AbortSignal } — pass mediation: 'conditional' for passkey autofill (prefer loginWithPasskeyAutofill instead)false

Sample Usage

const { data, errors } = await authRef.loginWithPasskey()

- loginWithPasskeyAutofill

Starts a "passkey autofill" (conditional mediation) login: the browser offers discoverable passkeys inline in a username field's autofill dropdown rather than a modal. The returned promise resolves only when the user actually picks a passkey (or rejects when aborted/cancelled) — fire it on mount and ignore abort errors. Requires an <input autocomplete="username webauthn"> on the page. Takes no parameters; only one autofill ceremony runs at a time (a new call, or an explicit modal loginWithPasskey(), aborts the previous one).

Sample Usage

useEffect(() => {
authRef.loginWithPasskeyAutofill().then(({ data }) => {
if (data?.access_token) {
// logged in via autofilled passkey
}
})
return () => authRef.cancelPasskeyAutofill()
}, [])

- cancelPasskeyAutofill

Aborts a pending loginWithPasskeyAutofill ceremony, e.g. on component unmount. Safe to call when none is in flight. Synchronous, returns nothing.

Sample Usage

authRef.cancelPasskeyAutofill()

- isWebauthnSupported

Standalone function (not a method on the Authorizer instance) that reports whether the current browser supports the WebAuthn PublicKeyCredential JSON APIs this SDK's passkey methods rely on.

Sample Usage

import { isWebauthnSupported } from '@authorizerdev/authorizer-js'

if (isWebauthnSupported()) {
// show a "Sign in with a passkey" button
}

- parseMfaRedirectParams

Standalone function (not a method on the Authorizer instance) that parses the mfa_required / mfa_methods / mfa_gate query params the server's OAuth callback appends to the redirect URL instead of the normal state/code params when a first-time MFA offer or verification is needed before a token can be issued. Useful on the page your OAuth redirectURL points to.

ArgumentDescriptionRequired
urlThe full redirect URL (e.g. window.location.href), or a URL instance. Must be absolute — a bare path/search string throwstrue

Returns null if the URL has no mfa_required=1 param, otherwise an object:

KeyDescription
mfaRequiredAlways true when non-null
mfaMethodsRaw method-name strings from the server (e.g. totp, webauthn, email_otp, sms_otp)
mfaGate'verify' — the user has a completed second factor to challenge; or 'offer' — first-time enrollment with a Skip option. Defaults to 'offer' when absent

Sample Usage

import { parseMfaRedirectParams } from '@authorizerdev/authorizer-js'

const params = parseMfaRedirectParams(window.location.href)
if (params?.mfaRequired) {
// route to the MFA setup/verify screen for params.mfaMethods
}