NodeJS local testing setup for Amazon Connect Hosted Widget JWT Authentication (documentation)
- NodeJS: v16+
- JWT Algorithm: HS256
- 1a. Follow the documentation to create your widget: https://docs.aws.amazon.com/connect/latest/adminguide/add-chat-to-website.html
- 1b. Save the JWT Security key generated by Amazon Connect
- 1c. Update the
const MY_SECRET = '<jwtSecret_REPLACE_ME>';
inapp.js
- 2a. Copy/paste your widget snippet code
<script type="text/javascript">
(function(w, d, x, id){
s=d.createElement('script');
s.src='https://asdfasdf.cloudfront.net/amazon-connect-chat-interface-client.js';
s.async=1;
s.id=id;
d.getElementsByTagName('head')[0].appendChild(s);
w[x] = w[x] || function() { (w[x].ac = w[x].ac || []).push(arguments) };
})(window, document, 'amazon_connect', '<widgetId_REPLACE_ME>');
amazon_connect('styles', { iconType: 'CHAT_VOICE', openChat: { color: '#ffffff', backgroundColor: '#123456' }, closeChat: { color: '#ffffff', backgroundColor: '#123456'} });
amazon_connect('snippetId', '<snippetId_REPLACE_ME>');
<script/>
- 2b. Add the
authenticate
callback, and add the widgetId from previous step
amazon_connect('authenticate', function(callback) {
const widgetId = '<replaceMe>';
window.fetch(`/token?widgetId=${widgetId}`).then(res => {
res.json().then(data => {
console.log(data.data);
callback(data.data);
});
});
});
git clone https://github.com/spenlep-amzn/amazon-connect-hosted-widget-jwt-testing-setup-nodejs.git
cd amazon-connect-hosted-widget-jwt-testing-setup-nodejs
npm install
npm run start
# App running on http://localhost:3000
Open http://localhost:3000 in your browser, and connect to an Agent!
Using the JWT setup, you can also pass contact attributes to your flow (documentation)
If you desire to pass data for contactAttributes from your website, update the Hosted Widget script snippet:
<script type="text/javascript">
(/* ... */)(window, document, 'amazon_connect', '<widgetId_REPLACE_ME>');
amazon_connect('authenticate', function(callback) {
const widgetId = '<widgetId_REPLACE_ME>';
const data = {
};
fetch(`/token?widgetId=${widgetId}`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
})
.then(res => res.json())
.then(data => {
callback(data.data); // the encoded token
});
});
</script>
Pass data in the attributes
key in the JWT payload
const payload = {
sub: widgetId,
iat: DateTime.utc().toSeconds(),
exp: DateTime.utc().plus(durationInSeconds).toSeconds(),
+ attributes: { Foo: 'bar' }
};
const header = {
typ: 'JWT',
alg: JWT_ALGORITHM,
};
const encoded_token = jwt.sign(payload, MY_SECRET, { algorithm: JWT_ALGORITHM, header });
You can access these attributes in the "UserDefined" namespace, example $Attrbitues.Foo
- 3a. Download the test-contractAttribute-flow.json file
- 3b. Import the Contact Flow (documentation)
- 3c. Update your widget settings to use the new Contact Attributes flow (documentation)