Search code examples
node.jsreactjsamazon-web-servicesamazon-cognitoaws-amplify

How to verify accessToken in node/express using aws-amplify?


I am using AWS amplify for user authentication on my front-end React app. My React app directly communicates with amplify without any backend(node server) interaction.

I have a REST API written in node/express. I want to secure that API using amplify.

Currently, I am planning to pass the access token from my react app to my node server. But I am unable to find a way through which I can verify this token on the backend using amplify.

Does aws-amplify package provide any function in which I can pass the access token to verify it?

Something like Auth.verifyToken(<access_token>)


Solution

  • Unfortunately, there is no such method available in official aws-amplify SDK. After doing a lot of research I had to write my own middleware for that. This is not that difficult as it may seem but the only difficult part is to gather the right information from the huge AWS documentation.

    I 've written this middleware to achieve the same, Hope this helps

    import axios from 'axios'
    import awsconfig from '../../aws-exports';
    
    const COGNITO_URL = `https://cognito-idp.${awsconfig.aws_project_region}.amazonaws.com/`;
    
    const authentication = async (req, res, next) => {
        try {
            const accessToken = req.headers.authorization.split(" ")[1];
    
            const { data } = await axios.post(
                COGNITO_URL,
                {
                    AccessToken: accessToken
                },
                {
                    headers: {
                        "Content-Type": "application/x-amz-json-1.1",
                        "X-Amz-Target": "AWSCognitoIdentityProviderService.GetUser"
                    }
                }
            )
    
            req.user = data;
            next();
        } catch (error) {
            return res.status(401).json({
                message: 'Auth failed'
            });
        }
    };
    
    export default authentication;
    

    This middleware takes the authorization header and verifies the incoming accessToken using AWS Cognito REST API.

    In order to get accessToken on your front-end you can do something like this:

    const { accessToken: { jwtToken } } = await Auth.currentSession();
    

    This jwtToken is your accessToken you can send this in your Authorization header and then verify this in the backend using the middleware I've written.