nodejs 项目的session验证
原文:https://www.codexpedia.com/node-js/a-very-basic-session-auth-in-node-js-with-express-js/
---------------------------------------------------------------------------------------------------------------------
Authentication is the process of verifying if the user is in fact who he/she is declared to be. Authorization is the process of determining if the user has the privileges to access the resources he/she requested.
This node.js code snippet demonstrated a very simple example of authentication and authorization process using session in express.js. There is a login endpoint, a logout endpoint and get post page. To see the post page, you have to login first, and your identity will be verified and saved in session. When you hit the logout endpoint, it will revoke your access by removing your identity from the session.
session_auth.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
|
var express = require( 'express' ), app = express(), session = require( 'express-session' ); app.use(session({ secret: '2C44-4D44-WppQ38S' , resave: true , saveUninitialized: true })); // Authentication and Authorization Middleware var auth = function (req, res, next) { if (req.session && req.session.user === "amy" && req.session.admin) return next(); else return res.sendStatus(401); }; // Login endpoint app.get( '/login' , function (req, res) { if (!req.query.username || !req.query.password) { res.send( 'login failed' ); } else if (req.query.username === "amy" || req.query.password === "amyspassword" ) { req.session.user = "amy" ; req.session.admin = true ; res.send( "login success!" ); } }); // Logout endpoint app.get( '/logout' , function (req, res) { req.session.destroy(); res.send( "logout success!" ); }); // Get content endpoint app.get( '/content' , auth, function (req, res) { res.send( "You can only see this after you've logged in." ); }); app.listen(3000); |
To run the above code from command line
1
2
3
|
npm install express npm install express-session node session_auth.js & |
Visit these urls in a browser
localhost:3000/content
localhost:3000/login?username=amy&password=amyspassword
localhost:3000/content
localhost:3000/logout
localhost:3000/content
Code explanation
Import express and express-session modules. Create express app and add session to express app as a middleware.
1
2
3
4
5
6
7
8
|
var express = require( 'express' ), app = express(), session = require( 'express-session' ); app.use(session({ secret: '2C44-4D44-WppQ38S' , resave: true , saveUninitialized: true })); |
Authentication and authorization middleware function. Grant the next step if the user is amy and if she has the admin access. The values to check against is hardcoded for demonstration purpose. A real web app will get the user and user access level from session, and then check against the user and user access lever from a database on the server.
1
2
3
4
5
6
7
|
// Authentication and Authorization Middleware var auth = function (req, res, next) { if (req.session && req.session.user === "amy" && req.session.admin) return next(); else return res.sendStatus(401); }; |
localhost:3000/login?username=amy&password=amyspassword, the login url to check log the user in by saving the user and user access level in a session. The session will be different for each user, and also be unique for the same user using different browsers. For example, if the same user logged in using Chrome, and the open up Firefox, the user will have to login again in FireFox in order to gain protected resources. For demonstration purpose, this is a get request and passing in the info through query parameters. A real web app will usually be using a post request and passing in the data in the post form. Again the user and passwords are hardcoded here for demonstration purpose. A real web app will check the incoming user and password against the user and password stored in a database on there server.
1
2
3
4
5
6
7
8
9
10
|
// Login endpoint app.get( '/login' , function (req, res) { if (!req.query.username || !req.query.password) { res.send( 'login failed' ); } else if (req.query.username === "amy" || req.query.password === "amyspassword" ) { req.session.user = "amy" ; req.session.admin = true ; res.send( "login success!" ); } }); |
localhost:3000/logout, logout by destroy the session. Once the session is destroyed, the user will have to hit the login url again in order to gain protected resources.
1
2
3
4
5
|
// Logout endpoint app.get( '/logout' , function (req, res) { req.session.destroy(); res.send( "logout success!" ); }); |
localhost:3000/content, get the protected contents. The auth function above is passed in the second parameters as a middleware before it proceed to serve the content to the user. If the auth function determined the user is not valid, it will not proceed to the thrid function to serve the content.
1
2
3
4
|
// Get content endpoint app.get( '/content' , auth, function (req, res) { res.send( "You can only see this after you've logged in." ); }); |
Lastly, start the app by listening on port 3000.
1
2
|
app.listen(3000); |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 25岁的心里话
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现