Cognito Userpool as identy provider with client credentials works only after saving in aws console - amazon-web-services

I'm deploying a serverless application in aws with the serverless framework. I was setting up AUTH2 with a cognito userpool and client credential authentication.
After the deployment it's not working, I get the error invalid grant, when I request a new token via postman.
When i login into the aws console, open the cognito app client page (refresh the page) and click the "save" button (without changing anything), it works. I can request as access token and can login into my app.
It works until my next deployment, so automatic deployment is not possible. What could be the reason? What happens when I click the save button?
This is my deployment code
resources:
Resources:
UserPoolDomain:
Type: AWS::Cognito::UserPoolDomain
Properties:
UserPoolId:
Ref: CognitoUserPool
Domain: "myapp-user-pool-domain"
CognitoUserPool:
Type: "AWS::Cognito::UserPool"
Properties:
MfaConfiguration: OFF
UserPoolName: myapp-user-pool
AdminCreateUserConfig:
AllowAdminCreateUserOnly: true
UsernameAttributes:
- email
CognitoUserPoolClient:
Type: "AWS::Cognito::UserPoolClient"
Properties:
ClientName: myapp-user-pool-client
GenerateSecret: True
UserPoolId:
Ref: CognitoUserPool
AllowedOAuthFlows: [ "client_credentials"]
ExplicitAuthFlows: ["ALLOW_USER_PASSWORD_AUTH","ALLOW_REFRESH_TOKEN_AUTH" ]
SupportedIdentityProviders: [ "COGNITO" ]
AllowedOAuthScopes: [ "myapp/odata4","myapp/trigger" ]
PreventUserExistenceErrors: ENABLED
ApiGatewayAuthorizer:
DependsOn:
- ApiGatewayRestApi
Type: AWS::ApiGateway::Authorizer
Properties:
Name: cognito-authorizer
IdentitySource: method.request.header.Authorization
RestApiId:
Ref: ApiGatewayRestApi
Type: COGNITO_USER_POOLS
ProviderARNs:
- Fn::GetAtt: [ CognitoUserPool, Arn ]
UserPoolResourceServer:
Type: AWS::Cognito::UserPoolResourceServer
Properties:
UserPoolId:
Ref: CognitoUserPool
Identifier: "myapp"
Name: "myapp"
Scopes:
- ScopeName: "results"
ScopeDescription: "provides myapp results"
- ScopeName: "trigger"
ScopeDescription: "trigger for myapp start"
Who can help?
Thanks

The following line has to be added to CognitoUserPoolClient: AllowedOAuthFlowsUserPoolClient: True. Then it works.

Related

Serverless Framework How to Get Access, Id and Refresh Tokens from AWS Cognito

I am trying to secure my serverless NodeJS apis using AWS Cognito User Pools.
Below is a sample of my serverless framework configuration:
service: hello-world
frameworkVersion: '3'
provider:
name: aws
runtime: nodejs14.x
environment:
user_pool_id: { Ref: UserPool }
client_id: { Ref: UserClient }
iam:
role:
statements:
- Effect: Allow
Action:
- cognito-idp:AdminInitiateAuth
- cognito-idp:AdminCreateUser
- cognito-idp:AdminSetUserPassword
Resource: "*"
functions:
loginUser:
handler: ./auth/login.handler
events:
- http:
path: auth/login
method: post
cors: true
signupUser:
handler: ./auth/signup.handler
events:
- http:
path: auth/signup
method: post
cors: true
list:
handler: ./users/users.handler
events:
- http:
path: users/list
method: get
cors: true
authorizer:
type: COGNITO_USER_POOLS
authorizerId:
Ref: ApiGatewayAuthorizer
resources:
Resources:
ApiGatewayAuthorizer:
Type: AWS::ApiGateway::Authorizer
Properties:
Name: CognitoUserPool
Type: COGNITO_USER_POOLS
IdentitySource: method.request.header.Authorization
RestApiId:
Ref: ApiGatewayRestApi
ProviderARNs:
- Fn::GetAtt:
- UserPool
- Arn
UserPool:
Type: AWS::Cognito::UserPool
Properties:
UserPoolName: serverless-auth-pool
Schema:
- Name: email
Required: true
Mutable: true
Policies:
PasswordPolicy:
MinimumLength: 6
AutoVerifiedAttributes: ["email"]
UserClient:
Type: AWS::Cognito::UserPoolClient
Properties:
ClientName: user-pool-ui
GenerateSecret: false
UserPoolId: { Ref: UserPool }
AccessTokenValidity: 1
IdTokenValidity: 1
ExplicitAuthFlows:
- "ADMIN_NO_SRP_AUTH"
I can successfully can call the signup and login endpoints to get a token and then use this token as an Authorization header to call my /users/list endpoint to get a list of users.
My problem is that I was expecting the login endpoint to return 3 tokens - an id token, an access token and a refresh token.
The login endpoint currently only returns one token that has a claim of:
"token_use": "id"
If I pass this token to the /users/list api then it is successfully validated, but I thought that the api would need the access token instead of the id token for authentication.
Does anyone know if my assumption is correct and how to fix the issue or have I misunderstood how the auth flow works ?

Aws sam cognito api gateway - access token forbidden but works if it's from postman

I have a CognitoUserPool and a lambda function that requires an authenticated user.
When making a request with the token acquired from postman that opens the aws UI login, it works, but when using the token from a curl login it doesn't got 403 forbidden, any idea of what I'm missing?
My template.yaml
AWSTemplateFormatVersion: '2010-09-09'
Parameters:
Env:
Type: String
Default: dev
AllowedValues:
- dev
- test
- prod
Description: >-
sam-app
Transform:
- AWS::Serverless-2016-10-31
Globals:
Function:
Timeout: 100
Runtime: nodejs16.x
MemorySize: 128
Resources:
CognitoUserPool:
Type: AWS::Cognito::UserPool
Properties:
UserPoolName: !Sub ${Env}-Cognito-User-Pool
Policies:
PasswordPolicy:
MinimumLength: 8
UsernameAttributes:
- email
AutoVerifiedAttributes:
- email
Schema:
- AttributeDataType: String
Name: email
Required: false
CognitoUserPoolClient:
Type: AWS::Cognito::UserPoolClient
Properties:
UserPoolId: !Ref CognitoUserPool
ClientName: !Sub ${Env}-CognitoUserPoolClient
GenerateSecret: false
CallbackURLs:
- http://localhost:3000
LogoutURLs:
- http://localhost:3000
AllowedOAuthFlowsUserPoolClient: true
ExplicitAuthFlows:
- ALLOW_ADMIN_USER_PASSWORD_AUTH
- ALLOW_USER_PASSWORD_AUTH
- ALLOW_CUSTOM_AUTH
- ALLOW_USER_SRP_AUTH
- ALLOW_REFRESH_TOKEN_AUTH
- ALLOW_USER_PASSWORD_AUTH
AllowedOAuthFlows:
- code
- implicit
SupportedIdentityProviders:
- COGNITO
AllowedOAuthScopes:
- openid
- email
- profile
CognitoDomainName:
Type: AWS::Cognito::UserPoolDomain
Properties:
Domain: !Sub ${Env}-domain-test
UserPoolId: !Ref CognitoUserPool
HttpApi:
Type: AWS::Serverless::HttpApi
DependsOn: CognitoUserPoolClient
Properties:
StageName: !Ref Env
Auth:
Authorizers:
CustomCognitoAuthorizer:
UserPoolArn: !GetAtt CognitoUserPool.Arn
AuthorizationScopes:
- email
IdentitySource: "$request.header.Authorization"
JwtConfiguration:
issuer: !Sub https://cognito-idp.${AWS::Region}.amazonaws.com/${CognitoUserPool}
audience:
- !Ref CognitoUserPoolClient
CorsConfiguration:
AllowMethods:
- GET
AllowHeaders: '*'
AllowOrigins:
- '*'
getAllItemsFunction:
Type: AWS::Serverless::Function
Properties:
Handler: src/handlers/get-all-items.getAllItemsHandler
Events:
DosGet:
Type: HttpApi
Properties:
Auth:
Authorizer: CustomCognitoAuthorizer
Path: /
ApiId: !Ref HttpApi
Method: GET
The curl that I use to login, got it from this post AWS - Cognito Authentication - Curl Call - Generate Token Without CLI - No Client Secret
Method: POST
Endpoint: https://cognito-idp.{REGION}.amazonaws.com/
Content-Type: application/x-amz-json-1.1
X-Amz-Target: AWSCognitoIdentityProviderService.InitiateAuth
Body:
{
"AuthParameters" : {
"USERNAME" : "YOUR_USERNAME",
"PASSWORD" : "YOUR_PASSWORD"
},
"AuthFlow" : "USER_PASSWORD_AUTH", // Don't have to change this if you are using password auth
"ClientId" : "APP_CLIENT_ID"
}
After a bit of digging, I solved the issue, by analyzing the token that was generated from each method I saw a difference.
The token acquired from the aws UI.
{
"scope": "aws.cognito.signin.user.admin"
}
And the one from curl login
{
"scope": "openid profile email"
}
So the solution was to add aws.cognito.signin.user.admin as part of my UserPoolClient AllowedOAuthScopes
AllowedOAuthScopes:
- openid
- email
- profile
- aws.cognito.signin.user.admin
and on my HttpApi AuthorizationScopes
AllowedOAuthScopes:
- email
- aws.cognito.signin.user.admin

Why does Cognito IDP initiate_auth not authorise API Gateway in this setup?

I have a cloud formation stack containing a Cognito User Pool and its client, an API Gateway and an Authorizer.
If I log in using the hosted form I get JWT tokens - and the access_token successfully authorises the API.
However if I log using idp.initiate_auth(), using the same credentials, I also get a set of JWT tokens - but the access_token won't allow me to access the API.
I can see that the hosted form does some opaque magic inside a function called getAdvancedSecurityData() and writes a form variable called cognitoAsfData... but beyond that I cannot make sense of it.
Here is - I hope the relevant sections of CFN config:
AWSTemplateFormatVersion: "2010-09-09"
Description: ""
Resources:
LADApiGatewayRestApi:
Type: "AWS::ApiGateway::RestApi"
Properties:
Name: "DemoApi"
Description: "This is the demo API."
ApiKeySourceType: "HEADER"
EndpointConfiguration:
Types:
- "REGIONAL"
LADApiGatewayStage:
Type: "AWS::ApiGateway::Stage"
Properties:
StageName: "test"
DeploymentId: !Ref LADApiGatewayDeployment
RestApiId: !Ref LADApiGatewayRestApi
CacheClusterEnabled: false
TracingEnabled: false
LADApiGatewayDeployment:
Type: "AWS::ApiGateway::Deployment"
Properties:
RestApiId: !Ref LADApiGatewayRestApi
DependsOn:
- LADApiGatewayResource
- LADApiGatewayMethod
- LADApiGatewayRestApi
LADApiGatewayResource:
Type: "AWS::ApiGateway::Resource"
Properties:
RestApiId: !Ref LADApiGatewayRestApi
PathPart: "transactions"
ParentId: !GetAtt LADApiGatewayRestApi.RootResourceId
LADApiGatewayMethod:
Type: "AWS::ApiGateway::Method"
Properties:
RestApiId: !Ref LADApiGatewayRestApi
ResourceId: !Ref LADApiGatewayResource
HttpMethod: "GET"
AuthorizationType: "COGNITO_USER_POOLS"
AuthorizerId: !Ref LADApiGatewayAuthorizer
ApiKeyRequired: false
MethodResponses:
-
ResponseModels:
"application/json": "Empty"
StatusCode: "200"
Integration:
CacheNamespace: !Ref LADApiGatewayResource
ContentHandling: "CONVERT_TO_TEXT"
IntegrationHttpMethod: "POST"
IntegrationResponses:
-
ResponseTemplates: {}
StatusCode: "200"
PassthroughBehavior: "WHEN_NO_MATCH"
TimeoutInMillis: 29000
Type: "AWS"
Uri: !Sub "arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/arn:aws:lambda:${AWS::Region}:${AWS::AccountId}:function:${LADLambdaFunction}/invocations"
AuthorizationScopes:
- "email"
LADApiGatewayAuthorizer:
Type: "AWS::ApiGateway::Authorizer"
Properties:
RestApiId: !Ref LADApiGatewayRestApi
Name: "LADDemoApiAuthorizer"
Type: "COGNITO_USER_POOLS"
ProviderARNs:
- !GetAtt LADCognitoUserPool.Arn
AuthType: "cognito_user_pools"
IdentitySource: "method.request.header.Authorization"
LADCognitoUserPool:
Type: "AWS::Cognito::UserPool"
Properties:
UserPoolName: "DemoApp"
Policies:
PasswordPolicy:
MinimumLength: 8
RequireUppercase: true
RequireLowercase: true
RequireNumbers: true
RequireSymbols: true
TemporaryPasswordValidityDays: 7
LambdaConfig: {}
Schema:
-
Name: "sub"
(...)
AutoVerifiedAttributes:
- "email"
MfaConfiguration: "OFF"
EmailConfiguration:
EmailSendingAccount: "COGNITO_DEFAULT"
AdminCreateUserConfig:
AllowAdminCreateUserOnly: false
UserPoolTags: {}
AccountRecoverySetting:
RecoveryMechanisms:
-
Priority: 1
Name: "verified_email"
-
Priority: 2
Name: "verified_phone_number"
UsernameConfiguration:
CaseSensitive: false
VerificationMessageTemplate:
DefaultEmailOption: "CONFIRM_WITH_CODE"
LADCognitoUserPoolClient:
Type: "AWS::Cognito::UserPoolClient"
Properties:
UserPoolId: !Ref LADCognitoUserPool
ClientName: "DemoAppClient"
RefreshTokenValidity: 30
ReadAttributes:
- "address" (...)
ExplicitAuthFlows:
- "ALLOW_CUSTOM_AUTH"
- "ALLOW_REFRESH_TOKEN_AUTH"
- "ALLOW_USER_SRP_AUTH"
- "ALLOW_USER_PASSWORD_AUTH"
GenerateSecret: false
PreventUserExistenceErrors: "ENABLED"
SupportedIdentityProviders:
- "COGNITO"
CallbackURLs:
- "https://example.com/callback"
LogoutURLs:
- "https://example.com/signout"
AllowedOAuthFlows:
- "code"
- "implicit"
AllowedOAuthScopes:
- "aws.cognito.signin.user.admin"
- "email"
- "openid"
- "phone"
- "profile"
AllowedOAuthFlowsUserPoolClient: true
IdTokenValidity: (...)
LADCognitoUserPoolDomain:
Type: "AWS::Cognito::UserPoolDomain"
Properties:
Domain: !Sub "ladauthdemo${LADApiGatewayStage}"
UserPoolId: !Ref LADCognitoUserPool
In the case of access_token from the hosted html I get tokens which decode like this:
{
"kid": "jFXB1AW4cAjbF1Ti+Tru/8ToxbYCAB1IYdCwEGfM7Sk=",
"alg": "RS256"
}
{
"sub": "eabb63bf-7bf2-464f-9d94-808239738981",
"iss": "https://cognito-idp.eu-west-2.amazonaws.com/eu-west-2_EyTaD2AsF",
"version": 2,
"client_id": "40vstm6vrhas7kokoasnrhf1g1",
"event_id": "2cbcc84d-db84-4ab5-91db-4088cd18829a",
"token_use": "access",
"scope": "aws.cognito.signin.user.admin phone openid profile email",
"auth_time": 1652623673,
"exp": 1652627273,
"iat": 1652623673,
"jti": "84921f7a-bd8e-4fea-a89d-984b1645b6e2",
"username": "testuser-adbed764-81f3-4b4f-950a-db2f041ff833#tunasoniq.io"
}
In the case of access_token from the api only the header part is base64 decodable. The header reads the same as the header above.
Here's an example of a whole encoded token from the api:
eyJraWQiOiJqRlhCMUFXNGNBamJGMVRpK1RydVwvOFRveGJZQ0FCMUlZZEN3RUdmTTdTaz0iLCJhbGciOiJSUzI1NiJ9.eyJzdWIiOiI1ZTJjYTRlOC0wYzNlLTQwZGYtYWJkMS0wOGFmOGI3MmM0YTIiLCJpc3MiOiJodHRwczpcL1wvY29nbml0by1pZHAuZXUtd2VzdC0yLmFtYXpvbmF3cy5jb21cL2V1LXdlc3QtMl9FeVRhRDJBc0YiLCJjbGllbnRfaWQiOiI0MHZzdG02dnJoYXM3a29rb2FzbnJoZjFnMSIsIm9yaWdpbl9qdGkiOiI4NDAyMjc4ZC0xMzA4LTRmZTgtODUyNC1kNjcxNjliNTg0ZjciLCJldmVudF9pZCI6IjdjMDA2YTQ1LWZiOTUtNDU1Mi05MWNhLTk2YTUwZjQ5MjRmOSIsInRva2VuX3VzZSI6ImFjY2VzcyIsInNjb3BlIjoiYXdzLmNvZ25pdG8uc2lnbmluLnVzZXIuYWRtaW4iLCJhdXRoX3RpbWUiOjE2NTI2MzgwMDgsImV4cCI6MTY1MjY0MTYwOCwiaWF0IjoxNjUyNjM4MDA4LCJqdGkiOiIwNjNlMzRhOC0wYzQ5LTRlNzItYTBjYi0wYjRhZTcxMTdhYmIiLCJ1c2VybmFtZSI6InRlc3R1c2VyLTM2MDkzZGZiLTViNWMtNGFkNi1hMzk4LWIwODQ2ODdlODUzN0B0dW5hc29uaXEuaW8ifQ.VQTz1cFOKUfn-QbOWfl4lk7gzbmptKS-tiCWlBAFbagMt4NvhAZVaLg_Sh7N8BNKw1apkjgQVeC0Coq4otQcDp04z4dt4kyvjFGUO7hdHbgDpp6vNL5pk3yy48a8Zw011gz9fZaAE9CcebBjLFWsWNix8JrN86CwtRiXcoBq6aRKeJez_HVPdLoT8cebESnmI5KbR7DeLcv_J7S-t5DJ9V__X9ksF8yybKlgiytBH7F9RvmCyMH3-8vuxLxOd8ZJ7MOx8NgXKjTw5ETkAWWWGSwp8FBw8Npkf2KmHiRMPaYjg-_sAJPirsc4tyBG8fDhwNCjnEFrj6VfzBjHxgadSA
Your API token is missing the email scope, which is required to access the APIG resource. You need to request the scopes which you want the token to be issued for when you make the call to the API, or you can manually add them with a Cognito pre-token-generation lambda.
There is no way that I've been able to discover, of getting back scopes other than 'aws.cognito.signin.user.admin' using the published APIs. The only way to get those scopes is to leverage the opaque magic in the hosted HTML from Cognito.
However you can add 'aws.cognito.signin.user.admin' to the AuthorizationScopes on your AWS::ApiGateway::Method and it works.
I think this a bit of an abuse of OAUTH process so don't use it to handle access to the nuclear codes.

AWS: Re-use amazon Cognito Userpool in multiple serverless applications

I have divided my serverless project in to multiple projects to avoid template error resource > 200. Now I am facing another error.
I have implemented authentication and authorization using AWS cognito which works well for lambda functions in one serverless application. I am trying to re-use same Cognito Userpool for authorizing API's in another serverless project. However, each serverless project creates UserPool again with same name in Cognito. How to avoid this issue.
Here is the how my serverless.yml and dummy response look like in lambda functions
CognitoUserPool:
Type: "AWS::Cognito::UserPool"
Properties:
MfaConfiguration: OFF
UserPoolName: userpool-impl
#RequiredAttributes:
# - email
UsernameAttributes:
- email
Policies:
PasswordPolicy:
MinimumLength: 8
RequireLowercase: True
RequireNumbers: True
RequireSymbols: True
RequireUppercase: True
CognitoUserPoolClient:
Type: "AWS::Cognito::UserPoolClient"
Properties:
ClientName: client-impl
GenerateSecret: False
UserPoolId:
Ref: CognitoUserPool
ApiGatewayAuthorizer:
DependsOn:
- ApiGatewayRestApi
Type: AWS::ApiGateway::Authorizer
Properties:
Name: cognito-authorizer
IdentitySource: method.request.header.Authorization
RestApiId:
Ref: ApiGatewayRestApi
Type: COGNITO_USER_POOLS
ProviderARNs:
- Fn::GetAtt: [CognitoUserPool, Arn]
Lamdba function:
response = {
"statusCode": 200,
'headers': {
"Access-Control-Allow-Origin": "http://localhost:3000",
"Access-Control-Allow-Credentials": True
},
"body": "Dummy Response"
}

Cognito user pool authorizer With Serverless Framework

I need to authorize my API end point using aws cognito userpool. I can do it manually, but I need to automate the authorization part with the serverless framework.
Does the Serverless framework have support for aws cognito?
If so, how do we setup an aws-userpool with serverless?
Yes . Serverless (v1.5) support to Cognito user pool authorizer.
If you use previous version of serverless you have to update v1.5 or later.
For the user-pool authorization of api end point you have to specify pool arn.
functions:
hello:
handler: handler.hello
events:
- http:
path: hello
method: get
integration: lambda
authorizer:
name: authorizer
arn: arn:aws:cognito-idp:us-east-1:123456789:userpool/us-east-1_XXXXXX
More details read this article.
If you want to set the authorizer to a Cognito User Pool you have declared in your resources you must use CloudFormation to create the authorizer as well.
functions:
functionName:
# ...
events:
- http:
# ...
authorizer:
type: COGNITO_USER_POOLS
authorizerId:
Ref: ApiGatewayAuthorizer
resources:
Resources:
ApiGatewayAuthorizer:
Type: AWS::ApiGateway::Authorizer
Properties:
Name: CognitoUserPool
Type: COGNITO_USER_POOLS
IdentitySource: method.request.header.Authorization
RestApiId:
Ref: ApiGatewayRestApi
ProviderARNs:
- Fn::GetAtt:
- UserPool
- Arn
UserPool:
Type: AWS::Cognito::UserPool
Serverless 1.35.1
In case someone stumbles across this how I did. Here is my working solution.
Wherever you create the user pool, you can go ahead and add ApiGatewayAuthorizer
# create a user pool as normal
CognitoUserPoolClient:
Type: AWS::Cognito::UserPoolClient
Properties:
# Generate an app client name based on the stage
ClientName: ${self:custom.stage}-user-pool-client
UserPoolId:
Ref: CognitoUserPool
ExplicitAuthFlows:
- ADMIN_NO_SRP_AUTH
GenerateSecret: true
# then add an authorizer you can reference later
ApiGatewayAuthorizer:
DependsOn:
# this is pre-defined by serverless
- ApiGatewayRestApi
Type: AWS::ApiGateway::Authorizer
Properties:
Name: cognito_auth
# apparently ApiGatewayRestApi is a global string
RestApiId: { "Ref" : "ApiGatewayRestApi" }
IdentitySource: method.request.header.Authorization
Type: COGNITO_USER_POOLS
ProviderARNs:
- Fn::GetAtt: [CognitoUserPool, Arn]
Then when you define your functions
graphql:
handler: src/app.graphqlHandler
events:
- http:
path: /
method: post
cors: true
integration: lambda
# add this and just reference the authorizer
authorizer:
type: COGNITO_USER_POOLS
authorizerId:
Ref: ApiGatewayAuthorizer