简体   繁体   English

如何使用AWS Cognito Userpool令牌登录到AWS Api网关?

[英]How to use AWS Cognito Userpool token to log into AWS Api gateway?

I have created an API gateway endpoint with a lambda function at the backend. 我创建了一个在后端具有lambda函数的API网关端点。 Then I created a cognito userpool with one account and configured the cognito userpool as authorizer in API Gateway. 然后,我使用一个帐户创建了一个cognito用户池,并将该cognito用户池配置为API Gateway中的授权者。 I could see that the API was unauthorized. 我可以看到该API是未经授权的。

Then I created a small web page with AWS Cognito Javascript SDK to log into the userpool and get an access token. 然后,我使用AWS Cognito Javascript SDK创建了一个小型网页,以登录到用户池并获取访问令牌。 I was able to do that successfully. 我能够成功做到这一点。 Here is the code. 这是代码。

  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); }, }); 

This code works and gives me a JWT Token. 此代码有效,并给了我一个JWT令牌。 However that token does not authorizes me into the API. 但是,该令牌未授权我进入API。 I am passing the token in the Authorization header without the Bearer keyword but I still cannot access the API. 我在不带Bearer关键字的Authorization标头中传递令牌,但仍然无法访问API。 How can I do that? 我怎样才能做到这一点?

You might be able to debug more easily using the 'Test' feature for authorizers in the API Gateway console. 使用API​​网关控制台中授权者的“测试”功能,您可能能够更轻松地进行调试。 You can paste the valid JWT token there and run a test on the authorizer; 您可以在其中粘贴有效的JWT令牌,然后在授权者上运行测试; if there are any issues you should see them in the Logs output. 如果有任何问题,您应该在“日志”输出中看到它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM