JSON webtoken login authorisation for react and express protected routes

冷暖自知 提交于 2020-01-25 06:41:31

问题


I am struggling to make a login system using JSON web tokens.

I have made the login (client side) that calls to my server.js file.

This is the login through the client side Below is my handle submit function that calls the server.js login route.How would I use a token here?


  handleSubmit(e) {
    e.preventDefault();
    if (this.state.email.length < 8 || this.state.password.length < 8) {
      alert(`please enter the form correctly `);
    } else {
      const data = { email: this.state.email, password: this.state.password };

      fetch("/login", {
        method: "POST", // or 'PUT'
        headers: {
          Accept: "application/json, text/plain, */*",
          "Content-Type": "application/json"
        },
        body: JSON.stringify(data)
      })
        .then(data => {
          console.log("Success:", data);
        })

        .catch(error => {
          console.error("Error:", error);
        });
    }
  }
  catch(e) {
    console.log(e);
  }

This is the login route for my server.js. As you can see I have assigned a jwt but how would I send this back to my login form and utilise it for protected routes.

app.post("/login", async (req, response) => {
  try {
    await sql.connect(config);

    var request = new sql.Request();
    var Email = req.body.email;
    var Password = req.body.password;

    console.log({ Email, Password });

    request.input("Email", sql.VarChar, Email);
    request.input("Password", sql.VarChar, Password);

    const result = await request.execute("dbo.LoginUser");

    if (result.recordsets[0].length > 0) {
      console.info("/login: login successful..");
      console.log(req.body);

      const token = jwt.sign({ user: Email }, "SECRET_KEY", {
        expiresIn: 3600000
      });

      var decoded = jwt.verify(token, "SECRET_KEY");
      console.log(decoded);

      response.status(200).json({
        ok: true,
        user: Email,
        token: token
      });

      console.log(token);
    } else {
      console.info("/login: bad creds");
      response.status(400).send("Incorrect email and/or Password!");
    }
  } catch (err) {
    console.log("Err: ", err);
    response.status(500).send("Check api console.log for the error");
  }
});

Essentially all I want is for my submit handler to be called for login. Server returns a jwt token which can then be used to verify other routes.


回答1:


There are two ways to route:

  1. Use React-Redux and react-router.
  2. Save the fetched JWT token into localStorage and use to validate route within your routes component.

I would recommend in using React-Redux / React-router for protected routing. Here is a video link to Build Real Web App with React by Rem Zolotykh

This will help you.



来源:https://stackoverflow.com/questions/59838186/json-webtoken-login-authorisation-for-react-and-express-protected-routes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!