我在后端创建了一个带有lambda函数的API网关 endpoints . 然后我创建了一个包含一个帐户的cognito用户池,并将cognito用户池配置为API网关中的授权者 . 我可以看到API未经授权 .
然后,我使用AWS Cognito Javascript SDK创建了一个小网页,以登录到用户池并获取访问令牌 . 我能够成功地做到这一点 . 这是代码 .
var authenticationData = {
Username : 'username',
Password : 'test123',
};
var authenticationDetails = new AuthenticationDetails(authenticationData);
var poolData = {
UserPoolId : 'ap-southeast-2_12312', // Your user pool id here
ClientId : '434324324' // Your client id here
};
var userPool = new CognitoUserPool(poolData);
var userData = {
Username : 'username',
Pool : userPool
};
var self = this;
var cognitoUser = new CognitoUser(userData);
cognitoUser.authenticateUser(authenticationDetails, {
onSuccess: function (result) {
var tok = result.getAccessToken().getJwtToken();
console.log('access token + ' + tok);
self.setState({ token: tok });
//POTENTIAL: Region needs to be set if not already set previously elsewhere.
// AWS.config.region = '<region>';
// AWS.config.credentials = new AWS.CognitoIdentityCredentials({
// IdentityPoolId : '...', // your identity pool id here
// Logins : {
// // Change the key below according to the specific region your user pool is in.
// 'cognito-idp.<region>.amazonaws.com/<YOUR_USER_POOL_ID>' : tok
// }
// });
// Instantiate aws sdk service objects now that the credentials have been updated.
// example: var s3 = new AWS.S3();
},
onFailure: function(err) {
alert(err);
},
});
这段代码可以工作并给我一个JWT令牌 . 但是,该令牌并未授权我使用API . 我在没有Bearer关键字的Authorization标头中传递令牌,但我仍然无法访问API . 我怎样才能做到这一点?
1 回答
您可以使用API网关控制台中的授权者使用“测试”功能更轻松地进行调试 . 您可以在那里粘贴有效的JWT令牌并在授权器上运行测试;如果有任何问题,您应该在Logs输出中看到它们 .