In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-22 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)05/31 Report--
This article mainly introduces "how to achieve identity authentication in node.js". In daily operation, I believe that many people have doubts about how to achieve identity authentication in node.js. The editor consulted all kinds of materials and sorted out simple and easy-to-use methods of operation. I hope it will be helpful to answer the doubts of "how to achieve identity authentication in node.js". Next, please follow the editor to study!
1. Today's first content is about the web development mode. Today, basically, we are talking about the content of identity authentication. Our web development mode is divided into two types, one is the server rendering mode, that is, the server performs a string concatenation, splices the html page together, and then returns it directly to the client. In this way, we do not need our ajax, just give it to the client. His advantage is that the front end is less time-consuming, after all, what the front end has done to the server, and he is also conducive to seo optimization, his disadvantage is that it takes up server resources, and is not conducive to the separation of front and rear development efficiency.
The second pattern: the front and rear separation pattern, which relies on a wide range of ajax applications, the back end is responsible for writing the api interface, and the front end is responsible for calling the interface. One of his advantages is that the development experience is good, after all, the front and rear ends are separated, and the user experience is good, which also reduces the pressure on the server.
But the disadvantage is that it is not conducive to the optimization of seo.
two。 And then we go into identity authentication,
What's the matter, authentication?
A way to confirm the identity of a user by certain means.
Server rendering development uses session authentication, while our front-end and back-end separation uses jwt authentication, both of which have their own advantages.
3. Let's talk about session first.
First of all, let's take a look at http statelessness, that is, each http request from the client is independent, there is no direct relationship between consecutive multiple requests, and the server will not actively retain the status of each http request (just like the cashier, can he remember that each customer is a member? )
Break through the stateless limit.
The way for supermarkets to break through this restriction is to issue membership cards to each member, right? in our web field, this way is cookie.
Cookie is a string stored in the user's browser that does not exceed 4kb. It is composed of name, value, and expiration date. Security is composed of optional attributes of applicable scope. Our cookie is independent under different domain names. Whenever the client initiates a request, it will automatically send all cookie under the current domain name to the server. Note that only under the current domain name.
Its features are: automatic sending, domain name independence, expiration time limit, 4kb restriction.
The role of 3.1cookie in identity Authentication
When our client requests the server for the first time, the server will send an authenticated cookie to the client through the response header, and our browser will store the cookie, and when we next request, it will directly send the cookie, that is, it will be sent automatically to prove the identity.
It is important to note that our cookie is not secure, and the browser also provides api for reading and writing cookie, so cookie is easy to be forged, just as our membership cards are forged. So don't use cookie to store important data, including our jwt. We'll talk about it later.
Is there any way to improve the security of our cookie?
That is session authentication, just like our membership card ➕ swiping card mechanism can break counterfeit cards.
Session authentication mechanism:
First of all, our client login account password sends a login request, and the server will start to verify. When the verification is successful, it will be stored in the server's memory, and a corresponding cookie string will be returned through the response header. Our browser will save this string under the current domain name, and when we request it again, we will send all the cookie under the domain name to the server. The server will find only the corresponding cookie to find your information successfully, and then the authentication will be successful.
After saying so much about how to use our sesson on the server side, we first install and import two tunes and then need to configure them. Note that the configuration is fixed, and secret can be any string.
After configuration, we can use req.session to access the session object, store some of our data in sessin, and then log in successfully and take it out through session, when we log out. The destroy method clears the session. Note that it only clears the account information, not other people's information. The specific code is as follows:
Pay attention to todo, which is what we need to do.
/ / Import express module const express = require ('express') / / create server instance of express const app = express () / / TODO_01: please configure Session middleware const session = require (' express-session') app.use (session ({secret: 'mySession', resave:' false') SaveUninitiallized: 'ture'})) / / hosting static page app.use (express.static ('. / pages')) / / parsing the form data submitted by POST app.use (express.urlencoded ({extended: false})) / / login API interface app.post ('/ api/login', (req) Res) = > {/ / determine whether the login information submitted by the user is correct if (req.body.username! = = 'admin' | | req.body.password! = =' 000000') {return res.send ({status: 1, msg: 'login failed'})} / / TODO_02: please send the user information after successful login Save to Session / / Note that you can use the req.session object req.session.user = req.body / / user information req.session.islogin = true / / the user's login status res.send ({status: 0, msg: 'login successful'})}) / / the interface app.get ('/ api/username', (req)) to get the user's name only after session has been configured above Res) = > {/ / TODO_03: get the user's name from Session Response to client / / to determine whether the login is successful if (! req.session.islogin) {return res.send ({status:1, msg:'fail'})} / / you can respond to the data return res.send ({status: 0, msg:' success', username: [req.session.user.username]})}) / / the login interface app.post ('/ api/logout', (req)) Res) = > {/ / TODO_04: clear Session information req.session.destroy () res.send ({status: 0, msg: 'login succeeded'})) / / call the app.listen method Specify the port number and start the web server app.listen (80, function () {console.log ('Express server running at http://127.0.0.1:80')}))
4. This is session, and then we see that the next authentication mechanism jwt,session needs cookie to implement, right? but our cookie has a fatal problem, which does not support cross-domain. If cross-domain is involved, there are a lot of steps to configure.
JWT is currently the most popular cross-domain authentication solution.
Implementation principle: first of all, the client initiates a request header to send the account password, and the server verifies it. After the verification is successful, it will encrypt a token string and then return a token string to you. When we get this token string, we will store it in localstorage or sessionStorage. When we request again, we will send the token to the server through an authorization request header. When the server gets the token, it will restore it to the user's information object, and then the identity will be successfully authenticated.
The component of JWT is made up of three parts: header. Patyload . Signature, this. Just the role of segmentation, our real information focuses on the middle of the payload before and after two just to ensure the security of token.
How to use our token in express?
You need to install two packages and define that the key is customized.
In the fourth step, when generating the JWT string, in the sign method, the configuration validity period is the period within which the token can be verified within the specified period.
The fifth step is to convert jwt to json. The statement unless means an interface that does not require authentication.
After configuring the fifth step to convert to a json file, we can use req.user to get the information, and this information is our fourth step to convert into a jwt string.
Finally, an error occurs when our token expires or is illegal. At this time, we need an error middleware.
/ / Import express module const express = require ('express') / / create a server instance of express const app = express () / / TODO_01: install and import two packages related to JWT Jsonwebtoken and express-jwtconst jwt = require ('jsonwebtoken') const expressJwt = require (' express-jwt') / / middleware allowing cross-domain resource sharing const cors = require ('cors') app.use (cors ()) / / parsing post form data const bodyParser = require (' body-parser') const {UnauthorizedError} = require ('express-jwt') const {response} = require (' express') app.use (bodyParser.urlencoded ({extended: false})) / / TODO_02: define secret key It is recommended that the key be named secretKeyconst secretKey = 'hard hard study day day up'// TODO_04: register the middleware app.use (expressJwt ({secret: secretKey, algorithms: [' HS256']}) that restores JWT string parsing to JSON objects. Unless ({path: [/ ^\ / api\ / /]}) / / login interface app.post ('/ api/login', function (req, res) {/ / the data in the req.body request body Dump to userinfo constant const userinfo = req.body / / login failed if (userinfo.username! = = 'admin' | | userinfo.password! = =' 000000') {return res.send ({status: 400, message: 'login failed!' })} / / successful login / / TODO_03: after a successful login, call the jwt.sign () method to generate a JWT string. And send it to the client through the token attribute and convert it to the token encrypted file const tokenStr = jwt.sign ({username: userinfo.username, algorithms: ['HS256']}, secretKey, {expiresIn:' 1h'}) res.send ({status: 200, message: 'login successful!' , token: tokenStr / / token string to be sent to the client}) / / this is an authorized API interface app.get ('/ admin/getinfo', function (req, res) {/ / TODO_05: use req.user to obtain user information and use the data attribute to send user information to the client res.send ({status: 200, message: 'get user information successfully!' , data: {username: req.user} / / user information to be sent to the client})}) / / TODO_06: using global error handling middleware Catch the error app.use ((err, req, res, next) = > {if (err.name = 'UnauthorizedError') caused by token parsing failure return res.send ({status: 401, msg:' invalid token'})} else {/ / other error return res.send ({status: 500) Msg: 'unknown error'})}) / / call the app.listen method Specify the port number and start the web server app.listen (8888, function () {console.log ('Express server running at http://127.0.0.1:8888')})). This is the end of the study on "how to authenticate node.js". I hope you can solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.