AWS Cognito与Node.js签名
#node #cognito #signin #autho

让我们在今天的节点项目中添加aws cognito符号。
我想您的项目已经添加了AWS Cognito注册您的项目。

如果没有,请查看我的善良文章:

此外,如果您对此。。

在路线中添加AWS Cognito登录

import controller from '../controllers/auth.controller';
import {
  validateSignupRequest,
  validateSignupConfirmRequest,
} from '../middleware';

export default (app) => {
  app.post('/api/auth/signup', validateSignupRequest, controller.signup);
  app.post(
    '/api/auth/email/verify',
    validateSignupConfirmRequest,
    controller.signupConfirm,
  );
  app.post('/api/auth/signin', validateSigninRequest, controller.signin); // add signin route
};

在Auth Controller中添加函数中的符号。

// User Signup
import CognitoIdentity from '../services/cognito';

const CognitoIdentityService = CognitoIdentity();

const signin = async (req, res) => {
  const { email, password } = req.body;
  const cognitoParams = {
    username: email,
    password,
  };

  try {
    const cognitoUser = await new Promise((resolve, reject) => {
      CognitoIdentityService.signin(cognitoParams, (err, user) => {
        if (err) {
          reject(err);
        } else {
          resolve(user);
        }
      });
    });

    // DB logic here
    // ...

    res.status(200).send({
      success: true,
      message: 'User logined successfully',
      user: cognitoUser,
    });
  } catch (error) {
    res.status(400).send({ success: false, message: error.message, error });
  }
};

export default {
  signup,
  signupConfirm,
  signin, // add
};

在服务中添加注册电子邮件确认。

然后,我们需要将AWS Cognito用户身份验证服务添加到服务文件夹。我将使用Amazon-Cognito-Identity-JS进行服务。
如果您不了解如何使用服务,请检查my git repository上的服务文件夹结构。

services/
  └──cognito/
        ├── index.js
        └── methods/
              ├── index.js
              ├── signup.js
              ├── signin.js // add
              └── signupConfirm.js

这是一个符号文件,请添加。

import {
  CognitoUserPool,
  CognitoUser,
  AuthenticationDetails,
} from 'amazon-cognito-identity-js';

/**
 * Signin
 * @param {*} poolData
 * @param {{username, password}} body
 * @param {*} callback
 */

const signin = (poolData, body, callback) => {
  const userPool = new CognitoUserPool(poolData);

  const { username, password } = body;

  const authenticationData = {
    Username: username,
    Password: password,
  };

  const authenticationDetails = new AuthenticationDetails(authenticationData);

  const userData = {
    Username: username,
    Pool: userPool,
  };

  const cognitoUser = new CognitoUser(userData);

  cognitoUser.authenticateUser(authenticationDetails, {
    onSuccess: (res) => {
      const data = {
        refreshToken: res.getRefreshToken().getToken(),
        accessToken: res.getAccessToken().getJwtToken(),
        accessTokenExpiresAt: res.getAccessToken().getExpiration(),
        idToken: res.getIdToken().getJwtToken(),
        idTokenExpiresAt: res.getAccessToken().getExpiration(),
      };
      callback(null, data);
    },
    onFailure: (err) => {
      callback(err);
    },
    mfaRequired: () => {
      const data = {
        nextStep: 'MFA_AUTH',
        loginSession: cognitoUser.Session,
      };
      callback(null, data);
    },
    totpRequired: () => {
      const data = {
        nextStep: 'SOFTWARE_TOKEN_MFA',
        loginSession: cognitoUser.Session,
      };
      callback(null, data);
    },
    newPasswordRequired: () => {
      const data = {
        nextStep: 'NEW_PASSWORD_REQUIRED',
        loginSession: cognitoUser.Session,
      };
      callback(null, data);
    },
  });
};

export default signin;

邮递员的结果

Cognito email verification

参考

https://github.com/itwebtiger/express-amazon-cognito/tree/congnito-signin
https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-social-idp.html#cognito-user-pools-social-idp-step-1