Skip to content

Instantly share code, notes, and snippets.

@rnjailamba
Last active March 27, 2021 11:49
Show Gist options
  • Save rnjailamba/fe54f41a5edc047e5f26a0fc01f4f5b5 to your computer and use it in GitHub Desktop.
Save rnjailamba/fe54f41a5edc047e5f26a0fc01f4f5b5 to your computer and use it in GitHub Desktop.
Reproduce accessToken verification
version: "3.7"
services:
localstack:
container_name: "${LOCALSTACK_DOCKER_NAME-localstack}"
image: localstack/localstack:latest
networks:
- mynet
ports:
- "4566-4599:4566-4599"
- '8081:8080'
- 443:443
environment:
- SERVICES=lambda,cognito,apigateway,cloudformation
- LOCALSTACK_API_KEY=<ZZZZZZZZZZ>
- DEBUG=1
- DATA_DIR=/tmp/localstack/data
- PORT_WEB_UI=${PORT_WEB_UI- }
- LAMBDA_EXECUTOR=docker-reuse
- LAMBDA_REMOTE_DOCKER=false
- LAMBDA_DOCKER_NETWORK=host
- LAMBDA_REMOVE_CONTAINERS=true
- KINESIS_ERROR_PROBABILITY=${KINESIS_ERROR_PROBABILITY- }
- DOCKER_HOST=unix:///var/run/docker.sock
- HOST_TMP_FOLDER=${PWD}/.localstack
volumes:
- "./.localstack:/tmp/localstack"
- "/var/run/docker.sock:/var/run/docker.sock"
- ./bin:/docker-entrypoint-initaws.d
networks:
mynet:
external: true
name: mynet
Unhandled rejection TypeError: Unable to generate certificate due to
StatusCodeError: 404 - "{\"message\":\"User pool us-east-2_76f5a0711ca3408d81e145b2321ea4e5 does not exist.\"}"
at /Users/rnjai/Desktop/auth/node_modules/cognito-express/lib/strategy.js:42:23
at tryCatcher (/Users/rnjai/Desktop/auth/node_modules/bluebird/js/release/util.js:16:23)
at Promise._settlePromiseFromHandler (/Users/rnjai/Desktop/auth/node_modules/bluebird/js/release/promise.js:547:31)
at Promise._settlePromise (/Users/rnjai/Desktop/auth/node_modules/bluebird/js/release/promise.js:604:18)
at Promise._settlePromise0 (/Users/rnjai/Desktop/auth/node_modules/bluebird/js/release/promise.js:649:10)
at Promise._settlePromises (/Users/rnjai/Desktop/auth/node_modules/bluebird/js/release/promise.js:725:18)
at _drainQueueStep (/Users/rnjai/Desktop/auth/node_modules/bluebird/js/release/async.js:93:12)
at _drainQueue (/Users/rnjai/Desktop/auth/node_modules/bluebird/js/release/async.js:86:9)
at Async._drainQueues (/Users/rnjai/Desktop/auth/node_modules/bluebird/js/release/async.js:102:5)
at Immediate.Async.drainQueues [as _onImmediate] (/Users/rnjai/Desktop/auth/node_modules/bluebird/js/release/async.js:15:14)
at processImmediate (node:internal/timers:464:21)
Verification -
AWS_DEFAULT_REGION=us-east-2 awslocal cognito-idp list-user-pools --max-results 10
{
"UserPools": [
{
"Id": "us-east-2_cfed32601dea4320873407021d70bbf8",
"Name": "sunroom-dev",
"LambdaConfig": {
},
"LastModifiedDate": "2021-03-27T04:23:59-06:00",
"CreationDate": "2021-03-27T04:23:59-06:00"
},
{
"Id": "us-east-2_75e89f6b4dfb49eeafe48b0336107948",
"Name": "sunroom-dev",
"LambdaConfig": {
"PostConfirmation": "arn:aws:lambda:us-east-2:000000000000:function:syncToHasura"
},
"LastModifiedDate": "2021-03-27T05:40:20-06:00",
"CreationDate": "2021-03-27T05:40:20-06:00"
},
{
"Id": "us-east-2_76f5a0711ca3408d81e145b2321ea4e5",
"Name": "sunroom-dev",
"LambdaConfig": {
"PostConfirmation": "arn:aws:lambda:us-east-2:000000000000:function:syncToHasura"
},
"LastModifiedDate": "2021-03-27T05:41:07-06:00",
"CreationDate": "2021-03-27T05:41:07-06:00"
}
]
}
const {
CognitoIdentityServiceProvider,
CognitoIdentity
} = require('aws-sdk');
var AWS = require('aws-sdk');
(async function() {
//TODO: cant share this code but just loads AWS SDK credentials
process.env.STAGE = 'dev';
const endpoint = 'http://localhost:4566';
const region = 'us-east-2';
AWS.config = {
credentials: {
accessKeyId: "local",
secretAccessKey: "local",
},
endpoint: endpoint,
region: region,
}
console.log('-- STARTING --');
const cognito = new CognitoIdentityServiceProvider({
endpoint,
region
});
const identity = new CognitoIdentity({
endpoint,
region
});
let userpool = null;
const poolName = 'sunroom-dev';
console.log('-- CREATING USER POOL OR FINDING IT --');
try {
userpool = await cognito.createUserPool({
PoolName: poolName,
LambdaConfig: {
'PostConfirmation': "arn:aws:lambda:us-east-2:000000000000:function:syncToHasura"
}
}).promise();
} catch (err) {
console.log(err);
const pools = await cognito.listUserPools({
MaxResults: 25
}).promise();
const pool = pools.UserPools.find((p) => p.Name == poolName);
userpool = await cognito.describeUserPool({
UserPoolId: pool.Id
}).promise();
}
const pools = await cognito.listUserPools({
MaxResults: 25
}).promise();
console.log(pools);
if (userpool == null) {
throw new Error('cant find pool at all');
}
let client = null;
const clientName = 'sunroom-dev-client';
console.log('-- CREATING USERPOOL CLIENT OR FINDING IT --');
try {
client = await cognito.createUserPoolClient({
UserPoolId: userpool.UserPool.Id,
ClientName: clientName,
GenerateSecret: false,
ExplicitAuthFlows: [
'ALLOW_ADMIN_USER_PASSWORD_AUTH'
]
}).promise();
} catch (err) {
console.log(err);
const clients = await cognito.listUserPoolClients({
UserPoolId: userpool.UserPool.Id
}).promise();
const tempClient = clients.UserPoolClients.find((c) => c.ClientName == clientName);
client = await cognito.describeUserPoolClient({
UserPoolId: userpool.UserPool.Id,
ClientId: tempClient.ClientId
}).promise();
}
const clients = await cognito.listUserPoolClients({
UserPoolId: userpool.UserPool.Id
}).promise();
console.log(clients);
if (client == null) {
throw new Error('cant find client');
}
console.log('-- CREATING IDENTITY POOL CLIENT OR CREATING IT --');
let identitypool = null;
const identitypoolName = 'sunroom-dev-identity-pool';
try {
identitypool = await identity.createIdentityPool({
IdentityPoolName: identitypoolName,
AllowUnauthenticatedIdentities: true,
CognitoIdentityProviders: [{
ProviderName: 'test',
ClientId: client.UserPoolClient.ClientId
}]
}).promise();
} catch (err) {
console.log(err);
const idpools = await identity.listIdentityPools({
MaxResults: 25
}).promise();
const id = idpools.IdentityPools.find((i) => i.IdentityPoolName == identitypoolName);
identitypool = await identity.describeIdentityPool({
IdentityPoolId: id.IdentityPoolId
}).promise();
}
const idpools = await identity.listIdentityPools({
MaxResults: 25
}).promise();
console.log(idpools);
if (identitypool == null) {
throw new Error('cant find ID pool');
}
console.log('-- CREATING USER --');
const username = 'test@test.com';
const password = 'Password1234!';
const res = await cognito.adminCreateUser({
UserPoolId: userpool.UserPool.Id,
Username: username,
MessageAction: 'SUPPRESS',
UserAttributes: []
})
.promise();
const user = res.User;
console.log('-- FORCING PASSWORD --');
await cognito.adminSetUserPassword({
Password: password,
Permanent: true,
UserPoolId: userpool.UserPool.Id,
Username: user.Username
})
.promise();
console.log('-- ATTEMPT LOGIN --');
const loginRes = await cognito.adminInitiateAuth({
UserPoolId: userpool.UserPool.Id,
AuthFlow: 'ADMIN_USER_PASSWORD_AUTH',
ClientId: client.UserPoolClient.ClientId,
AuthParameters: {
USERNAME: username,
PASSWORD: password,
}
})
.promise();
console.log(loginRes);
var CognitoExpress = require('cognito-express');
var cognitoExpress = new CognitoExpress({
cognitoUserPoolId: userpool.UserPool.Id,
tokenUse: 'id', //Possible Values: access | id
tokenExpiration: 3600000, //Up to default expiration of 1 hour (3600000 ms)
region: "us-east-2",
endpoint: endpoint
});
var accessToken = loginRes.AuthenticationResult.AccessToken;
console.log(accessToken);
cognitoExpress.validate(accessToken, function(err, response) {
/** Mocked for testing */
// console.log('fake-token-expired', context.req.headers['fake-token-expired']);
// if (context.req.headers['fake-token-expired'] === 'true') {
// const mockError = {
// code: 'TokenExpiredError',
// name: 'TokenExpiredError',
// message: 'Token has expired',
// expiredAt: Date.now(),
// };
// console.error('Error validating accessToken', mockError.name || err);
// context.viewer = null;
// context.authTokenExpired = (err || mockError)?.name === 'TokenExpiredError';
// context.authError = err || mockError;
// }
/** Mocked for testing */
if (err) {
console.error('Error validating accessToken', err);
context.viewer = null;
context.authTokenExpired = err.name === 'TokenExpiredError';
context.authError = err;
} else {
context.viewer = response;
}
resolve();
});
})();
{
"main": "src/index.js",
"scripts": {
"start": "micro",
"start:doppler": "doppler run -- micro",
"dev": "doppler run -- micro-dev",
"format": "prettier --write \"**/*.{js,json}\"",
"check-format": "prettier --check \"**/*.{js,json}\"",
"precommit": "lint-staged"
},
"dependencies": {
"amazon-cognito-identity-js": "^4.5.9",
"aws-sdk": "^2.835.0",
"cognito-express": "^2.0.18",
"cognito-local": "^2.1.0",
"graphql-request": "^3.4.0",
"graphql-tools": "^7.0.2",
"graphql-type-json": "^0.3.2",
"iap": "^1.1.1",
"jwt-decode": "^3.1.2"
},
"lint-staged": {
"**/*.{js,json}": [
"prettier --write"
]
},
"husky": {
"hooks": {
"pre-commit": "npm run precommit",
"post-commit": "git update-index --again"
}
},
"devDependencies": {
"@aws-cdk/aws-lambda": "^1.95.1",
"@aws-cdk/core": "^1.95.1"
}
}
docker-compose up
npm i
node index.js
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment