Skip to Content
Node与Express开发(第2版)
book

Node与Express开发(第2版)

by Ethan Brown
June 2021
Intermediate to advanced
290 pages
9h 21m
Chinese
Posts & Telecom Press
Content preview from Node与Express开发(第2版)
214
|
第
18
章
18.3.7
 基于角色的授权
目前为止,从技术上来说,我们并没有做任何授权(只是区分了已授权和未授权的用户)。
可是,如果只想让客户看到他们自己账号的视图该怎么办?(雇员可以有一个完全不同的
视图,在其中他们可以看到所有用户的账号信息。)
还记得吗?在单个路由里,可以有多个函数,它们会按顺序得到调用。创建一个名为
customerOnly
的函数,只允许客户通过:
const customerOnly = (req, res, next) => {
if(req.user && req.user.role === 'customer') return next()
// 让只允许客户访问的页面知道自己是需要登录的
res.redirect(303, '/unauthorized')
}
再创建一个名为
employeeOnly
的函数,它跟上面略有不同。比如说,我们希望只有雇员才
可以访问路径
/sales
,
而且甚至不想让非雇员知道这个页面的存在,即便他们是误打误撞
才访问的。如果某个潜在的攻击者进入了
/sales
,看到一个
“未授权”页,这也会作为给
他提供的信息,并可能会使他的攻击更容易一些(知道了这个页面的存在)。因此,为了
增加一点儿安全性,希望非雇员在访问
/sales
页时看到的是一个常规的
404
页
,从而不给
潜在的攻击者提供任何头绪:
const employeeOnly = (req, res, next) => {
if(req.user && req.user.role ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.

Read now

Unlock full access

More than 5,000 organizations count on O’Reilly

AirBnbBlueOriginElectronic ArtsHomeDepotNasdaqRakutenTata Consultancy Services

QuotationMarkO’Reilly covers everything we've got, with content to help us build a world-class technology community, upgrade the capabilities and competencies of our teams, and improve overall team performance as well as their engagement.
Julian F.
Head of Cybersecurity
QuotationMarkI wanted to learn C and C++, but it didn't click for me until I picked up an O'Reilly book. When I went on the O’Reilly platform, I was astonished to find all the books there, plus live events and sandboxes so you could play around with the technology.
Addison B.
Field Engineer
QuotationMarkI’ve been on the O’Reilly platform for more than eight years. I use a couple of learning platforms, but I'm on O'Reilly more than anybody else. When you're there, you start learning. I'm never disappointed.
Amir M.
Data Platform Tech Lead
QuotationMarkI'm always learning. So when I got on to O'Reilly, I was like a kid in a candy store. There are playlists. There are answers. There's on-demand training. It's worth its weight in gold, in terms of what it allows me to do.
Mark W.
Embedded Software Engineer

You might also like

面向对象的思考过程(原书第5版)

面向对象的思考过程(原书第5版)

马特 魏斯费尔德
精通模块化JavaScript

精通模块化JavaScript

Nicolás Bevacqua
前端架构设计

前端架构设计

Micah Godbolt

Publisher Resources

ISBN: 9787115565099