Skip to content

Instantly share code, notes, and snippets.

@BerndWessels
Created May 26, 2019 21:13
Show Gist options
  • Save BerndWessels/322f0d74655394cbf752534705c8e54e to your computer and use it in GitHub Desktop.
Save BerndWessels/322f0d74655394cbf752534705c8e54e to your computer and use it in GitHub Desktop.
BFF pulumi cra cognito test app
import React, {useEffect, useState} from 'react';
import logo from './logo.svg';
import './App.css';
let region = 'us-east-1';
let userPoolName = 'mybfff';
let userPoolId = 'us-east-1_xxxxxxxxx';
let userPoolAppClientId = 'xxxxxxxxxxxxxxxxxxxxxxxxxx';
let identityPoolId = 'us-east-1:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx';
let cognitoIdentityPoolUrl = 'https://cognito-identity.us-east-1.amazonaws.com';
let cognitoUserPoolLoginRedirectUrl = 'http://localhost:3000/';
let cognitoUserPoolLoginScopes = 'phone email openid profile';
let cognitoUserPoolLoginUrl = `https://${userPoolName}.auth.${region}.amazoncognito.com/login?redirect_uri=${encodeURI(cognitoUserPoolLoginRedirectUrl)}&response_type=code&client_id=${userPoolAppClientId}&identity_provider=COGNITO&scopes=${encodeURI(cognitoUserPoolLoginScopes)}`;
let cognitoUserPoolTokenUrl = `https://${userPoolName}.auth.${region}.amazoncognito.com/oauth2/token`;
function App() {
const [cognitoUserPoolAuthorizationCode, setCognitoUserPoolAuthorizationCode] = useState(null);
const [cognitoUserPoolTokens, setCognitoUserPoolTokens] = useState(null);
const [cognitoUserPoolRefreshToken, setCognitoUserPoolRefreshToken] = useState(null);
const [cognitoIdentityPoolIdentityId, setCognitoIdentityPoolIdentityId] = useState(null);
useEffect(() => {
let parsedUrl = new URL(window.location.href);
let parsedCode = parsedUrl.searchParams.get("code");
setCognitoUserPoolAuthorizationCode(parsedCode);
}, []);
const getTokensFromCode = e => {
const params = {
grant_type: 'authorization_code',
code: cognitoUserPoolAuthorizationCode,
client_id: userPoolAppClientId,
redirect_uri: cognitoUserPoolLoginRedirectUrl,
};
const searchParams = Object.keys(params).map((key) => {
return encodeURIComponent(key) + '=' + encodeURIComponent(params[key]);
}).join('&');
fetch(cognitoUserPoolTokenUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
},
body: searchParams
}).then(function (response) {
let contentType = response.headers.get("content-type");
if (contentType && contentType.includes("application/json")) {
return response.json();
}
console.log(contentType);
throw new TypeError("Oops, we haven't got JSON!",);
})
.then(function (json) { /* process your JSON further */
console.log("json", json);
setCognitoUserPoolTokens(json);
if(json.hasOwnProperty('refresh_token')) {
setCognitoUserPoolRefreshToken(json.refresh_token);
}
})
.catch(function (error) {
console.log(error);
});
};
const getTokensFromRefreshToken = e => {
const params = {
grant_type: 'refresh_token',
refresh_token: cognitoUserPoolRefreshToken,
client_id: userPoolAppClientId,
};
const searchParams = Object.keys(params).map((key) => {
return encodeURIComponent(key) + '=' + encodeURIComponent(params[key]);
}).join('&');
fetch(cognitoUserPoolTokenUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
},
body: searchParams
}).then(function (response) {
let contentType = response.headers.get("content-type");
if (contentType && contentType.includes("application/json")) {
return response.json();
}
console.log(contentType);
throw new TypeError("Oops, we haven't got JSON!",);
})
.then(function (json) { /* process your JSON further */
console.log("json", json);
setCognitoUserPoolTokens(json);
})
.catch(function (error) {
console.log(error);
});
};
const getIdentityForUser = e => {
fetch(cognitoIdentityPoolUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/x-amz-json-1.1',
'X-Amz-Target': 'AWSCognitoIdentityService.GetId',
},
body: JSON.stringify({
'IdentityPoolId': identityPoolId,
'Logins': {
[`cognito-idp.${region}.amazonaws.com/${userPoolId}`]: cognitoUserPoolTokens.id_token,
},
}),
}).then(function (response) {
let contentType = response.headers.get("content-type");
if (contentType && contentType.includes("application/x-amz-json-1.1")) {
return response.json();
}
console.log(contentType);
throw new TypeError("Oops, we haven't got JSON!",);
})
.then(function (json) { /* process your JSON further */
console.log("json", json);
setCognitoIdentityPoolIdentityId(json.IdentityId);
})
.catch(function (error) {
console.log(error);
});
};
const GetCredentialsForIdentity = e => {
fetch(cognitoIdentityPoolUrl, {
'method': 'POST',
'headers': {
'Content-Type': 'application/x-amz-json-1.1',
'X-Amz-Target': 'AWSCognitoIdentityService.GetCredentialsForIdentity',
},
'body': JSON.stringify({
IdentityId: cognitoIdentityPoolIdentityId,
'Logins': {
[`cognito-idp.${region}.amazonaws.com/${userPoolId}`]: cognitoUserPoolTokens.id_token,
},
}),
}).then(function (response) {
let contentType = response.headers.get("content-type");
if (contentType && contentType.includes("application/x-amz-json-1.1")) {
return response.json();
}
console.log(contentType);
throw new TypeError("Oops, we haven't got JSON!",);
})
.then(function (json) { /* process your JSON further */
console.log("json", json);
})
.catch(function (error) {
console.log(error);
});
};
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo"/>
<p>
Edit <code>src/App.js</code> and save to reload.
</p>
<p>
Code <code>{cognitoUserPoolAuthorizationCode}</code>
</p>
<p>
Token <code>{JSON.stringify(cognitoUserPoolTokens, null, 2)}</code>
</p>
<p>
Refresh Token <code>{JSON.stringify(cognitoUserPoolRefreshToken, null, 2)}</code>
</p>
<p>
IdentityId <code>{cognitoIdentityPoolIdentityId}</code>
</p>
<a href={cognitoUserPoolLoginUrl}>Login</a>
<button onClick={getTokensFromCode}>Get Tokens from code</button>
<button onClick={getIdentityForUser}>Get Identity for user</button>
<button onClick={GetCredentialsForIdentity}>Get Credentials for identity</button>
<button onClick={getTokensFromRefreshToken}>Get Tokens from refresh token</button>
</header>
</div>
);
}
export default App;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment