如何使用 aws-amplify 验证节点/express 中的 accessToken?

Wae*_*eez 9 amazon-web-services node.js reactjs amazon-cognito aws-amplify

我在前端 React 应用程序上使用 AWS amplify 进行用户身份验证。我的 React 应用程序直接与 amplify 通信,无需任何后端(节点服务器)交互。

我有一个用 node/express 编写的 REST API。我想使用放大来保护该 API。

目前,我计划将访问令牌从我的 React 应用程序传递到我的节点服务器。但是我无法找到一种方法来使用放大在后端验证此令牌。

aws-amplify 包是否提供任何可以传递访问令牌来验证它的功能?

就像是 Auth.verifyToken(<access_token>)

Zai*_*een 12

不幸的是,官方的 aws-amplify SDK 中没有这样的方法。在做了大量研究之后,我不得不为此编写自己的中间件。这并不像看起来那么困难,但唯一困难的部分是从庞大的 AWS 文档中收集正确的信息。

我已经编写了这个中间件来实现相同的目的,希望这会有所帮助

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;
Run Code Online (Sandbox Code Playgroud)

此中间件获取授权标头并使用 AWS Cognito REST API 验证传入的 accessToken。

为了在您的前端获取 accessToken,您可以执行以下操作:

const { accessToken: { jwtToken } } = await Auth.currentSession();
Run Code Online (Sandbox Code Playgroud)

jwtToken是您的 accessToken,您可以将其发送到您的Authorization标头中,然后使用我编写的中间件在后端进行验证。


Phi*_*nan 5

AWS 实际上已经对此进行了很好的记录。我编写了一个中间件,用于在我的express.js 服务器中验证 AWS Cognito 令牌。

本质上,当您在 Amazon 中创建用户池时,AWS 会创建一个 JSON Web Key (JWK)。JWT 包含可用于验证 JWT 签名的公钥。

Javascript 的高层次:

import jwt from "jsonwebtoken";

const authToken = getJwtFromHeader(request);

// please remember to verify the "iss" claim and "exp" claim!
validateAuthToken(authToken);

// convert a jwk to a PEM for use by OpenSSL or crypto
const jwk = getJwkFromAWS();
const pem = jwkToPem(jwk);

// verify the signature of the token using the public key from AWS
await jwt.verify(authToken, pem, {algorithms: ['RS256']}, (err, decoded) =>{
  console.log('decoded', decoded);
  // TODO -- verify claims from decoded token
}); 
Run Code Online (Sandbox Code Playgroud)

我的 GIST 完整的express.js实现: https://gist.github.com/fourgates/92dc769468497863168417c3524e24dd

AWS 资源:

https://github.com/awslabs/aws-support-tools/tree/master/Cognito/decode-verify-jwt https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user -pools-using-tokens-verifying-a-jwt.html

  • 重要提示:对于阅读本文的任何人,_请_记住验证“iss”声明和“exp”声明!如果您不检查“iss”声明,则拥有 AWS 账户的任何人都可以创建用户池并颁发将通过您的应用程序进行身份验证的 JWT。听起来很明显,但以防万一你忘记了! (2认同)