Serverless Framework How to Get Access, Id and Refresh Tokens from AWS Cognito - amazon-web-services

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 ?

Related

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

Serverless Cognito - Sign Up with Username, Password, and Email

I am having trouble implementing Cognito via Serverless. The AWS Cognito documentation is poor. What I want to do is:
Allow user to sign up with a unique username (coolprogrammer69), a unique email, and password
After sign up, allow user to modify username (coolprogrammer69 -> awesomeprogrammer69) and email as long as it is unique
This is a typical auth flow for a forum website like Stackoverflow; however, I cannot find the right combination of attributes to make this a reality. Can you please help me figure out what I am doing wrong?
service: my-cool-infrastructure
package:
individually: true
provider:
name: aws
runtime: nodejs14.x
environment:
user_pool_id: { Ref: UserPool }
client_id: { Ref: UserClient }
iamRoleStatements:
- Effect: Allow
Action:
- cognito-idp:AdminInitiateAuth
- cognito-idp:AdminCreateUser
- cognito-idp:AdminSetUserPassword
Resource: "*"
functions:
login:
handler: user/login.handler
events:
- http:
path: user/login
method: post
cors: true
register:
handler: user/register.handler
events:
- http:
path: user/register
method: post
cors: true
privateAPI:
handler: user/private.handler
events:
- http:
path: user/private
method: post
cors: true
authorizer:
name: PrivateAuthorizer
type: COGNITO_USER_POOLS
arn:
Fn::GetAtt:
- UserPool
- Arn
claims:
- email
resources:
Resources:
UserPool:
Type: AWS::Cognito::UserPool
Properties:
UserPoolName: my-cognito-pool
Schema:
-
Name: email
Mutable: true
Required: true
-
Name: preferred_username
Mutable: true
Required: true
Policies:
PasswordPolicy:
MinimumLength: 8
RequireNumbers: true
RequireSymbols: true
UserClient:
Type: AWS::Cognito::UserPoolClient
Properties:
ClientName: user-pool-ui
GenerateSecret: false
UserPoolId: { Ref: UserPool }
AccessTokenValidity: 5
IdTokenValidity: 5
ExplicitAuthFlows:
- "ADMIN_NO_SRP_AUTH"

Cognito Userpool as identy provider with client credentials works only after saving in aws console

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.

Serverless framework AWS ApiGateway v2 authorizers

I'm trying to setup simple authorizer based on this doc. Also using serverless plugin serverless-pseudo-parameters.
My serverless configuration for authorizer:
provider:
...
logs:
httpApi: true
httpApi:
cors: true
authorizers:
simpleAuthorizer:
identitySource: $request.header.Authorization
issuerUrl:
- Fn::Join:
- '/'
- - https://cognito-idp.#{AWS::Region}.amazonaws.com
- "#{CognitoUserPool}"
audience:
- "#CognitoUserPoolClient"
My configuration for simple lambda:
functions:
ping:
name: ${self:provider.stage}-ping
handler: test.handler
events:
- httpApi:
method: GET
path: /test
authorizer:
name: simpleAuthorizer
My configuration of user pool and user pool client:
resources:
Resources:
CognitoUserPool:
Type: AWS::Cognito::UserPool
Properties:
UserPoolName: ${self:service}-${self:provider.stage}-user
UsernameAttributes:
- email
Policies:
PasswordPolicy:
MinimumLength: 6
RequireLowercase: False
RequireNumbers: True
RequireSymbols: False
RequireUppercase: True
Schema:
- Name: email
Required: false
DeveloperOnlyAttribute: false
Mutable: true
AttributeDataType: String
CognitoUserPoolClient:
Type: AWS::Cognito::UserPoolClient
Properties:
ClientName: cognito-example-client
GenerateSecret: False
UserPoolId: "#{CognitoUserPool}"
User pool, user pool client, HTTP API, lambda successfully created, but I can't see a authorizer at the AWS console of API Gateway service.
So, the problem has simple solution: just update your serverless (I used 1.63.0 which gave me this problem).

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