【发布时间】:2021-06-18 10:14:56
【问题描述】:
我无法弄清楚为什么我在sam deploy 之后无法登录我的应用程序。我不断收到 CORS 丢失 Allow Origin
如果我使用 sam local start-api 在本地运行它,那么我会得到状态 200,因此它似乎可以在本地运行。我将 lambda 函数的 CORS 设置为 *,所以我不确定我需要更新什么。我有一个注册函数,它具有相同的响应头设置
headers: {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Credentials":
},
但是 register 函数没有 CORS 问题,所以我认为 template.yaml 很好。我不确定还需要做什么。感谢您对此提供的任何帮助!
login.js
'use strict';
//global.fetch = require('node-fetch')
require('dotenv').config();
const Cognito = require('./confirm/cognito/index');
const { verify } = require('./confirm/cognito/index');
exports.handler = async (event) => {
const json = JSON.parse(event.body)
// console.log("EVENT BODY", event.body)
const verificationResponse = await Cognito.signIn(json.email, json.password);
console.log(verificationResponse)
if (verificationResponse.statusCode !== 200) {
console.log("Verification Error:", verificationResponse.response.message);
const response = {
statusCode: 500,
body: JSON.stringify('failed to verify user'),
headers: {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Credentials": true
},
};
return response;
}
const response = {
statusCode: 200,
body: JSON.stringify(statusCode),
headers: {
"Access-Control-Allow-Origin": "*", // Required for CORS support to work
"Access-Control-Allow-Credentials": true // Required for cookies, authorization headers with HTTPS
},
};
return response;
};
Cognito.signIn 函数
function signIn(email, password) {
return new Promise((resolve) => {
AwsConfig.getCognitoUser(email).authenticateUser(AwsConfig.getAuthDetails(email, password), {
onSuccess: (result) => {
console.log("RESULT", result)
const token = {
accessToken: result.getAccessToken().getJwtToken(),
idToken: result.getIdToken().getJwtToken(),
refreshToken: result.getRefreshToken().getToken(),
}
return resolve({ statusCode: 200, response: AwsConfig.decodeJWTToken(token) });
},
onFailure: (err) => {
console.log("ERROR HERE", err)
return resolve({ statusCode: 400, response: err.message || JSON.stringify(err) });
},
});
});
}
模板.yaml
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: REST API using SAM
Globals:
Function:
Runtime: nodejs12.x
Environment:
Variables:
TABLE_NAME: !Ref Table
MemorySize: 128
Timeout: 5
Api:
Cors:
AllowMethods: "'GET,POST,PUT,DELETE,OPTIONS'"
AllowHeaders: "'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token,X-Amz-User-Agent'"
AllowOrigin: "'*'"
AllowCredentials: "'*'"
Resources:
Table:
Type: AWS::Serverless::SimpleTable
Properties:
PrimaryKey:
Name: userid
Type: String
ProvisionedThroughput:
ReadCapacityUnits: 1
WriteCapacityUnits: 1
RegisterUser:
Type: AWS::Serverless::Function
Properties:
Handler: register.handler
Events:
Register:
Type: Api
Properties:
Path: /register
Method: post
LoginUser:
Type: AWS::Serverless::Function
Properties:
Handler: login.handler
Events:
Login:
Type: Api
Properties:
Path: /login
Method: post
【问题讨论】:
-
如果您将所有服务器放在一个公共域后面,您将不会遇到 CORS 问题,并且您不需要像您正在使用的那样使用不安全的标头配置。
-
我可能会将 origin 标头更新为仅用于以后要使用的域,但我希望在开发过程中暂时在本地运行前端应用程序时让它工作。您能否就如何避免出现此错误提供任何建议?我让它在本地工作以进行注册,所以我只是不明白为什么登录会出现问题。
-
使用反向代理将所有服务器放在同一个源/域后面,您根本不需要标头。
-
因为您使用 AWS aws.amazon.com/blogs/architecture/…
标签: node.js aws-lambda cors amazon-cognito aws-sam