question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Unauthorized API calls

See original GitHub issue

Hi, I’m trying to setup the Cognito Auth to be able to get a user username, I’m adding to my handlers

authorizer_employee = CognitoUserPoolAuthorizer(
    'MyUserPool',
    ['arn:aws:cognito-idp:eu-west-1:...']
)

@app.route('/user/getUsername', methods=['GET'], authorizer=authorizer_employee)
def user_get():
    request = app.current_request
    print(request.context)
    return {'req': request.to_dict()}

and according to https://stackoverflow.com/questions/52765636/api-created-with-chalice-and-a-cognito-authorizer-returns-unauthorized I’m using autogen_policy: false and adding this to .chalice/policy-dev.json

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "logs:CreateLogGroup",
                "logs:CreateLogStream",
                "logs:PutLogEvents"
            ],
            "Resource": "arn:aws:logs:*:*:*"
        },
        {
            "Effect": "Allow",
            "Action": [
                "cognito-identity:*",
                "cognito-idp:*",
                "cognito-sync:*",
                "iam:ListRoles",
                "iam:ListOpenIdConnectProviders",
                "sns:ListPlatformApplications"
            ],
            "Resource": "*"
        }
    ]
}

then I’m using the following code to query the API:

import boto3
import requests
import subprocess

USERPOOL_CLIENT_ID = 'USERPOOL_ID'
REST_API_URL = subprocess.check_output(['chalice', 'url']).decode('utf-8').strip()

class AuthAPI:
    def __init__(self, client_id, api_url):
        self.client_id = client_id
        self.api_url = api_url
        self.access_token = None
        self.client = boto3.client('cognito-idp')

    def connect(self, username, password):
        response = self.client.initiate_auth(
            ClientId=self.client_id,
            AuthFlow='USER_PASSWORD_AUTH',
            AuthParameters={
                'USERNAME': username,
                'PASSWORD': password,
            },
        )
        self.access_token = response['AuthenticationResult']['AccessToken']
        return response

    @property
    def headers(self):
        return {'Authorization': self.access_token}

    def get(self, endpoint):
        return requests.get('{}/{}'.format(REST_API_URL, endpoint), headers=self.headers)

api = AuthAPI(USERPOOL_CLIENT_ID, REST_API_URL)
api.connect('email', 'password')
r = api.get('user/getUsername')
print(r.text)

the token is generated correctly, but when hitting the API I get {"message":"Unauthorized"}

what should I change?

I updated the cognito ClientId to not use a secret and allow AUTH_PASSWORD

is there something to change?

is it possible to add a full working example of cognito authentication to the doc or chalice?

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Comments:7 (1 by maintainers)

github_iconTop GitHub Comments

1reaction
maelpcommented, Mar 9, 2020

Is it normal that when doing this and authenticating, I get parameters in the context claims, but the context identity does not have account data?

"identity":{"cognitoIdentityPoolId":null,"accountId":null,"cognitoIdentityId":null,"caller":null,"sourceIp":"ip","principalOrgId":null,"accessKey":null,"cognitoAuthenticationType":null,"cognitoAuthenticationProvider":null,"userArn":null,"userAgent":"python-requests/2.23.0","user":null}
0reactions
no-response[bot]commented, Mar 18, 2020

This issue has been automatically closed because there has been no response to our request for more information from the original author. With only the information that is currently in the issue, we don’t have enough information to take action. Please reach out if you have or find the answers we need so that we can investigate further.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Unauthorized Api Calls Alarm - A Secure Cloud
Unauthorized Api Calls Alarm. A CloudWatch Alarm that triggers if Multiple unauthorized actions or logins attempted. Prerequisites: This Alarm requires ...
Read more >
AWS Unauthorized Operation Alarm | CloudWatch Best Practice
Understanding when unauthorized api calls are being made can alert you to a potential security incident and is why this is considered a...
Read more >
CloudWatch log metric filter and alarm for unauthorized API ...
It is recommended that users set up a metric filter and alarm for unauthorized API calls. Monitoring unauthorized API calls will help reveal...
Read more >
Authorization Failures Alarm | Trend Micro
Ensure any unauthorized API calls made within your AWS account are being monitored using CloudWatch alarms.
Read more >
Review API calls in your AWS account using CloudTrail
You can use AWS CloudTrail data to view and track API calls made to your account using the following: ... Note: Not all...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found