Skip to content

jill64/cognito-serverless

Folders and files

NameName
Last commit message
Last commit date

Latest commit

ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 

Repository files navigation

cognito-serverless

npm-version npm-license npm-download-month npm-min-size local.yml remote.yml

๐Ÿ”‘ AWS Cognito Hosted UI OAuth on Serverless

Installation

npm i cognito-serverless

Usage

Add code in your middleware or route to authenticate user.

import { Auth } from 'cognito-server'

const cognito = new Auth(
  {
    COGNITO_DOMAIN: 'auth.example.com',
    COGNITO_CLIENT_ID: 'client-id',
    COGNITO_CLIENT_SECRET: 'client-secret',
    // State is a random string to prevent CSRF attacks (optional)
    COGNITO_STATE: 'random-string'
  },
  /*
   * The scopes of the access request.
   * @optional
   * @default ['openid', 'profile', 'email']
   */
  scopes: ['openid', 'profile', 'email']

  /*
   * After successful authentication, the user will be redirected to this URL.
   * @optional
   * @default url.origin
   */
  redirect_uri: 'https://example.com/callback'
)

/* UserInfo | URL */
const result = await cognito.auth({
  url: new URL('https://example.com'),
  cookies: {
    get: (key) => {
      /** get cookie */
    }
    set: (key, value, options) => {
      /** set cookie */
    }
  },
  // Override class config (optional)
  redirect_uri: 'https://example.com/callback'
})

if (typeof result === 'string') {
  /* Please redirect to `result` (Cognito Hosted UI) */
}

else {
  /* User is authenticated */
}

License

MIT