๐ AWS Cognito Hosted UI OAuth on Serverless
npm i cognito-serverless
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 */
}