This article has participated in the good article call order activity, click to see: back end, big front end double track submission, 20,000 yuan prize pool for you to challenge!
This minimal permission authentication must be mastered, the code is not more than 100, but it is critical
Small white recently did not come to ask the question of the school committee, but a few days ago, a friend asked how to control access, resource control, the school committee specially wrote a.
This is actually the authority authentication, understanding and grasp its core idea is very important, and every system can not be avoided! Let’s see.
Story telling – minimalist permission authentication [code + principle + suggestion collection] (above for the same article to explain the video, you can see the video analysis more intuitive understanding)
Normally, we need to authenticate user access to all apis. For example, determine who is currently accessing the user, what role.
The following statements are based on the security system of commercial office buildings.
I went to work today but forgot to bring my employee card
As an office worker, you go to a certain floor of a large office building and want to enter different floors, the mall property will authenticate.
Then enter the elevator to open by pressing a certain floor. Then you need to open the card before entering the office, and the card will be connected to the Internet to verify.
Some companies do more employee identification, but the essence is similar.
Of course, how many times to drop card verification, depending on where you want to go, the corresponding number of security levels.
This is actually with us to do a website/platform permission authentication a reason.
We go to a place to drop cards, what’s the equivalent behavior in technology?
In fact, we do the system for security, most of the time will not directly send the user name and password, which is not safe.
It’s like, most office complexes don’t ask you to pull out your ID and recite the id number and address every time.
Or every time you enter a venue, they ask you a bunch of private questions, only to let you in when the answers and the system’s pre-programmed data are fully configured.
It’s a hassle! So we do permission authentication based on a token mechanism, which is like we take an employee card, access card.
Here we simply understand a concept, token is like an access card, we access the platform resources when the token, drop, resources can be accessed.
No drop card/take the wrong card, no access to the office building!
First look at the effect, which looks like this:
May I enter the elevator/office building after PUNCHING the clock?
First look at the effect: this is the login user access to restricted resources
Let’s compare the two requests
The first time you access the restricted resource “/restrictData”, you can check in the Inspector that the request header does not contain a token.
It’s like forgetting your card. The site just denied access.
The second request is detailed below. Take a look at the following figure, this request carries a token, access to the restricted resource, and is an effective token, so the output below is “access to the restricted resource, the current user is learning from the committee”.
After seeing the effect, do you understand the core of the permission authentication?
Do you have a few questions in mind
- How does the site verify that each request is valid? (For each visitor, check whether the visitor can access the data)
- How is the token generated for this site? (Similar to how the card is made, hairpin)
Said the above some intuitive feeling, the following lei School committee will take you to interpret the technology to achieve, this time to achieve with javascript, based on NodeJS engine run.
The principle of analytic
First, how do I verify that every request is valid
We use the Express Interceptor here. The code is as follows:
// For each request
app.use((req, res, next) = >{
var url = req.originalUrl
console.log('filter - url:',url)
// The first step is to determine whether to whitelist, such as login, logout, and other unrestricted access to resources.
if(url.startsWith('/login/')||url==='/logout'||url==='/checkToken'){
next();
return;
}
// Second step, if not the above whitelist resources, then obtain the token token, no token directly rejected
var t = req.header('token')
console.log('filter - request header token:', t)
if(! t){ res.status(400).send("No unauthorized access!!")
return
}
// console.log('filter - current session:', req.session)
// The third step is to query the user token registry of the website and check whether the user corresponding to the current token is protected. Otherwise, the token is invalid, like taking the wrong card.
var user = getUserByToken(req)
if(! user){ res.status(400).send("Your token is invalid or not logged in, please log in!")
return
}
// Finally, the above verification is passed, and the subsequent resource processing is directly carried out.
req.session.user = user
console.log('filter - check user is ' + user)
next();
});
// Token Indicates the token registry
const tokenRegisterTable = {}
// Define a method to query and retrieve user information based on the token
const getUserByToken=(req) = >{
var t = req.header('token')
if(! t)return false
return tokenRegisterTable[t]
}
Copy the code
So, through an interceptor, an AOP mechanism similar to Spring (or a Filter in a Servlet) looks at the token on each request.
This interceptor/filter is like a security guard standing on the ground: stop, little brother, can you show me your valid id please? Otherwise, leave as soon as possible!
(Image from:www.sohu.com/a/293107575…
How are tokens generated and cards created and issued?
Registration card, just like every student/employee who goes to the relevant unit to register, management gives you a card on the day you report in.
In our code, there is usually a registration process, but the card will not be issued to you at this time, because there will be great security risks if the website data is sent to a card that can be used permanently. So more often than not, a card (token) is issued for every login! And the card is time-limited.
The following is the implementation of the login token issuance:
// This is the login interface. There is no need to verify the password
app.get('/login/:user'.function(req, res){
const user = req.params.user
console.log('user is ',user)
// Check whether the user is logged in from the Express session
if(req.session.name){
res.send('You are logged in, user'+req.session.name)
return;
}
// If there is no login, record the user and set two cookies in the corresponding, record the user name and token token
req.session.user = user
res.cookie('name', user)
res.cookie('token', getTokenFromSession(user,req.session)) // Token The token is used for client storage. Take a look at the screenshot of the browser token below
res.send("Login user =" + user)
});
// A simple implementation to generate random tokens
const getTokenFromSession = (user, session) = >{
var token = 'token-' + rand()
tokenRegisterTable[token] = user
console.log('tokenRegisterTable=',tokenRegisterTable)
return token
}
const rand = () = > new Date().getTime()+The '-'+Math.floor((Math.random()+1) *1000)
Copy the code
Let’s look at the user’s local token, which also has a user name.
As the difficulty escalates, let’s look at the general process
The following is the core code of this minimalist permission authentication, student committee here only to show the key links.
- Displays login and token generation, but does not check encrypted password ciphertext from database or distributed cache to verify user back session.
- Simply encrypt the cookie and session
- I simply made a tokenRegisterTable, the token registry
- Implement login/logout/a restricted resource for core principle presentation.
const express = require('express')
const serveStatic = require('serve-static')
const session = require('express-session')
const cookieParser = require('cookie-parser')
const app = express()
const tokenRegisterTable = {}
// Value static page, the page above showing login/verify access to restricted resources
app.use(serveStatic('./public'));
app.use(cookieParser('Lei School Committee Key'))
app.use(session({
secret: 'Lei School Committee Key'.resave: true.saveUninitialized: true.cookie: { secure: true}}))const getUserByToken=(req) = >{
var t = req.header('token')
if(! t)return false
return tokenRegisterTable[t]
}
// Request the interceptor
app.use((req, res, next) = >{
var url = req.originalUrl
console.log('filter - url:',url)
if(url.startsWith('/login/')||url==='/logout'||url==='/checkToken'){
next();
return;
}
var t = req.header('token')
console.log('filter - request header token:', t)
if(! t){ res.status(400).send("No unauthorized access!!")
return
}
// console.log('filter - current session:', req.session)
var user = getUserByToken(req)
if(! user){ res.status(400).send("Your token is invalid or not logged in, please log in!")
return
}
req.session.user = user
console.log('filter - check user is ' + user)
next();
});
// Exit the user, knowing the local access token
app.get('/logout'.(req,res) = >{
var t = req.cookies['token']
var u = req.session.user
req.session.destroy();
tokenRegisterTable[t] = null
res.clearCookie('name')
res.clearCookie('token')
console.log('logout - session:',req.session)
res.send(u + 'Logged out successfully! ');
});
// A simple restricted resource. If the user is allowed to access the resource, return "access restricted resource, current user x"
app.get('/restrictData'.function(req,res){
var user = req.session.user
res.send('Access restricted resource, current user'+user)
});
const rand = () = > new Date().getTime()+The '-'+Math.floor((Math.random()+1) *1000)
const getTokenFromSession = (user, session) = >{
var token = 'token-' + rand()
tokenRegisterTable[token] = user
console.log('tokenRegisterTable=',tokenRegisterTable)
return token
}
// Verify the token interface separately
app.get('/checkToken'.function(req, res){
res.send(getUserByToken(req)&&true)});// Verify the login user
app.get('/login/:user'.function(req, res){
const user = req.params.user
console.log('user is ',user)
if(req.session.user){
token = req.cookies['token']
let data = 'You are logged in, user'+req.session.user
res.send(data)
return;
}
req.session.user = user
res.cookie('name', user)
res.cookie('token', getTokenFromSession(user,req.session))
console.log('user login :' , user)
res.send("Login user =" + user)
});
PORT=12024
app.listen(PORT, function(){
console.log('app running at port ' + PORT);
});
Copy the code
The above code login, the interceptor explained.
Add logout/exit here
This interface is necessary to make sure that each time the user accesses an logout or clicks logout, the token map from the server side is empty and the user’s browser side token is cleared. (This is not standard practice, of course, as apps usually retain a refreshToken, which will not be mentioned in this article.)
conclusion
Access to each resource requires a card, and the right card, to access the appropriate service! Or some readers may think of health codes, which are essentially a trust authorization mechanism!
Again, why not use the password directly each verification, each request with a password, resulting in a greater risk of password leakage! As for the token, it is like a card, which can be cancelled at any time, making it easier to manage.
This paper mainly shows the idea of web platform permission authentication, covering the generation of permission authentication token, token management, request verification process.
Other things like token customization, such as having JWT tokens, token timeliness, and user role management are not covered. These implementations have a lot of detail customization. If the developer doesn’t understand the core idea of this article, let alone implement the details.
For example, the micro-service platform will have a unified authentication service, and the big data platform and TMS will introduce Kerberos, which is more complicated to implement. We’ll have a chance to talk about that later.
By the way, the school committee also has this can pay attention to long-term reading => lei School committee interesting programming story compilation
Continuous learning and continuous development, I am the Lei School committee! Programming is fun, but the key is to get the technology straight. Creation is not easy, please support a lot, click like collection to support the school committee!
Refer to the link
Code download do not understand NodeJS can see -> Lei Xuechai NodeJS series