一个简单的JWT使用示例

34次阅读

共计 2689 个字符,预计需要花费 7 分钟才能阅读完成。

一个简单的 JWT 使用示例

准备

npm i --save koa koa-route koa-bodyparser @koa/cors jwt-simple

服务端代码

const Koa = require("koa");
const app = new Koa();
const route = require('koa-route');
var bodyParser = require('koa-bodyparser');
const jwt = require('jwt-simple');
const cors = require('@koa/cors');

const secret = 'your_secret_string'; // 加密用的 SECRET 字符串,可随意更改
app.use(bodyParser()); // 处理 post 请求的参数

const login = ctx => {
    const req = ctx.request.body;
    const userName = req.userName;
    const expires = Date.now() + 3600000; // 设置超时时间为一小时后
    
    var payload = { 
        iss: userName,
        exp: expires
    };
    const Token = jwt.encode(payload, secret);
    ctx.response.body = {
        data: Token,
        msg: '登陆成功'
    };
}
const getUserName = ctx => {
    const reqHeader = ctx.request.headers;
   
    const token = reqHeader.authorization.split(" ")[1];
    var decoded = jwt.decode(token, secret);
    ctx.response.body = {
        data: {username: decoded.iss,},
        msg: '获取用户名成功'
    };
}
app.use(cors());
app.use(route.post('/login', login));
app.use(route.get('/getUsername', getUserName));
app.listen(3200, () => {console.log('启动成功');
});

客户端代码

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>JWT-demo</title>
    <style>
        .login-wrap {
            height: 100px;
            width: 200px;
            border: 1px solid #ccc;
            padding: 20px;
            margin-bottom: 20px;
        }
    </style>
</head>

<body>
    <div class="login-wrap">
        <input type="text" placeholder="用户名" class="userName">
        <br>
        <input type="password" placeholder="密码" class="password">
        <br>
        <br>
        <button class="btn"> 登陆 </button>
    </div>
    
    <button class="btn1"> 获取用户名 </button>
    <p class="username"></p>
</body>
<script>
    var btn = document.querySelector('.btn');
    
    btn.onclick = function () {var userName = document.querySelector('.userName').value;
        var password = document.querySelector('.password').value;
        fetch('http://localhost:3200/login', {
            method: 'POST', 
            body: JSON.stringify({
                userName,
                password
            }),
            headers:{'Content-Type': 'application/json'},
            mode: 'cors' // no-cors, cors, *same-origin
        })
            .then(function (response) {return response.json();
            })
            .then(function (res) {
                // 获取到 Token, 将 Token 放在 localStorage
                document.cookie = `token=${res.data}`;
                localStorage.setItem('token', res.data);
                localStorage.setItem('token_exp', new Date().getTime());
                alert(res.msg);
                console.log('本地测试', res);
            })
            .catch(err => {console.error('本地测试错误', err);
            });
    }
    var btn1 = document.querySelector('.btn1');
    btn1.onclick = function () {var username = document.querySelector('.username');
        const token = localStorage.getItem('token');
        fetch('http://localhost:3200/getUsername', {
            headers:{'Authorization': 'Bearer' + token},
            mode: 'cors' // no-cors, cors, *same-origin
        })
            .then(function (response) {return response.json();
            })
            .then(function (res) {console.log('返回用户名结果', res);
                username.innerHTML = ` 姓名:${res.data.username}`;
            })
            .catch(err => {console.error('本地测试错误', err);
            });
    }
</script>

</html>

运行代码

其他

以上只是一个特别简单的例子,很多边界条件没有做处理,比如未登陆的校验,异常的处理,Token 过期的判断;

正文完
 0