最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How can I use refresh token in react - Stack Overflow

programmeradmin1浏览0评论

I have a get refresh token url like this client/api//auth/refresh-token. but I have a hard time using this. I think it should save a refresh token in the local storage after the login. but how can I use it?

login.tsx

export const useLogin = () => {

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

I have a get refresh token url like this client.com/api//auth/refresh-token. but I have a hard time using this. I think it should save a refresh token in the local storage after the login. but how can I use it?

login.tsx

export const useLogin = () => {

    const LoginAuth = async (data: AuthenticationProps) => {
        await axios.post(baseURL + `client/auth/login`,
        {
            email: data.email,
            password: data.password,
        },
        {
            headers: {
                "Content-Type": "application/json",
                Accept: "application/json",
            }
        }
        )
        .then((res) => {
            if(res.status === 200) {
                console.log("success")
            }
        }, (err) => {
            console.log(err);
        })
        
    }
    return {
        LoginAuth,
    }
}
Share Improve this question edited May 31, 2022 at 12:59 General Grievance 4,98838 gold badges37 silver badges55 bronze badges asked May 27, 2022 at 19:45 Julia SchaferJulia Schafer 4271 gold badge7 silver badges19 bronze badges 0
Add a comment  | 

6 Answers 6

Reset to default 8 +50

You should not set the refresh token in local storage, it would cause a security vulnerability, since local storage is accessible by javascript, and since refresh token is long term token (live longer than access token), what you would do is, to store access token in local storage, since access token is short termed token, storing in local storage or cookies is totally fine, and then you should make an useEffect() call in react, that check whenever the token is expired and then make the call, a small example:

import Cookies from 'js-cookie';
axios.get("ur_url_here/",data,{withCredentials:true}).then((res)=>{
                Cookies.set(res.data.access) // assuming the response has the access token
        
}))

// now we check the expiration of access token

useEffect(()=>{
   if(!(Cookies.get("access"))){
      axios.get("refresh_url_here/",{withCredentials:true}).then((res)=>{
        Cookies.set(res.data.access)
})
/*what you do here, is try to have a 
resource/view in your backend that has 
the refresh token and make request to it 
so that it gives you a new access token, 
because refresh token should be in cookies tagged with `httponly', 
then you can send the access token to client side 
as a response and set it somewhere.
*/
}
   else{
      //do something else
}
},[])

this is a simplified code, but should explain well the idea of refreshing a token safely.

also note, i stored access in cookies, but you can do the same and store it in local storage.

Save it in local storage

export const storeToken = async (token: string) => {
  await AsyncStorage.setItem('@token', token);
};

And fetch from storage when needed

export const getToken = async () => {
  return await AsyncStorage.getItem('@token');
};

You should probably fetch the token from storage when application starts or when fetching from the API and store it in state or such while using the application.

Save in web storage

Only strings can be stored in web storage

LocalStorage

Persists even when the browser is closed and reopened.

Get

const token = localStorage.getItem('token');

Set

localStorage.setItem('token', 'value')

SessionStorage

Data removed when browser closed

Get

sessionStorage.getItem('token', 'value')

Set

sessionStorage.setItem('token', 'value')

You can use LocalStorage, or SessionStorage.

export const useLogin = () => {

    const LoginAuth = async (data: AuthenticationProps) => {
        await axios.post(baseURL + `client/auth/login`,
        {
            email: data.email,
            password: data.password,
        },
        {
            headers: {
                "Content-Type": "application/json",
                Accept: "application/json",
            }
        }
        )
        .then((res) => {
            if(res.status === 200) {
                console.log("success")
                window.localstorage.setItem('authToken', res.data.token);
                // Same as session storage
                // window.localstorage.setItem('authToken', res.data.token);
            }
        }, (err) => {
            console.log(err);
        })
        
    }
    
    return {
        LoginAuth,
    }
}

You can check here for the difference

The best way to store the refresh token is in localstorage.

Setting token in localstorage,

localStorage.setItem("token", token); 

Getting token from localstorage

let token = localStorage.getItem("token");

You can also view the stored token in browser like below,

All the measures of security of web application logic process conclude by giving you access token and refresh token, then and its your responsibility to keep them safe. As long as these tokens are valid, they are only artifacts required to make an access. In fact if you look at OIDC flows the access token is not even handed to browsers in most of them because of so many known weaknesses of browsers in terms in security.

The best way to keep or store either of these tokens is to deal with them in back channel and if not then in browsers encrypt them with custom logic and store in local storage so that only your app knows how to use these tokens.

Better even to have the backend code does this part for you as you know javascript is always exposed and retrievable.

Hope this helps.

发布评论

评论列表(0)

  1. 暂无评论