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',
})

- getToken

Function to get token information based on code / refresh_token

It accepts JSON object as a parameter with following keys

KeyDescriptionRequired
grant_typeSupports authorization_code & refresh_token grant types. Default is authorization_codefalse
code_verifierCode verifier to verify against the code_challenge sent in authorize request. Required if authorization_code flow is used.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

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

// 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)',
})

- 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

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
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 usertrue
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

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

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

Response

KeyDescription
messageSuccess / Error message from server
should_show_email_otp_screenBoolean value for frontend application to show otp input for email based login screen
should_show_mobile_otp_screenBoolean value for frontend application to show otp input for mobile based login screen
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
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`,
})

- 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
given_namefirst name of user
family_namelast name of user
signup_methodsmethods using which user have signed up, eg: google,github
email_verifieddetermine if email is verified or not
pictureprofile picture URL
rolesuser roles
created_attimestamp at which the user entry was created
updated_attimestamp at which the user entry was updated

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
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 newPassword and confirmNewPassword will be required.false
newPasswordNew password that user wants to set. In this scenario old_password and confirmNewPassword will be requiredfalse
confirmNewPasswordValue same as the new password to make sure it matches the password entered by user. In this scenario old_password and newPassword will be requiredfalse

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 changedtrue

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 in step 1.true

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`,
})

- 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 supports optional argument for role based login

Sample Usage

await authRef.oauthLogin('google')

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

- 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

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_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

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 as the second argument to validate roles 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
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
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
const { data, errors } = await authRef.getSession(null, 'admin')

// from NodeJS / if HTTP cookie is not used
const { data, errors } = await authRef.getSession(
{
Authorization: `Bearer some_token`,
},
'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

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

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 what the subject can access — ideal for filtering a list page down to what the user may see. With both relation and object_type set it answers "which object_types can I relation?"; either or both filters may be omitted, so an empty data object returns every permission the subject holds. Subject resolution follows the same rules as checkPermissions.

It accepts 2 JSON objects as its parameters.

  1. data - Optional relation / object type filters
  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). Omit to enumerate every relation of the active modelfalse
object_typeObject type to enumerate (e.g. document). Omit to enumerate every type of the active modelfalse
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"]
permissionsThe (object, relation) detail behind objects — relevant when no relation filter was supplied
truncatedtrue when the result was capped (1000 entries) and more permissions exist

Sample Usage

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

// No filters: everything the caller holds, with per-relation detail
const all = await authRef.listPermissions({}, { Authorization: `Bearer ${token}` });
// all.data?.permissions => [{ object: 'document:1', relation: 'can_view' }, ...]
// all.data?.truncated => false

- 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

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

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`,
})