原文: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);
console.log("app running at http://localhost: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);
console.log("app running at http://localhost:3000");

nodejs 项目的session验证的更多相关文章

  1. Silverlight调用网站项目的Session

    项目中遇到Silverlight调网站Session的问题了,试了几种方法,用这种方法获取到了,如果有不对不恰当的地方,还望各路大神给指正出来. 解决方法: 1.Silverlight调用网站的接口 ...

  2. 使用spring-session共享springmvc项目的session

    一.说在前面 spring mvc项目,使用nginx,tomcat部署. 之前没做session共享,而nginx采用sticky模块进行分发. 但发现有时不能正确地指向同一台服务器,从而导致ses ...

  3. [转]同一个tomcat不同项目的session共享问题

    问题描述: session常常用来存储一些公共信息供不同页面访问,比如用户登录信息.访问同一个tomcat下的不同项目所创建的session是不一样的.自然地面临了如何共享session的问题. 解决 ...

  4. nodejs项目的model操作mongo

    想想以前学习hibernate的时候,学习各种表和表之间的映射关系等一对多,多对一,多对多,后来到了工作中,勇哥告诉我, 那时在学习的时候,公司中都直接用外键关联. 这里我们学习下,如何在Nodejs ...

  5. 应用集成-在Hexo、Hugo博客框架中使用Gitalk基于Github上仓库项目的issue无后端服务评论系统实践

    关注「WeiyiGeek」公众号 设为「特别关注」每天带你玩转网络安全运维.应用开发.物联网IOT学习! 希望各位看友[关注.点赞.评论.收藏.投币],助力每一个梦想. 本章目录 目录 0x00 Gi ...

  6. 老项目的#iPhone6于iPhone6Plus适配#iPhone6分辨率与适配

    技术博客http://www.cnblogs.com/ChenYilong/    本文永久地址为http://www.cnblogs.com/ChenYilong/p/4011744.html ,转 ...

  7. 更换已存在项目的svn的地址

      CreateTime--2017年11月23日16:20:14 Author:Marydon 如何更换已存在项目的svn的地址? 参考链接:http://blog.csdn.net/sinat_2 ...

  8. PHP项目的“苦逼”经历与思考

    PHP项目的"苦逼"经历与思考 PHP零基础.但因为项目人手不够的原因,被安排到一个用户"定制"项目. 该项目是用PHP生成的统计数据报表. 而用户又有新的3个 ...

  9. maven项目的pom.xml文件详解

    <project xmlns="http://maven.apache.org/POM/4.0.0 " 2 xmlns:xsi="http://www.w3.org ...

随机推荐

  1. hdu 5783 Divide the Sequence 贪心

    Divide the Sequence 题目连接: http://acm.hdu.edu.cn/showproblem.php?pid=5783 Description Alice has a seq ...

  2. 使用 IntraWeb (16) - 基本控件之 TIWList、TIWListbox、TIWComboBox、TIWOrderedListbox

    TIWList //列表; 它对应 Html 中的 OL.LI(某些选项下会用表格模拟); TIWListbox 和 TIWComboBox 则对应 Html 在的 Option TIWListbox ...

  3. NAS系统收集

    FreeNAS®,目前最受欢迎的开源免费 NAS 操作系统之一,基于以安全和稳定著称的 FreeBSD 系统开发,由 ixsystems 公司的技术团队维护.项目地址:www.freenas.org ...

  4. 新浪微博基于MySQL的分布式数据库实践

    提起微博,相信大家都是很了解的.但是有谁知道微博的数据库架构是怎样的呢?在今天举行的2011数据库技术大会上,新浪首席DBA杨海潮为我们详细解读了新浪微博的数据库架构——基于MySQL的分布式数据库实 ...

  5. HDU 4815 Little Tiger vs. Deep Monkey(2013长春现场赛C题)

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=4815 简单的DP题. #include <stdio.h> #include <st ...

  6. HDU 4771 Stealing Harry Potter's Precious (2013杭州赛区1002题,bfs,状态压缩)

    Stealing Harry Potter's Precious Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 ...

  7. 关于pcie的备忘

    总线驱动:深度优先统计资源,深度滞后分配资源 资源包括Bus id和内存(prefectable和non-prefectable内存) 设备驱动:包括设备驱动层和消息通信 主要是四个部分: (1)中断 ...

  8. eclipse使用profile完成不同环境的maven打包功能

    原文:https://blog.csdn.net/duan9421/article/details/79086335 我们在日常开发工作中通常会根据不同的项目运行环境,添加不同的配置文件,例如 开发环 ...

  9. 咏南Mormot中间件接口

    咏南Mormot中间件接口 只使用了MORMOT的HTTPS.SYS作为通讯,数据引擎使用FIREDAC,数据序列/还原是自行封装. 客户端支持FDMemeTable和ClientDataSet数据集 ...

  10. 某个 页面覆盖了 UITabBar 的tabItem的解决办法

    将这个页面的背景色设置为无色: [self.view setBackgroundColor:[UIColor clearColor]]; 或者 self.view.frame = CGRectMake ...