【问题标题】:serverless authentication with JSON Web Tokens使用 JSON Web 令牌进行无服务器身份验证
【发布时间】:2018-07-30 22:01:48
【问题描述】:

我学习了基于 AWS Lambda、API 网关和 Dynamodb 的无服务器架构。 这是我的配置文件(serverless.yml):

...
functions:
  authorize:
    handler: auth/handler.verify
    description: verify client access token
    environment:
      TOKEN_SCRET: ${self:custom.tokenSecret}
  login:
    handler: user/handler.login
    description: return access token to client
    events:
      - http: GET /login
    environment:
      TOKEN_SECRET: ${self:custom.tokenSecret}
  getAllCustomers:
    handler: customer/handler.getCustomers
    description: retrieve all customers info from db
    events:
      - http:
          path: /customers
          method: get
          cors: true
          authorizer: authorize
    environment:
      CUSTOMERS_TABLE: ${self:custom.customerTable}
...

我为 API Gateway 设置了一个自定义授权方。我首先测试了所有 lambda 函数,一切正常。但是,当我测试 getAllCustomer 的 API 时,它没有返回正确的响应,而是返回

{
   "message": null 
}

应该是

{
  "Items": [
    {
      "id": "test",
      "userId": "test"
    }
  ],
  "Count": 1,
  "ScannedCount": 1
}

它应该通过授权lambda函数并传递给getAllCustomers,但是当我检查日志时,只有授权函数收到了请求。

这是我的授权功能:

const JWT = require('jsonwebtoken')

module.exports.verify = (event, context, callback) => {
const token = event.authorizationToken

  JWT.verify(token, process.env.TOKEN_SECRET, { algorithms: ['HS256'] }, (err, decoded) => {
    if (err) {
      return callback('Unauthorized')
    }

    const userId = decoded.userId
    callback(null, generatePolicy(userId, 'Allow', event.methodArn, { userId }))
  })
}

const generatePolicy = (principalId, effect, resource, context) => {
  return {
    principalId,
    Version: '2012-10-17',
    Statement: [{
      Action: 'execute-api:Invoke',
      Effect: effect,
      Resource: resource
    }],
    context: context,
  }
}

【问题讨论】:

    标签: node.js aws-lambda aws-api-gateway serverless-framework


    【解决方案1】:

    嗯。 Policy 对象的格式错误。版本和声明应包含在 policyDocument 中。

    {
      "principalId": "yyyyyyyy",
      "policyDocument": {
        "Version": "2012-10-17",
        "Statement": [
          {
            "Action": "execute-api:Invoke",
            "Effect": "Allow|Deny",
            "Resource": "arn:aws:execute-api:{regionId}:{accountId}:{appId}/{stage}/{httpVerb}/[{resource}/[child-resources]]"
          }
        ]
      },
      "context": {
        "stringKey": "value",
        "numberKey": "1",
        "booleanKey": "true"
      },
      "usageIdentifierKey": "{api-key}"
    }
    

    【讨论】:

      猜你喜欢
      • 2021-06-28
      • 1970-01-01
      • 2017-07-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-07
      • 2018-03-11
      • 1970-01-01
      相关资源
      最近更新 更多