Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

React Native Invalid Token Specified #79

Closed
unblvdl opened this issue Sep 27, 2019 · 3 comments
Closed

React Native Invalid Token Specified #79

unblvdl opened this issue Sep 27, 2019 · 3 comments

Comments

@unblvdl
Copy link

unblvdl commented Sep 27, 2019

Hi, I'm struggling with jwt-decode in my react native app, whenever I start expo i get Invalid Token Specified error, what am i missing? Here is my code:

var jwt_decode = require('jwt-decode');
import { AsyncStorage } from 'react-native';
const initialState = {
  user: null
};
if (AsyncStorage.getItem('jwtToken')) {
  const decodedToken = jwt_decode(AsyncStorage.getItem('jwtToken'));

  if (decodedToken.exp * 1000 < Date.now()) {
    AsyncStorage.removeItem('jwtToken');
  } else {
    initialState.user = decodedToken;
  }
}

const AuthContext = createContext({
  user: null,
  login: (userData) => {},
  logout: () => {}
});

function authReducer(state, action) {
  switch (action.type) {
    case 'LOGIN':
      return {
        ...state,
        user: action.payload
      };
    case 'LOGOUT':
      return {
        ...state,
        user: null
      };
    default:
      return state;
  }
}

function AuthProvider(props) {
  const [state, dispatch] = useReducer(authReducer, initialState);

  login = async (userData) => {
    try{
      await AsyncStorage.setItem('jwtToken', userData.token);
      dispatch({
      type: 'LOGIN',
      payload: userData
    });
  } catch(e) {
    // save error
  }
  }

  logout = async () => {
    try{
    await AsyncStorage.removeItem('jwtToken');
    dispatch({ type: 'LOGOUT' });
    } catch(e) {
      // save error
    }
  }

  return (
    <AuthContext.Provider
      value={{ user: state.user, login, logout }}
      {...props}
    />
  );
}

export { AuthContext, AuthProvider };`

@toelapiut
Copy link

I had the same issue with keycloak but i realized that the package that i was using had already decoded the token for me. I believe you cant decode the token twice

@Widcket
Copy link
Contributor

Widcket commented Jan 15, 2020

Going to close this one, if this is still an issue please reply with additional information or just a ping.

@Widcket Widcket closed this as completed Jan 15, 2020
@Thomasosho
Copy link

I had the same issue with keycloak but i realized that the package that i was using had already decoded the token for me. I believe you cant decode the token twice

This solved my issue, Thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants