session authentication mechanism

Front-end identity authentication is mainly divided into two types, one is Session identity authentication, and the other is JWT identity authentication.

It is recommended to use the session authentication mechanism for server-side rendering

It is recommended to use the JWT authentication mechanism for front-end and back-end separation

This blog describes the session authentication mechanism. Before understanding the session authentication mechanism, you need to understand the following

(1) HTTP stateless

 (2)Cookie

The role of cookies in identity authentication

 Cookies are not secure

 Improve the security of identity authentication

(3) Working principle of Session authentication (important!!!) 

(4) Use session authentication in Express 

 

 

The complete case is as follows

app.js code:

// 导入express包
const express = require('express');
// 创建web服务器
const app = express();
// 托管静态资源
app.use(express.static('./pages'))
    // 导入session包
const session = require('express-session');
// 解析 POST 提交过来的表单数据
app.use(express.urlencoded({ extended: false }))
    // 配置session中间件
app.use(session({
        secret: 'sy',
        resave: false,
        saveUninitialized: true
    }))
    // 将登录成功的用户信息保存在session中
app.post('/login', (req, res) => {
        console.log(req.body);
        if (req.body.username !== 'sy' || req.body.password !== '123456') {
            return res.send({ status: 1, msg: '登录失败' });
        }
        // 将登录成功的用户信息保存到session中
        req.session.user = req.body;
        // 将用户状态保存到session中
        req.session.islogin = true;
        res.send({ status: 0, msg: '登录成功!' });
    })
    // 获取用户姓名的接口
app.get('/username', (req, res) => {
        if (!req.session.islogin) {
            return res.send({ status: 1, msg: 'fail' });
        }
        res.send({ status: 0, msg: 'success', username: req.session.user.username });
    })
    // 退出登录的接口
app.post('/logout', (req, res) => {
    // 清空session信息 注意:只会清空当前用户的session不会清空其他用户的
    req.session.destroy();
    res.send({ status: 0, msg: '退出登录成功' });
})
app.listen(80, () => {
    console.log('hahaha');
})

index.html code:

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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>后台主页</title>
    <script src="./jquery.js"></script>
</head>

<body>
    <h1>首页</h1>

    <button id="btnLogout">退出登录</button>

    <script>
        $(function() {
            // 页面加载完成后,自动发起请求,获取用户姓名
            $.get('/username', function(res) {
                // status 为 0 表示获取用户名称成功;否则表示获取用户名称失败!
                if (res.status !== 0) {
                    alert('您尚未登录,请登录后再执行此操作!')
                    location.href = './login.html'
                } else {
                    alert('欢迎您:' + res.username)
                }
            })

            // 点击按钮退出登录
            $('#btnLogout').on('click', function() {
                // 发起 POST 请求,退出登录
                $.post('/logout', function(res) {
                    if (res.status === 0) {
                        // 如果 status 为 0,则表示退出成功,重新跳转到登录页面
                        location.href = './login.html'
                    }
                })
            })
        })
    </script>
</body>

</html>

login.html code:

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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>登录页面</title>
    <script src="./jquery.js"></script>
</head>

<body>
    <!-- 登录表单 -->
    <form id="form1">
        <div>账号:<input type="text" name="username" autocomplete="off" /></div>
        <div>密码:<input type="password" name="password" /></div>
        <button>登录</button>
    </form>

    <script>
        $(function() {
            // 监听表单的提交事件
            $('#form1').on('submit', function(e) {
                // 阻止默认提交行为
                e.preventDefault()

                // 发起 POST 登录请求
                $.post('/login', $(this).serialize(), function(res) {
                    // status 为 0 表示登录成功;否则表示登录失败!
                    if (res.status === 0) {
                        location.href = './index.html'
                    } else {
                        alert('登录失败!')
                    }
                })
            })
        })
    </script>
</body>

</html>

Guess you like

Origin blog.csdn.net/qq_43781887/article/details/127290652