简体   繁体   English

如何在客户端 Express 应用程序中处理 jwt 令牌和 refreshtoken?

[英]How to handle jwt token and refreshtoken in a client side express application?

Hey guys i have two express applications, one is the backend where im having a rest api for all crud operations to the db.嘿伙计们,我有两个快速应用程序,一个是后端,我有一个 rest api 用于对数据库的所有 crud 操作。

The Client is also structured in a seperate express application were I only do GET requests, there im working with templates to consume data from the rest api.客户端也在一个单独的快速应用程序中构建,我只做 GET 请求,我使用模板来使用来自 rest api 的数据。

The way of login is a fetch request at the html template file, included in a script tag below of this file, because i have to set an EventListener to the login submit button and have to extract the username and password, if the login was successful i store the token into localstorage and the refreshtoken into a cookie.登录方式是 html 模板文件中的获取请求,包含在该文件下方的脚本标记中,因为我必须为登录提交按钮设置一个 EventListener 并且必须提取用户名和密码,如果登录成功我将令牌存储到本地存储中,并将刷新令牌存储到 cookie 中。

The problem is now i need the token also in the nodejs/express side to call the api and render some other data into the views but from nodejs/express i dont have access to the browsers localstorage.问题是现在我需要在 nodejs/express 端使用令牌来调用 api 并将一些其他数据渲染到视图中,但是从 nodejs/express 我无法访问浏览器的本地存储。

What can i do here, what is the right way for handeling such a case?我能在这里做什么,处理这种情况的正确方法是什么? Thank you for any help!感谢您的任何帮助!

Example: Api Call in the template for access token, this is in the views folder示例:Api 在模板中调用访问令牌,这是在视图文件夹中


<body>
<div class="login-dark">
    <form method="post" action="http://localhost:3007/auth/">
        <h2 class="sr-only">Login Form</h2>
        <div class="illustration"><i class="icon ion-ios-locked-outline" style="color: var(--success);"></i></div>
        <div class="form-group"><input class="form-control" type="email" id="email" name="email" placeholder="Email">
        </div>
        <div class="form-group"><input class="form-control" type="password" id="password" name="password"
                                       placeholder="Password"></div>
        <div class="form-group">
            <button class="btn btn-primary btn-block" id="submit" type="submit" style="background: var(--green);">Log
                In
            </button>
        </div>
        <a id="forgotPassword" class="forgot" href="#">Forgot your email or password?</a>
    </form>
    <img class="img-fluid" src="assetsLogin/img/thunderstorm-3430471_1920.jpg">
</div>
<script src="assetsLogin/js/jquery.min.js"></script>
<script src="assetsLogin/bootstrap/js/bootstrap.min.js"></script>
<script>
    submit.addEventListener("click", async (event) => {
        event.preventDefault()

        let data = {
            email: email.value,
            password: password.value
        }

        await fetch('http://localhost:3007/auth', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(data),
        }).then(response => response.json())
                .then(data => {
                            console.log(data)
                            if (data.token) {
                                document.cookie = "refreshToken=" + data.refreshtoken + "; expires=Thu, 11 Dec 2021 12:00:00 UTC";
                                localStorage.setItem("token", data.token)
                                window.location.href = 'http://localhost:3010/create';
                            }
                            else {
                                window.reload()
                            }
                        }
                );
    });
</script>
</body>

In a Express route i would to do:在 Express 路线中,我会这样做:


const express = require('express');
const router = express.Router();

router.get('/', (req, res) =>{

   // here i want to fetch first the data from api
  // but i need here the access token that is stored on browsers localstorage
  // then i want to populate this data into the view below
    res.render('view', {data from fetch});
});



In this scenario, you can do one more API call with to the server with accessToken(after successfully login) from that call get the user data and store it in local storage in the browser.在这种情况下,您可以使用 accessToken(成功登录后)对服务器再进行一次 API 调用,从该调用获取用户数据并将其存储在浏览器的本地存储中。

I hope this helps for you.我希望这对你有帮助。

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

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