cognito-token-observer
TypeScript icon, indicating that this package has built-in type declarations

2.3.2 • Public • Published

cognito-token-observer

cognito-token-observer

NPM version npm-typescript License Build status Install size

About

Monitors date expiration of access and id tokens provided by Amazon Cognito. Refreshes when expired.

Use case

Authorize users with Amazon Cognito and use result token in 3rd party projects outside AWS.

Example

React app

projects:

Installation:

npm install cognito-token-observer

or

yarn add cognito-token-observer

Usage

Add CognitoAuthObserver to your component:

import React, { useEffect, useState } from 'react'
import ReactDOM from 'react-dom/client'
import { CognitoAuthObserver } from 'cognito-token-observer'

function App() {
  const [userData, setUserData] = useState([])

  const cognitoObserver = CognitoAuthObserver({ // init
    clientId: process.env.REACT_APP_COGNITO_CLIENT_ID,
    poolDomain: process.env.REACT_APP_COGNITO_POOL_DOMAIN,
    redirectUrl: process.env.REACT_APP_COGNITO_REDIRECT_URI,
    region: process.env.REACT_APP_COGNITO_REGION,
    userPoolId: process.env.REACT_APP_COGNITO_USER_POOL_ID,
  });

  cognitoObserver.onTokenUpdate(() => { // callback on token update
    setUserData(cognitoObserver.getUserData())
  }, 'onTokenUpdateKey')
  
  const getCodeFromBrowser = () => { 
    // get code after signin/up to aws cognito 
    // then pass to cognitoObserver
    const urlSearchParams = new URLSearchParams(window.location.search);
    const params = Object.fromEntries(urlSearchParams.entries());
    const code = params['code'];
  }

  const cognitoCode = getCodeFromBrowser()

  useEffect(() => {
    cognitoObserver.init(cognitoCode)
      .then(isAuthenticated => {
        console.log('Token updated:', isAuthenticated)
      })
  }, [])

  return (
    <div>
        {JSON.stringify(userData)}
    </div>
  )

}

Development

In the root package

npm run build
npm pack
# will create .tgz file cognito-token-observer-{x.x.x}.tgz

add path in example

cd example

Open package.json

change dependency from

"cognito-token-observer": "^x.x.x",

to the path

# in my case version 2.2.2.
"file:../cognito-token-observer-2.2.2.tgz"

API

  • init(code?: string) => Promise CognitoObserver.init: (code?: string | undefined) => Promise
  • isActive() => boolean
  • onTokenUpdate(callback, key) key need to be unique. Used because of reference from react etc
  • getAccessToken() => string | null
  • getIdToken() => string | null
  • getUserData() => userData:UserDataType
  • clearTokens() remove localStorage tokens

Readme

Keywords

Package Sidebar

Install

npm i cognito-token-observer

Weekly Downloads

58

Version

2.3.2

License

MIT

Unpacked Size

57.1 kB

Total Files

9

Last publish

Collaborators

  • romankurnovskii