I am developing Role-based access control with JWT.
I have tried the example code in the following article (‘Usage’ section).
But I found out that the default expiration period is only 3600sec (1hour).
The following image is a Chrome screenshot of localStorage (expires_in: 3600).
1 hour is is too short for my application.
Is there any way to change the expiration period from 1 hour to longer value (for example 1 day, or 1 week).
I have already read the following articles and documents, but I could not find any information related to my topic.
You’ve two ways to go about this:
-
If you’re on the Business plan, you can set a custom JWT secret. You can use that secret to sign custom JWT tokens with a longer expiration time.
-
On the lower plans, you have to make use of the ‘refresh_token’. You need to send a request like:
axios({
data: `grant_type=refresh_token&refresh_token=${JSON.parse(localStorage.getItem('gotrue.user')).token.refresh_token}`,
method: 'post',
url: 'https://site.netlify.app/.netlify/identity/token'
}).then(({data}) => {
save(data)
}).catch(({response: {data}}) => {
console.log(data)
})
save(token) {
return new Promise((resolve, reject) => {
axios({
headers: {
authorization: `Bearer ${token.access_token}`
},
url: 'https://site.netlify.app/.netlify/identity/user'
}).then(({data}) => {
localStorage.setItem('user', JSON.stringify({
...data,
token: {
...token,
expires_at: Date.now() + 3000000
},
url: 'https://site.netlify.app/.netlify/identity'
}))
resolve()
}).catch(error => {
reject(error)
})
})
}
If you’re using Netlify Identity Widget, I believe this is taken care of automatically, but if you’re using a custom solution, you might have to rely on the above example (also used in a custom solution).