使用JSON Web令牌进行无服务器身份验证

时间:2018-02-20 14:00:32

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

我学习了基于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,
  }
}

1 个答案:

答案 0 :(得分:0)

好。 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}"
}
相关问题