Search code examples
oauth-2.0aws-api-gatewayamazon-cognitowebsecurityrest-security

Is this possible to use cognito's Authorization code grant type as a authorizer in the api-gateway?


I would like to know is there any way or possibility to implement authorization code grant type as Authroizer in securing API gateway? As is searched, 'Authorization code' grant type is most recommended for securing API. i found below article which explain's using cognito 'client credentials' as grant type to secure the api gateway,

https://medium.com/@awskarthik82/part-1-securing-aws-api-gateway-using-aws-cognito-oauth2-scopes-410e7fb4a4c0

I tried the similar way to create an API gateway, where i have done following integration:

  1. Created user pool 'UI Hosted' in cognito with the grant type - 'Authorization code'

  2. Add the resource server

  3. Choosed default scopes as i don't want to add any new scope

  4. Associated call back uri

Now iam able to access the login page to sign up and sign in and it return the 'Authorization code' in the call back uri

In API gateway

  1. I created an API and integrated some mock response

  2. Attached above user pool as Authorizer in the api gateway and deployed

Now when i invoke the api without passing token, it returns 'Unauthorized'

So i used below approach to extract the access token from cognito

How programtically exchange the authorization code to get the access token from cognito using python

And passed the token in the api header using post man, but still i am getting 'Unauthorized' response

So would like to know what needs to be done in api gateway in order to verify the token or what went wrong in this approach..?

Appreciate if anybody can help on this?

Thanks


Solution

  • finally i got the answer here..

    https://aws.amazon.com/blogs/mobile/understanding-amazon-cognito-user-pool-oauth-2-0-grants/

    so i created a simple flask logic here to exchange the auth code to get the 'id_token' from cognito, which further can pass in the api header to get the response.

    def getToken(auth_code):
        response=''
        try:
            print("Code is", auth_code)
            response = requests.post(url + '/oauth2/token',{'Content-Type':'application/x-www-form-urlencoded', 'grant_type': grant_type, 'client_id': App_client_id,  'code': auth_code, 'redirect_uri': 'http://localhost:5000/login'})
            if response.status_code != 200:
                return "Not a valid response"
            print("Response is", response.json())
            token_value = response.json()
            print("Token value", token_value['id_token'])
            return token_value['id_token']
    
        except TypeError as e:
            print("Error is",e)