Search code examples
reactjsrestauthenticationrefresh-token

How can I use refresh token


I have a get refresh token api like this http://token.net/api/auth/refresh-token . I want to use it in my login function but to be honest I don't know anything about refresh tokens. how can I implement the refresh token into this.

LoginAuth.js

export const useLogin = () => {

    const LoginAuth = async (data: AuthenticationProps) => {
        await axios.post(`client.com/auth/login`,
        {
            email: data.email,
            password: data.password,
        },
        {
            headers: {
                "Content-Type": "application/json",
                Accept: "application/json",
            }
        }
        )
        .then((res) => {
            if(res.status === 200) {
                console.log("works");
            }
        }, (err) => {
            console.log(err);
        })
        
    }
    return {
        LoginAuth,
    }
}

Solution

  • Refresh token is used to generate new access token for an application. If the access token has an expiration date, once it expires, the user would have to authenticate again to obtain an access token.

    Steps:

    • After successful login response, store token in localStorage.
    • Add axios response interceptor method axios.interceptors.response to call refresh_token API and update localStorage with new access_token.
    • whenever token will get expired, API call will returnINVALID_TOKEN code in response and refresh_token API will be called.

    Now, further any API will be called with new refreshed token.