Otavio de Souza Rocha
Otavio de Souza Rocha

Reputation: 203

Verify if Token JWT is valid

I'm using the Slim Framework to develop the backend. But I can not find a way to compare the token generated by my login function:

public function login($request, $response){
    $key = $this->container['key'];
    $email = $request->getParsedBody()['email'];
    $senha = $this->salt . $request->getParsedBody()['senha'];

    $usuario = $this->em->getRepository(UsuarioEntity::class)->findOneBy(['email' => $email]);

    if(empty($usuario) || !password_verify($senha, $usuario->getSenha())) {
      return $response->withJson('Usuario sem permissão de acesso', 401);
    }

    $token = array(
      "session" => password_hash($usuario->getId() . 'f*u87', PASSWORD_BCRYPT),
      "id" => $usuario->getId(),
      "iat" => time(),
      "exp" => time() + (60 * 10)
    );

    $jwt = \Firebase\JWT\JWT::encode($token, $key);
    return $response->withJson($jwt, 200);
}

On the front-end (React) I call a JS class that handles all requests. I get and store the token value, but I do not know how to use it to check if user is logged in or not

Requisition.js

axiosPost(funcao,dados){
    //A AUTENTICAÇÃO VAI AQUI
    return axios.post(config.urlBase + funcao, dados);
}

setToken(token){
    this.token = token;
}

getToken(){
    return this.token;
}

LoginEmpresa.js(React Component)

login(){
    var reqAxios = new Requisicoes();
    reqAxios.axiosPost('login',{ email: this.state.email, senha: this.state.senha }).then(res => {
      if(res.data){
        reqAxios.setToken(res.data);
      }else{
        [...]
      }
    })
}

Thanks

Upvotes: 1

Views: 3298

Answers (2)

Tom Van Rompaey
Tom Van Rompaey

Reputation: 3586

You can check if the JWT is valid by doing a request to the backend API.

public function getUser($request, $response){
    $user = // GET CURRENT LOGGED IN USER BASED ON THE JWT

    if(!$user) {
      return $response->withJson('user is not logged in', 401);
    }

    return $response->withJson($user, 200);
}

On the React part, you can do a request to the API to get the currently logged in user.

  • If you receive a 200 response with a user -> logged in
  • If you receive a 401 response -> not logged in

You can use a response interceptor from Axios to check the status code:

axios.interceptors.response.use(function (response) {
    // Do something with response data
    return response;
  }, function (error) {
    // Do something with response error
    if (error.status === 401) {
      // DELETE YOUR TOKEN 
      this.removeToken();
    }
    return Promise.reject(error);
});

Also, I recommend you to store the token in localStorage so that the session of a user won't expire on a page refresh.

setToken(token){
    localStorage.setItem('jwt_token', token);
}

getToken(){
    return localStorage.getItem('jwt_token');
}

removeToken(){
    localStorage.removeItem('jwt_token');
}

Upvotes: 2

Murilo Cruz
Murilo Cruz

Reputation: 2521

As your front end is a React app, on the login response, you should store the token on your app's state. You may have it on the main component of your app or in a redux store, or anywhere else.

It is also good to think about storing the JWT on the localStorage, to ensure the user keeps logged in between multiple tabs on your application.

And if you are using the JWT protocol, you should be configuring your axios instance to send the Authorization HTTP header with the token inside. I don't see it on the piece of code you've provided

Upvotes: 1

Related Questions