問題描述
使用 AWS Lambda 對 Hasura 身份驗證掛鉤的空響應 (Empty response on Hasura auth hook using AWS Lambda)
我在使用 Lambda 配置 Hasura 身份驗證掛鉤時遇到了一些麻煩。出於安全原因,我需要這樣一個函數,因為我將 JWT 令牌存儲在僅 HTTP 的 cookie 中。
我正在使用返回正確響應的無服務器函數(直接測試 curl 請求時) ,甚至在記錄 lambda 時):
{
"statusCode":200,
"body":"{\"X‑Hasura‑User‑Id\":\"74d3bfa9‑0983‑4f09‑be02‑6a36888b382e\",\"X‑Hasura‑Role\":\"user\"}"
}
然而,Hasura 鉤子似乎無法識別響應:
{
"type": "webhook‑log",
"timestamp": "2020‑02‑07T10:27:34.844+0000",
"level": "info",
"detail": {
"response": null,
"url": "http://serverless:3000/auth",
"method": "GET",
"http_error": null,
"status_code": 200
}
}
這兩行日誌在我的日誌中是相鄰的。我只是對它們進行了一些重新格式化以方便閱讀。
我的 lambda 代碼如下所示:
export const handler = async (event) => {
const cookies = getCookiesFromHeader(event.headers);
const { access_token: accessToken } = cookies;
let decodedToken = null;
try {
const cert = fs.readFileSync("./src/pem/dev.pem");
decodedToken = jwt.verify(accessToken, cert);
} catch (err) {
console.error(err);
return {
statusCode: 401,
};
}
const hasuraClaims = decodedToken['https://hasura.io/jwt/claims'];
return {
statusCode: 200,
body: JSON.stringify({
"X‑Hasura‑User‑Id": hasuraClaims['x‑hasura‑user‑id'],
"X‑Hasura‑Role": hasuraClaims['x‑hasura‑default‑role']
})
}
}
知道發生了什麼嗎?請注意,我正在使用無服務器離線,以防萬一。:)
參考解法
方法 1:
In AWS Lambda, the spec requires the response body to be stringified and the actual response will be a parsed JSON object which is what Hasura will receive from the auth webhook.
When you are using serverless‑offline
, the response body is returned as a String (since JSON.stringify is used) without getting parsed. A simple curl will give you the difference.
The above code will work on Lambda but not on local development using serverless‑offline. You will have to use the event
object to see if isOffline
is true and return JSON directly and if not return the stringified version.
Example code:
if(event.isOffline) {
// make it work with serverless‑offline
return { "x‑hasura‑role": "user" ....};
} else {
// make it work with lambda
return { statusCode: 200, body: JSON.stringify({"x‑hasura‑role": "user"}) };
}
Official example in the serverless‑offline repo along with error handling.
Related issues:
- https://github.com/dherault/serverless‑offline/issues/530
- https://github.com/dherault/serverless‑offline/issues/488
(by Jonathan Petitcolas、praveenweb)