<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Rohit Chanda  on Medium]]></title>
        <description><![CDATA[Stories by Rohit Chanda  on Medium]]></description>
        <link>https://medium.com/@rohit.chanda.93?source=rss-26121da0de8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*vbLTEqiMxIeHliXa</url>
            <title>Stories by Rohit Chanda  on Medium</title>
            <link>https://medium.com/@rohit.chanda.93?source=rss-26121da0de8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 27 Nov 2026 17:10:28 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rohit.chanda.93/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Cognito Authentication in Node.js with AWS-SDK and Typescript]]></title>
            <link>https://medium.com/@rohit.chanda.93/cognito-authentication-in-node-js-with-aws-sdk-and-typescript-dcf031d54e8f?source=rss-26121da0de8------2</link>
            <guid isPermaLink="false">https://medium.com/p/dcf031d54e8f</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[cognito-authentication]]></category>
            <dc:creator><![CDATA[Rohit Chanda ]]></dc:creator>
            <pubDate>Thu, 02 Feb 2023 19:30:01 GMT</pubDate>
            <atom:updated>2023-02-03T17:45:47.360Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, I will show how you create UserPool in Cognito as well as how to <strong>create a user in UserPool</strong>, <strong>user login</strong>, <strong>access token validation</strong>, <strong>create groups, and add user in group </strong>in Cognito UserPool. <br><strong>GitHub link</strong> — <a href="https://github.com/RohitChanda/Cognito_with_Node">https://github.com/RohitChanda/Cognito_with_Node</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BOvPEzFFKJlvLXAAVwbiCA.jpeg" /></figure><p>With <strong>Amazon Cognito,</strong> you can add user sign-up and sign-in features and control access to your web and mobile applications. Amazon Cognito supports various compliance regulations and integrates with frontend and backend development resources.</p><p>Developers can use Cognito Identity <strong>to add sign-up and sign-in to their apps and to enable their users to securely access their app’s resources</strong>. Cognito also enables developers to sync data across devices, platforms, and applications.</p><p>A U<strong>ser pool</strong> is a user directory in Amazon Cognito. With a user pool, your users can sign in to your web or mobile app through Amazon Cognito.</p><p>User pool provides:</p><ul><li>Sign-up and sign-in services.</li><li>A built-in, customizable web UI to sign in users.</li><li>Social sign-in with Facebook, Google, Login with Amazon, and Sign in with Apple, as well as sign-in with SAML identity providers from your user pool.</li><li>User directory management and user profiles.</li><li>Security features such as multi-factor authentication (MFA), checks for compromised credentials, account takeover protection, and phone and email verification.</li><li>Customized workflows and user migration through AWS Lambda triggers.</li></ul><h4><strong>Create Cognito User Pool</strong></h4><ol><li>Open the AWS Official site and sign in to your console.</li></ol><p>2. After Signing in to your console, search Cognito and click it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*svM5Tmq02warbwUiM8rF2g.png" /></figure><p>3. Click to manage User Pools.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*cQi9YlWc7raLWcGnrirzWQ.png" /></figure><p>4. Click<strong> Create user pool</strong> button</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*M6Vfi2p08lBqgNZ-ZTFuzg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*l_2UmP7uuUonndwz2N7uVQ.png" /></figure><p>5. Write down the pool name and create it by clicking the <strong>Step through settings</strong> button, or you can choose default settings by clicking the <strong>Review defaults</strong> button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*l_2UmP7uuUonndwz2N7uVQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/763/1*hSeZCv4Tyn_UkTHbTGYzEA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*GUTKQzKI9OToBlM3LRgJMQ.png" /></figure><p>Also, you can add custom attributes in Cognito.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*Anl0afekRuI-YinjS-mVRA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zw67FcCGQNZfLm1jlebYAQ.png" /></figure><p>Create App Client. Remember one thing uncheck the <strong>Generate client secret</strong> option.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_gMAkk22dcL6p4Kb_LBlGw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j8mYwe9HgiOKwHvg-ltdjw.png" /></figure><h4>Create a user in Cognito UserPool</h4><ol><li>First set up AWS-SDK in your backend repository.</li></ol><pre>import AWS from &#39;aws-sdk&#39;<br>import dotenv from &#39;dotenv&#39;<br>dotenv.config()<br><br>AWS.config.update({<br>    region: process.env.AWS_REGION,<br>    accessKeyId: process.env.ACCESS_KEY_ID,<br>    secretAccessKey: process.env.SECRET_ACCESS_KEY<br>})<br><br>export default AWS</pre><p>2. set up Cognito</p><pre>import AWS from &quot;../config/aws-sdk&quot;<br>import * as dotenv from &quot;dotenv&quot;<br>import { CognitoSignupPayload, AddUserINGroupPayload } from &quot;../interface/auth&quot;<br>import axios from &quot;axios&quot;<br>import JWT from &#39;jsonwebtoken&#39;<br>import jwkToPem from &#39;jwk-to-pem&#39;<br>dotenv.config()<br><br>const poolData:{UserPoolId:string, ClientId:string, PoolRegion:string } = {<br>    UserPoolId : process.env.AWS_COGNITO_USER_POOL_ID as string,<br>    ClientId   : process.env.AWS_COGNITO_CLIENT_ID as string,<br>    PoolRegion : process.env.AWS_REGION as string<br>}<br><br>const cognito = new AWS.CognitoIdentityServiceProvider({region: poolData.PoolRegion})</pre><p>3. <strong>User SignUp function</strong></p><pre>export function SignUp(body:CognitoSignupPayload){<br>    const { email ,firstName, lastName, designation} = body<br>    return new Promise((resolve, reject)=&gt;{<br>        cognito.adminCreateUser({<br>            UserPoolId: poolData.UserPoolId,<br>            Username: email,<br>            DesiredDeliveryMediums: [&#39;EMAIL&#39;],<br>            //MessageAction: &#39;SUPPRESS&#39;, //stop sending the invitation<br>            //MessageAction: &#39;RESET&#39;,  // resend the invitation message to a user that already exists <br>            TemporaryPassword: &quot;temp#1234&quot;, // If you don&#39;t specify a value, Amazon Cognito generates one for you.<br>            UserAttributes: [<br>                {<br>                    Name  : &#39;email&#39;,<br>                    Value : email<br>                },<br>                {<br>                    Name  : &#39;given_name&#39;,<br>                    Value : firstName<br>                },<br>                {<br>                    Name  : &#39;family_name&#39;,<br>                    Value : lastName<br>                },<br>                {<br>                    Name  : &#39;custom:designation&#39;, // custome attribute<br>                    Value : designation<br>                },<br>            ]<br>        },function(err,response){<br>            if(err){<br>                reject(new Error(err.message))<br>            }else{<br>                resolve(response.User)<br>            }<br>        })<br>    })<br>}</pre><p>in controller function</p><pre>import { Request, Response} from &#39;express&#39;<br>import { CognitoSignupPayload} from &#39;../interface/auth&#39;<br>import {SignUp } from &#39;../cognito/cognito&#39;<br><br>export async function addUserInCognito(req:Request,res:Response) {<br>    try {<br>        const { email, first_name, last_name, designation } = req.body<br>        const payload: CognitoSignupPayload = {<br>            email       : email, <br>            firstName   : first_name, <br>            lastName    : last_name, <br>            designation : designation<br>        }<br>        const result = await SignUp(payload)<br>        res.status(200).json({<br>            response: result,<br>            message: &quot;User added in cognito&quot;<br>        })<br>    } catch (error) {<br>        console.log(error);<br>        res.status(500).json({<br>            message: &quot;something went wrong!&quot;<br>        });<br>    }<br>}</pre><p>4. User login</p><pre>export function UserLogin(payload:{email:string,password:string}){<br>    const { email, password } = payload<br>    return new Promise((resolve, reject)=&gt;{<br>        cognito.adminInitiateAuth({<br>            AuthFlow: &#39;ADMIN_NO_SRP_AUTH&#39;,<br>            ClientId: poolData.ClientId,<br>            UserPoolId: poolData.UserPoolId,<br>            AuthParameters: {<br>                USERNAME: email,<br>                PASSWORD: password<br>            }<br>        },function(err,response){<br>            if(err){<br>               reject(err)<br>               return<br>            }<br>            <br>            resolve(response)<br>            <br>        })<br>    })<br>}</pre><p>in controller</p><pre>export async function userLogin(req:Request,res:Response) {<br>    try {<br>        const { email, password } = req.body<br>        const payload = {<br>            email:email,<br>            password:password<br>        }<br>        const result:any = await UserLogin(payload)<br>        if( result.ChallengeName == &#39;NEW_PASSWORD_REQUIRED&#39; ) {<br>            res.status(200).json({<br>                ChallengeName:result.ChallengeName,<br>                session: result.Session,<br>                message: &quot;SET NEW PASSWORD&quot;<br>            })<br>        }<br>        res.status(200).json({<br>            response: result,<br>            message: &quot;User logged in successfully&quot;<br>        })<br>    } catch (error:any) {<br>        res.status(500).json({<br>            message: error.message<br>        });<br>    }<br>}</pre><p><strong>If a user logged in for the first time then the response object will be like</strong></p><pre>{<br>    &quot;ChallengeName&quot;: &quot;NEW_PASSWORD_REQUIRED&quot;,<br>    &quot;session&quot;: &quot;string&quot;,<br>    &quot;message&quot;: &quot;SET NEW PASSWORD&quot;<br>}</pre><p>It means now the user has to set a new password. for this functionality, we have to use the <strong>adminRespondToAuthChallenge</strong> method from Cognito.</p><pre>export async function newPasswordRequired(payload:{email:string, newPassword:string, session:string}){<br>    const { email, newPassword, session } = payload<br>    return new Promise((resolve, reject)=&gt;{<br>        cognito.adminRespondToAuthChallenge({<br>            ChallengeName: &#39;NEW_PASSWORD_REQUIRED&#39;,<br>            ClientId: poolData.ClientId,<br>            UserPoolId: poolData.UserPoolId,<br>            ChallengeResponses: {<br>              USERNAME: email,<br>              NEW_PASSWORD: newPassword,<br>            },<br>            Session: session<br>          },function(err,response){<br>            if(err){<br>                reject(err)<br>            }else{<br>                resolve(response)<br>            }<br>        })<br>    })<br>}</pre><p>response object</p><pre>  &quot;response&quot;: {<br>        &quot;ChallengeParameters&quot;: {},<br>        &quot;AuthenticationResult&quot;: {<br>            &quot;AccessToken&quot;: &quot;string&quot;,<br>            &quot;ExpiresIn&quot;: number<br>            &quot;TokenType&quot;: &quot;string&quot;<br>            &quot;RefreshToken&quot;: &quot;string&quot;,<br>            &quot;IdToken&quot;: &quot;string&quot;,<br>        }<br>    },</pre><p>next time, when the user tries to log in, Cognito API will return a response object like this</p><pre>&quot;response&quot;: {<br>        &quot;ChallengeParameters&quot;: {},<br>        &quot;AuthenticationResult&quot;: {<br>            &quot;AccessToken&quot;: &quot;string&quot;<br>            &quot;TokenType&quot;: &quot;Bearer&quot;,<br>            &quot;RefreshToken&quot;: &quot;string&quot;<br>            &quot;IdToken&quot;: &quot;string&quot; <br>        }<br>    },</pre><p>5. Validate access token</p><pre>import AWS from &quot;../config/aws-sdk&quot;<br>import * as dotenv from &quot;dotenv&quot;<br>import axios from &quot;axios&quot;<br>import JWT from &#39;jsonwebtoken&#39;<br>import jwkToPem from &#39;jwk-to-pem&#39;<br>dotenv.config()<br>export  function validateAccessToken(token:string) {<br>    return new Promise((resolve, reject) =&gt; {<br>        axios.get(`https://cognito-idp.${poolData.PoolRegion}.amazonaws.com/${poolData.UserPoolId}/.well-known/jwks.json`, {headers: {&#39;Content-Type&#39;: &#39;application/json&#39;}})<br>        .then((response)=&gt;{<br>            const body = response.data;<br>            const pem = jwkToPem(body.keys[1])<br>        <br>            JWT.verify(token, pem, function(err:any, payload:any) {<br>                if(err) {<br>                    reject(new Error(&#39;Invalid token&#39;))<br>                } else {<br>                    resolve(payload)<br>                }<br>            })<br>        })<br>        .catch((err)=&gt;{<br>            console.log(err);<br>            reject(err)<br>        })<br>    })<br>}</pre><p>6. Create Group in Cognito</p><pre>export function createGroup(groupName:string){<br>    return new Promise((resolve, reject)=&gt;{<br>        cognito.createGroup({<br>            GroupName: groupName,<br>            UserPoolId: poolData.UserPoolId<br>        },function(err,response){<br>            if(err){<br>                reject(err)<br>            }else{<br>                resolve(response)<br>            }<br>        })<br>    })<br>}</pre><p>7. Add user to Group</p><pre>export function addUserIntoGroup( payload:AddUserINGroupPayload ){<br>    const {groupName, userName} = payload<br>    return new Promise((resolve, reject)=&gt;{<br>        cognito.adminAddUserToGroup({<br>            GroupName: groupName,<br>            Username: userName,<br>            UserPoolId: poolData.UserPoolId<br>        },function(err,response){<br>            if(err){<br>                reject(err)<br>            }else{<br>                resolve(response)<br>            }<br>        })<br>    })<br>}</pre><p>For more info about Cognito API, you can check <a href="https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_Operations.html"><strong>AWS Cognito Documentation</strong></a><strong>.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dcf031d54e8f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>