【发布时间】: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