【问题标题】:node.js server-side validation of cognito credentials认知凭证的node.js服务器端验证
【发布时间】:2022-06-16 10:05:48
【问题描述】:

我正在为 aws cognito 编写一些服务器端登录代码,我想验证正在登录的用户是否存在于身份池中并获取分配给他们的属性。

对于电子邮件登录,我使用以下代码很好地工作 - 使用 aws-sdk:

let cognitoVerifyUser = null
            try {
                const cognitoIdProvider = new AWS.CognitoIdentityServiceProvider()
                cognitoVerifyUser = await cognitoIdProvider.adminGetUser({
                    UserPoolId: pool.userPoolId,
                    Username: username,
                }).promise()
            } catch (e) { 
                throwError(e, e.message)
            }

            if (!cognitoVerifyUser) {
                throwError(error.unauthorized, e)
            }

            const emailAttrib = cognitoVerifyUser.UserAttributes.find(a => a.Name == 'email')
            if (!cognitoVerifyUser.Enabled || cognitoVerifyUser.UserStatus != 'CONFIRMED' || username != cognitoVerifyUser.Username || email != emailAttrib.Value) {
                throwError(error.unauthorized, e)
            }

但我一直试图为联合用户做类似的事情(例如通过谷歌登录)。 有人可以帮帮我吗?

【问题讨论】:

    标签: javascript node.js aws-lambda amazon-cognito aws-sdk


    【解决方案1】:
    import generateResponse from "../../../Utils/generateResponse";
    import {
      CognitoUserPool,
      CognitoUser,
      AuthenticationDetails
    } from "amazon-cognito-identity-js";
    import { APIGatewayEvent } from "aws-lambda";
    
    type LoginType = {
      email: string;
      password: string;
    };
    
    export const handler = async (event: APIGatewayEvent) => {
      try {
        const body = JSON.parse(event.body as string) as LoginType;
    
        const userPool = new CognitoUserPool({
          UserPoolId: process.env.COGNITO_USERPOOLID as string,
          ClientId: process.env.COGNITO_CLIENTID as string
        });
    
        const user = new CognitoUser({ Username: body.email, Pool: userPool });
    
        const authenticationData = {
          Username: body.email,
          Password: body.password
        };
        const authenticationDetails = new AuthenticationDetails(authenticationData);
    
        return new Promise(resolve =>
          user.authenticateUser(authenticationDetails, {
            //@ts-ignore
            onSuccess: result => {
              resolve({ body: JSON.stringify(result) });
            },
            onFailure: err => {
              resolve({ body: JSON.stringify(err) });
            }
          })
        );
      } catch (err) {
        return generateResponse({
          statusCode: 400,
          body: JSON.stringify(err, Object.getOwnPropertyNames(err))
        });
      }
    };
    

    我有一个登录端点。试试看。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-09-26
      • 2011-08-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多