Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

teko-oauth2

Package Overview
Dependencies
Maintainers
1
Versions
62
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

teko-oauth2

Teko Identity OAuth 2 Javascript Library for Web App Client

  • 1.7.1
  • npm
  • Socket score

Version published
Maintainers
1
Created
Source

Teko Identity OAuth2 Javascript Library for Web App

A Javascript Library for integrate Teko Identity OAuth2 to Web Application.

Note: If your want to integrate with your Backend API or Server Side Rendering Web App, this library is not for you.

Getting started

import TekoID from 'teko-oauth2'

const App = props => {
  if (TekoID.user.isLoggedIn())
    return <HomePageView userInfo={TekoID.user.getUserInfo()} />
  return <LoginView />
}

const LoginView = props => (
  <p onClick={() => TekoID.user.login()}>
    Login with Teko
  </p>
)

Installation

# With yarn
yarn add teko-oauth2

# With npm
npm install teko-oauth2

Then you can initiate the client using TekoID:

import TekoID from 'teko-oauth2'

TekoID.init({
  clientId: 'your-client-id',
  redirectUri: 'your-redirect-uri',
  scopes: ['your', 'scopes'],
  oauthDomain: 'https://oauth.develop.tekoapis.net'
}).then(() => {
  // The initial phase is finish.
  // Now you can do your logic.
  const rootElement = document.getElementById('root')
  ReactDOM.render(<App />, rootElement)
})

which returns a promise and resolve after finish initiating.

For advance usage, please check examples folder.

NOTE: You can also include JS SDK teko-oauth2.min.js in your source code, then access the lib using window.TekoID.

Usage

async TekoID.init(configs)

configs keyTypeDefault valueRequired
clientIdstringY
oauthDomainstringhttps://oauth.teko.vn
redirectUristringprotocol//hostname:port
postLogoutRedirectUristringprotocol//hostname:port
scopes[string][]
silentbooleantrue
monitorSessionbooleanfalse
checkTokenRevokedbooleanfalse
  • clientId: The ID of your client which you registered in Identity Teko.
  • redirectUri: Your client will redirect to this uri with authorization code value after user successfully logged in. This value should match exact with one of the redirect_uris you registered in IAM App.
  • postLogoutRedirectUri: Your client will redirect to this uri after user successfully logged out. This value should match exact with one of the post_logout_redirect_uris you registered in IAM App.
  • scopes: The scopes of your client.
  • oauthDomain: The TekoID domain to use SDK.
  • silent: If the SDK auto renew access token silently when the current one is expired. Set false to turn off this feature (so user must re-login if access token is expired).
  • monitorSession: Set to true to able to listen to changes in user session.
  • checkTokenRevoked: Set to true to call oauthDomain/userinfo endpoint to ensure the current cached token is not revoked.

NOTE: For develop environment, please specific oauthDomain to https://oauth.develop.tekoapis.net

NOTE: For stage environment, please specific oauthDomain to https://oauth.stage.tekoapis.net

NOTE: TekoID.init() function is an async function.


TekoID.user

.isLoggedIn()

Return true if user is logged in, false if not.

.login(redirectUri = null, additionalParams = {})

Redirect to Teko Identity OAuth Login page to start login process.

After login success, Teko Identity OAuth Login will redirect back to optional parameter redirectUri.

By default, it will redirect to redirectUri param in TekoID.init function.

Call this function when user click to Login button in your application.

This value should match exact with one of the redirect_uris you registered in IAM App.

additionalParams helps you to add more parameters for Identity server to handle in Authorization Request, useful for adding such as locale.

async .loginSilent()

A promise return current user logged in OAuth server with latest info and new access token. Raise if there is not logged user in OAuth server.

.logout(redirectUri = null, additionalParams = {})

Clear current user's info and log user out.

After logout success, Teko Identity OAuth Login will redirect back to optional parameter redirectUri.

By default, it will redirect to postLogoutRedirectUri param in TekoID.init function.

Call this function when user click to Logout button in your application.

This value should match exact with one of the post_logout_redirect_uris you registered in IAM UI.

additionalParams helps you to add more parameters for Identity server to handle in Logout Request, useful for adding such as locale.

.loadUser()

Load current cache user in storage. Return undefined if there is not any user in cache storage.

Return value example:

{
  accessToken: 'random-string',
  expiresAt: 1595500000,
  expiresIn: 3600,
  idToken: 'jwt-string',
  profile: {
    sub: 'string',
    name: 'string',
    picture: 'url-string',
  },
  scopes: ['openid', 'profile'],
  sessionState: 'random-string',
  tokenType: 'Bearer'
}

NOTE: This function might return an user with expired accessToken.

.unloadUser()

Remove current cache user in storage.

.getAccessToken()

Get logged user's current access token.

Return a string which is current user's access token if user is logged. undefined if user is not logged.

NOTE: Since the access token can be renew silently after the current is expired (init with slient: true), be sure that you always use the current access token (not the old one).

import axios from 'axios'
import TekoID from 'teko-oauth2'

const { user } = TekoID

// Bad
const axiosInstance = axios.create({
  headers: { Authorization: `Bearer ${user.getAccessToken()}` }
})
axiosInstance.get('/api/resources') // The access token always same

// Good
axios.get('/api/resources', {
  headers: { Authorization: `Bearer ${user.getAccessToken()}` }
}) // Now the token is fetch each time a request is made

// Better
const axiosInstance = axios.create()
axiosInstance.interceptors.request.use(
  config => {
    config.headers.Authorization = `Bearer ${user.getAccessToken()}`
    return config
  },
  error => Promise.reject(error)
)
axiosInstance.get('/api/resources')

NOTE: You should treat access token as a random string, even when OAuth server return this token in some specific forms (like JWT).

.getUserInfo()

Get current user's general information.

Return object which includes current user's information. Return undefined if user is not logged or openid not in scopes.

  • With openid scope, id_token will return with fields: sub, name, picture, updated_at.

  • With addition profile scope, id_token will return with addition fields: email, phone_number, birthday, address.

Return value example (with openid, profile, read:permissions included in scopes):

{
  sub: 'user_unique_id',
  name: 'User Name',
  picture: 'https://domain.com/avatar_url.jpg',

  email: 'email@teko.vn',
  phone_number: '0123456789',
  birthday: '2000-12-31',
  address: 'Yume street',
}
async .getFullUserInfo(adminDomain = null)

Send HTTP request to get current user's full information.

Return object which includes current user's information. Return undefined if user is not logged or access token is expired. Return {message: null} current access token is invalid (revoked).

The response is as same as .getUserInfo() response, with addition read:permissions scope:

  • With addition read:permissions scope, response will return with addition fields: roles, permissions, meta_data.

Return value example (with openid, profile, read:permissions included in scopes):

{
  sub: 'user_unique_id',
  name: 'User Name',
  picture: 'https://domain.com/avatar_url.jpg',
  updated_at: '2019-12-31 00:00:00',

  email: 'email@teko.vn',
  phone_number: '0123456789',
  birthday: '2000-12-31',
  address: 'Yume street',

  roles: ['string'],
  permissions: ['string'],
  meta_data: { key: 'value' }
}

WARNING: Calling getFullUserInfo() without specific adminDomain may lead to incorrect data.

For Teko OAuth, the adminDomain is auto-detected from oauthDomain. For other OAuth (Digilife OAuth), please specific this parameter.

This parameter is needed because of the limitation in current OAuth server when refresh user's access control data. This may be changed in later version.

.getUserScopes()

Get logged user's scopes.

Return array of string which is current user's scopes if user is logged. undefined if user is not logged.

Return value example:

['openid', 'profile']

NOTE: This scopes may different with the scopes you defined when init. Because the scopes may be able to access by your app, but not for the current user (the user denied the app for access his/her data). If you want to use scopes in order to display correct UI, please use this scopes value.

.getAccessTokenExpiresAt()

Return timestamp when the access token expired. undefined if user is not logged.


TekoID.user.events

Register callbacks and execute them whenever certain events raise.

Current supported events:

  • userLoaded: raised when a user session has been established (or re-established). Not raised when user is loaded from cache storage.
  • userSessionChanged: raised when user's sign in status at OAuth Server has changed.
  • silentRenewError: raised when automatic silent renew has failed.
  • accessTokenExpiring: raised 5 minutes before the current access token expires.
  • accessTokenExpired: raised when current access token has expired.

You can register callbacks by add functions, or remove them if you no longer want to execute them.

Examples:

// Should only call after Teko.init has resolved
TekoID.user.events.addUserSessionChanged(() => {
  alert('User session changed. Force user to re-login.')
  TekoID.user.unloadUser()
  TekoID.user.login()
})

TekoID.user.events.addSilentRenewError(err => {
  console.err('Silent renew error. Details:', err)
})

Keywords

FAQs

Package last updated on 15 Mar 2022

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc