Unable to sign-in (SecretHash does not match for the client)

0

While creating an User pool in cognito, i created a App Client with Client Secret however now while hitting the signin api in postman I am getting an error "SecretHash does not match for the client: hjfuivhioewrjnmcpwoei(dummy)"

However, i have checked my code in every possible scnerio, the client secret, client id, username everything is passed correctly.

Below is my API function: const AWS = require("aws-sdk"); const dotenv = require("dotenv"); const jwt = require("jsonwebtoken"); const crypto = require('crypto');

dotenv.config();

const AWS_COGNITO_KEY = process.env.ACCESS_KEY_ID; const AWS_COGNITO_SECRET = process.env.SECRET_ACCESS_KEY; const COGNITO_REGION = process.env.COGNITO_REGION; const USER_POOL_ID = process.env.USER_POOL_ID; const CLIENT_ID = process.env.CLIENT_ID; const CLIENT_SECRET= process.env.CLIENT_SECRET;

AWS.config.update({ accessKeyId: AWS_COGNITO_KEY, secretAccessKey: AWS_COGNITO_SECRET, region: COGNITO_REGION, });

function generateSecretHash(CLIENT_ID, CLIENT_SECRET, username) { const hmac = crypto.createHmac("sha256", CLIENT_SECRET); hmac.update(username + CLIENT_ID); return hmac.digest("hex");

}

module.exports.signIn = (req, res) => { const { username, password } = req.body;

const secretHash = generateSecretHash(CLIENT_ID, CLIENT_SECRET, username); console.log("clientid------------------------->",CLIENT_ID) console.log("Client secret----------->",CLIENT_SECRET) console.log("Username----->", username) console.log('secretHash:', secretHash); const params = { AuthFlow: "USER_PASSWORD_AUTH", ClientId: CLIENT_ID, AuthParameters: { USERNAME: username, PASSWORD: password, SECRET_HASH: secretHash }, }; console.log(params) console.log(CLIENT_ID)

cognito.initiateAuth(params, (err, data) => { if (err) { return res.status(409).json({ error: err.message }); } else { const authResult = data.AuthenticationResult; if (authResult) { res.status(200).json({ message: "User sign-in successful", accessToken: authResult.AccessToken, idToken: authResult.IdToken, refreshToken: authResult.RefreshToken, }); } else { res.status(409).json({ error: "Authentication result missing" }); } } }); };

Dev
asked 7 months ago641 views
1 Answer
0
Accepted Answer

Hi, did you encode the secret hash to Base 64 as stated in this documentation?

The following implementation works for me.

const crypto = require("crypto");

function getSecretHash(username, clientId, clientSecret) {
  return crypto
    .createHmac("sha256", clientSecret)
    .update(`${username}${clientId}`)
    .digest("base64");
}
profile picture
HS
answered 7 months ago
profile pictureAWS
EXPERT
reviewed 7 months ago
  • Thankyou so much HS, it worked.

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.

Guidelines for Answering Questions