Reputation: 471
I have a react app and I am using Cognito to handle user's authentication. I need to know how do I make a call to Cognito with the refresh token so that it gives me back a new token?
I looked into all of the examples from Cognito and they didn't work. They are using dependencies that I don't have and they don't clearly list how to get them.
Can someone please help?
Upvotes: 5
Views: 3821
Reputation: 444
You can write the client from scratch as Henry suggests or you can use a library and you're good to go.
We've been using this package: https://www.npmjs.com/package/amazon-cognito-identity-js
It worked just fine. If it doesn't work for you due to some mysterious dependencies problem, please elaborate a little bit more about that. Maybe we'll figure that out.
Upvotes: 2
Reputation: 15662
From the documentation, to exchange a refresh token for an access token, you need to make a POST request to the token endpoint oauth2/token
. See section 'Exchanging a Refresh Token for Tokens' here: https://docs.aws.amazon.com/cognito/latest/developerguide/token-endpoint.html
You can use the Fetch API to make requests simply. Here are the docs on it: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API.
Since token requests involve sending your client id and client secret to AWS cognito, I'd recommend not making this request in React directly. If you did do this in React, it would be possible for someone to find your client id and client secret, and make requests that look like they are coming from your application.
Instead you should have React ask your server to make the request and return the response it receives.
Here's an example:
On the server side, you can make a route like /api/aws/tokens/refresh
or something like that, which expects a refreshToken
in the request body. Then the controller for that route can call this method:
async getAccessToken(refreshToken) {
const endpoint = 'https://mydomain.auth.us-east-1.amazoncognito.com/oauth2/token';
const options = {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': `Basic ${btoa(CLIENT_ID:CLIENT_SECRET)}`
},
body: JSON.stringify({
grant_type: 'refresh_token',
client_id: CLIENT_ID,
refresh_token: refreshToken
})
}
const response = await fetch(endpoint, options);
return response;
}
Note that the Authorization uses the method btoa
, which base64 encodes its input.
On the client side, your React app can call your server like this:
async getAccessToken(refreshToken) {
const endpoint = '/api/aws/tokens/refresh';
const options = {
method: 'POST',
body: JSON.stringify({
refreshToken: refreshToken
})
}
const response = await fetch(endpoint, options);
// store the tokens or return them
}
There are other ways to separate the work of your server an client on this problem, and many things to configure to have this all work, but hopefully this is helpful for getting started.
Upvotes: 4