Big News: Socket raises $60M Series C at a $1B valuation to secure software supply chains for AI-driven development.Announcement
Sign In

cognito-token-observer

Package Overview
Dependencies
Maintainers
1
Versions
14
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

cognito-token-observer

Monitor and refresh AWS Cognito tokens for the current session

latest
Source
npmnpm
Version
2.3.2
Version published
Maintainers
1
Created
Source

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

Keywords

aws

FAQs

Package last updated on 06 Dec 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