簡體   English   中英

使用JSON Web令牌的無服務器身份驗證

[英]serverless authentication with JSON Web Tokens

我學習基於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網關設置了自定義授權者。 我首先測試所有的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,
  }
}

好。 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}"
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM