JSON Webtoken登录授权以做出反应并表达受保护的路由 [英] JSON webtoken login authorisation for react and express protected routes

查看:79
本文介绍了JSON Webtoken登录授权以做出反应并表达受保护的路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在努力使用JSON Web令牌构建登录系统.

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

我已经完成了调用我的server.js文件的登录(客户端).

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

这是通过客户端的登录下面是我的句柄提交函数,它调用server.js登录路由.如何在此处使用令牌?

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);
  }

这是我的server.js的登录路径.如您所见,我已经分配了一个jwt,但是如何将其发送回我的登录表单,并将其用于受保护的路由.

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");
  }
});

基本上,我想要做的只是调用我的提交处理程序进行登录.服务器返回一个jwt令牌,然后该令牌可用于验证其他路由.

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. 使用React-Redux和react-router.
  2. 将获取的JWT令牌保存到localStorage中,并用于验证路由组件中的路由.

我建议使用React-Redux/React-router进行受保护的路由. 这是指向使用React by构建Real Web App 雷姆·佐洛蒂赫(Rem Zolotykh)

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

这将为您提供帮助.

这篇关于JSON Webtoken登录授权以做出反应并表达受保护的路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆