Skip to content

Instantly share code, notes, and snippets.

@mhart
Last active March 2, 2017 16:07
Show Gist options
  • Save mhart/47be3aef030bdc7d6471bca30989b36a to your computer and use it in GitHub Desktop.
Save mhart/47be3aef030bdc7d6471bca30989b36a to your computer and use it in GitHub Desktop.
<!doctype html>
<html lang="en">
<!-- Example HTML file for AWS Proxy Resource tutorial at: https://aws.amazon.com/blogs/compute/authorizing-access-through-a-proxy-resource-to-amazon-api-gateway-and-aws-lambda-using-amazon-cognito-user-pools/ -->
<!-- Fill out your UserPoolId, ClientId and apiGatewayEndpoint in JS further below -->
<!-- Then serve locally with a static file server, such as `python -m SimpleHTTPServer` and open http://localhost:8000 -->
<head>
<meta charset="utf-8">
<title>APIGW Test</title>
<script src="https://unpkg.com/[email protected]/dist/aws-cognito-sdk.min.js"></script>
<script src="https://unpkg.com/[email protected]/dist/amazon-cognito-identity.min.js"></script>
</head>
<body>
<form action="javascript:void(0);">
<fieldset>
<legend>Login</legend>
User:<br>
<input id="user" /><br>
Password:<br>
<input id="password" /><br>
<button id="buttonAuth">Login</button><br>
</fieldset>
<fieldset>
<legend>Test API Gateway</legend>
<button id="buttonGet">Get</button> <button id="buttonPost">Post</button>
</fieldset>
</form>
<pre id="output" />
<script>
// All you need to modify is the UserPoolId, ClientId and apiGatewayEndpoint:
var poolData = {
UserPoolId : 'us-east-1_XXXXXXXXX',
ClientId : '12ioh8c17q3stmndpXXXXXXXX',
};
var apiGatewayEndpoint = 'https://XXXXXXXX.execute-api.us-east-1.amazonaws.com/prod';
// Configure the AWS client with the Cognito role and a blank identity pool to get initial credentials
AWSCognito.config.update({
region: 'us-east-1',
credentials: new AWSCognito.CognitoIdentityCredentials({IdentityPoolId: ''}),
});
var token = '';
// Authenticate user with MFA
document.getElementById('buttonAuth').addEventListener('click', function() {
var authenticationData = {
Username: document.getElementById('user').value,
Password: document.getElementById('password').value,
};
var authenticationDetails = new AWSCognito.CognitoIdentityServiceProvider.AuthenticationDetails(authenticationData);
var userPool = new AWSCognito.CognitoIdentityServiceProvider.CognitoUserPool(poolData);
var userData = {
Username: document.getElementById('user').value,
Pool: userPool,
};
var cognitoUser = new AWSCognito.CognitoIdentityServiceProvider.CognitoUser(userData);
cognitoUser.authenticateUser(authenticationDetails, {
onSuccess: function(result) {
token = result.getIdToken().getJwtToken(); // CUP Authorizer = ID Token
console.log('ID Token: ' + token);
var cognitoGetUser = userPool.getCurrentUser();
if (cognitoGetUser != null) {
cognitoGetUser.getSession(function(err, result) {
if (result) {
console.log('Authenticated!');
}
});
}
},
onFailure: function(err) {
alert(err);
},
mfaRequired: function(codeDeliveryDetails) {
var verificationCode = prompt('Please input a verification code.', '');
cognitoUser.sendMFACode(verificationCode, this);
},
});
});
// Send a GET request to the API
document.getElementById('buttonGet').addEventListener('click', function() {
var httpRequest = new AWSCognito.HttpRequest(apiGatewayEndpoint);
httpRequest.method = 'GET';
httpRequest.headers = {
'Accept': 'application/json',
'Authorization': token,
};
AWSCognito.util.handleRequestWithRetries(httpRequest, null, function(err, body) {
if (err) {
console.error(err);
document.getElementById('output').innerHTML = 'Error: ' + (err.stack || err);
} else {
var data = JSON.parse(body);
console.log(data);
document.getElementById('output').innerHTML = 'Response: ' + JSON.stringify(data, null, 2);
}
})
});
// Send a POST request to the API
document.getElementById('buttonPost').addEventListener('click', function() {
var httpRequest = new AWSCognito.HttpRequest(apiGatewayEndpoint);
httpRequest.method = 'POST';
httpRequest.headers = {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': token,
};
httpRequest.body = JSON.stringify({message: 'Sample POST payload'});
AWSCognito.util.handleRequestWithRetries(httpRequest, null, function(err, body) {
if (err) {
console.error(err);
document.getElementById('output').innerHTML = 'Error: ' + (err.stack || err);
} else {
var data = JSON.parse(body);
console.log(data);
document.getElementById('output').innerHTML = 'Response: ' + JSON.stringify(data, null, 2);
}
})
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment