Open Monstarrrr opened 4 months ago
Can't we just get the new access token whenever the old one is expired? Directly inside of the interceptor?
Concretely something like:
// api.ts
// ...
if (accessToken && accessToken !== 'null' && accessToken !== 'undefined') {
if (!isTokenExpired(accessToken)) {
console.log('# Access token is not expired.')
req.headers['authorization'] = `Bearer ${accessToken}`
} else if (refreshToken && refreshToken !== 'null' && refreshToken !== 'undefined') {
try {
console.log('# Access token is expired. Refreshing...');
const newAccessToken = await refreshAccessToken(refreshToken);
localStorage.setItem('access_token', newAccessToken);
req.headers['authorization'] = `Bearer ${newAccessToken}`;
(where refreshAccessToken()
is a helper function that runs a simple fetch()
call or whatever the best way to implement this would be)
Example implementation of this:
https://dev.to/koladev/fullstack-nextjs-django-authentication-django-rest-typescript-jwt-wretch-djoser-2pcf
Word search for handleJWTRefresh()
to see how they handle it more exactly.
They use wretch and not axios but the following code snippet serves as good inspiration:
const api = () => {
return (
wretch("http://localhost:8000")
// Initialize authentication with the access token.
.auth(`Bearer ${getToken("access")}`)
// Catch 401 errors to refresh the token and retry the request.
.catcher(401, async (error: WretchError, request: Wretch) => {
try {
// Attempt to refresh the JWT token.
const { access } = (await handleJWTRefresh().json()) as {
access: string;
};
// Store the new access token.
storeToken(access, "access");
...
we like that we found a reddit comment says that httpOnly is safer than localstorage or standard cookies. the article Ziggy shared says similar "Their security features, such as HttpOnly flags, making them ideal for handling authentication tokens."
Impact: 🟡 Medium
Status: 🔓 Deciding...
Deciders & Confidence:
Last updated: [DD-MM-YYYY]
Context
[Communicate what this decision is about exactly; the importance of it;]
Decision Drivers
Considered Options
[option 1]
[ description ]
:green_circle: Better [driver 1]
:orange_circle: Worse [driver 2]
:green_circle: Better [driver 3]
:green_circle: [argument A]
:green_circle: [argument B]
:orange_circle: [argument C]
[option 2]
...
Decision Outcome
Chosen option:
Reason: