obabichev / react-token-auth

84 stars 22 forks source link

How can I get raw access to the token held in local storage by react-token-auth for use in Axios? #15

Closed therealrobster closed 2 years ago

therealrobster commented 3 years ago

Hi there,

Have done a basic setup. Working well, am logged in and can conditionally render based on that.

I want to do my requests through Axios though, so can't use the authFetch method.

I therefore need to extract the token from react-token-auth and send it via Axios somewhat like this:

let myToken = react-token-auth.getLocalStorage.Token  <<---  What would I actually put here?

axios
    .post("/login", data)
    .then((response) => {
        if (response.status == "200") {

            // Alter axios defaults after instance has been created
            axios.defaults.headers.common[
                "Authorization"
            ] = `Bearer ${myToken}`;

How can I get raw access to the token held in local storage by react-token-auth?

voksar commented 3 years ago

Dont know if you still need help with this but can be accessed through the localStorage.getItem function. Eg.

token = JSON.parse(localStorage.getItem('REACT_TOKEN_AUTH_KEY'));
token.access_token // <-- This is the item you are looking for. access_token depends on how you configured CreatheAuthProvider
obabichev commented 2 years ago

In version 2 of the library the methods getSession and getSessionState are provided,

the first one returns the state (and updates the session in the case of expiration), the second one returns current state synchronously