• authorizer-js
  • Functions

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.

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 res = 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.

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 res = await authRef.getToken({
  response_type: 'code',
  response_mode: 'query',
})

- signup

Function to sign-up user using email and password.

It accepts JSON object as a parameter with 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

Following is the response for signup function

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

Sample Usage

const res = await authRef.signup({
  email: 'foo@bar.com',
  password: 'test',
  confirm_password: 'test',
})

- login

Function to login user using email and password.

It accepts JSON object as a parameter with 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 function

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

Sample Usage

const res = 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 following keys

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.

Sample Usage

const res = 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

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 user = await authRef.getProfile()
 
// from NodeJS / if HTTP cookie is not used
const user = await authRef.getProfile({
  Authorization: `Bearer ${token}`,
})

- updateProfile

Function to update profile of user.

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

Response

KeyDescription
messageSuccess / Error message from server

Sample Usage

const res = 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 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

Response

KeyDescription
messageSuccess / Error message from server

Sample Usage

const res = 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

Response

KeyDescription
messageSuccess / Error message from server

Sample Usage

const res = 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

Response

KeyDescription
messageSuccess / Error message from server

Sample Usage

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

- getMetadata

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

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 res 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 validate the roles against the given token by passing the roles as second argument to function.

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

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

Sample Usage

// from browser with HTTP Cookie
const res = await authRef.getSession()
 
// role validation with http cookie
const res = await authRef.getSession(null, 'admin')
 
// from NodeJS / if HTTP cookie is not used
const res = 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

Response

KeyDescription
messageSuccess message

Sample Usage

const res = 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

Response

KeyDescription
messageSuccess / Error message from server

Sample Usage

// from browser with HTTP Cookie
const res = await authRef.logout()
 
// from NodeJS / if HTTP cookie is not used
const res = 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

Response

KeyDescription
is_validBoolean indicating if given token was valid or not

Sample Usage

const res = 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

Response

KeyDescription
is_validBoolean indicating if given token was valid or not

Sample Usage

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

- 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

Following is the response for verifyOtp function

Response

KeyDescription
messageError / Success 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 all the basic profile information

Sample Usage

const res = 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

Following is the response for resendOtp function

Response

KeyDescription
messageError / Success message from server

Sample Usage

const res = await authRef.resendOtp({
  email: 'foo@bar.com',
})
Last updated on July 23, 2023