简体   繁体   English

验证令牌JWT是否有效

[英]Verify if Token JWT is valid

I'm using the Slim Framework to develop the backend. 我正在使用Slim Framework开发后端。 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. 在前端(React)上,我调用了一个处理所有请求的JS类。 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 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) LoginEmpresa.js(反应组件)

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 谢谢

As your front end is a React app, on the login response, you should store the token on your app's state. 由于您的前端是React应用,因此在登录响应中,您应该将令牌存储在应用的状态中。 You may have it on the main component of your app or in a redux store, or anywhere else. 您可以将其安装在应用程序的主要组件或Redux商店中,或其他任何地方。

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. 考虑将JWT存储在localStorage上也是不错的选择,以确保用户在应用程序的多个选项卡之间保持登录状态。

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. 如果使用的是JWT协议,则应配置axios实例以发送带有令牌的Authorization HTTP标头。 I don't see it on the piece of code you've provided 我在您提供的代码段中看不到它

You can check if the JWT is valid by doing a request to the backend API. 您可以通过向后端API发出请求来检查JWT是否有效。

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. 在React部分,您可以向API发出请求以获取当前登录的用户。

  • If you receive a 200 response with a user -> logged in 如果您收到用户200回应->已登录
  • If you receive a 401 response -> not logged in 如果您收到401响应->未登录

You can use a response interceptor from Axios to check the status code: 您可以使用Axios的响应拦截器来检查状态码:

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. 另外,我建议您将令牌存储在localStorage中,以便用户会话不会在页面刷新时过期。

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

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM