如何使用json開發web
by Sudheesh Shetty
由Sudheesh Shetty
如何通過使用JSON Web令牌簡化應用程序的身份驗證 (How to simplify your app’s authentication by using JSON Web Token)
Every application we come across today implements security measures so that the user data is not misused. Security is always something that is changing and evolving. Authentication is one of the essential part of every application.
我們今天遇到的每個應用程序都實施安全措施,以便不會濫用用戶數據。 安全始終是不斷變化和發展的事物。 身份驗證是每個應用程序必不可少的部分之一。
There are various ways to authenticate the user. Let us discuss token based authentication using node.js application. For this, we will be using JSON Web tokens.
有多種驗證用戶身份的方法。 讓我們討論使用node.js應用程序進行的基于令牌的身份驗證。 為此,我們將使用JSON Web令牌。
什么是JSON Web令牌(JWT)? (What are JSON Web Tokens (JWT)?)
JSON Web Tokens (JWT) is a standard that defines a compact and self-contained way for securely transmitting information between parties as a JSON object.
JSON Web令牌(JWT)是一種標準,它定義了一種緊湊且自包含的方式,用于在各方之間作為JSON對象安全地傳輸信息。
Compact: Smaller size so that easily transferred.
緊湊 :體積更小,易于轉移。
Self-Contained: It contains all information about the user.
自包含:它包含有關用戶的所有信息。
它們如何工作? (How Do they work?)
When a user sends a request with required parameters like username and password. The application checks if username and password are valid. On validation, the application will create a token using a payload and a secret key. It will then send the token back to the user to store and send it with each request. When user sends request with this token, application verifies validity with same secret key. If the token is valid, the request is served, else the application will send an appropriate error message.
用戶發送帶有必需參數(如用戶名和密碼)的請求時。 該應用程序檢查用戶名和密碼是否有效。 驗證后,應用程序將使用有效負載和密鑰創建令牌。 然后,它將令牌發送回用戶以進行存儲并隨每個請求發送。 當用戶使用此令牌發送請求時,應用程序將使用相同的密鑰驗證有效性。 如果令牌有效,則請求得到響應,否則應用程序將發送適當的錯誤消息。
結構體 (Structure)
Basic structure of JWT is something like
JWT的基本結構類似于
header payload signature
header: It contains token type and algorithm used to make signature. Gets encoded to base64.
標頭:包含令牌類型和用于簽名的算法。 獲取編碼為base64。
payload: Any custom user data like username and email.
有效負載:任何自定義用戶數據,例如用戶名和電子郵件。
signature: Hash of encoded header, payload and a secret key.
簽名:編碼的標頭,有效負載和密鑰的哈希。
智威湯遜的優勢 (Advantages of JWT)
Single Key: There is no need for database calls every time to verify the user. A single secret key will decode tokens provided by any user.
單鍵:無需每次都進行數據庫調用來驗證用戶。 單個密鑰將解碼任何用戶提供的令牌。
Portable: Same token can be used among different domains or different platforms. All it needs is the key.
可移植:相同的令牌可以在不同的域或平臺之間使用。 它所需要的只是關鍵。
Easy Expire: One can set expiration time using JWT. After that time JWT expires.
簡易到期時間:可以使用JWT設置到期時間。 在此之后,JWT到期。
我們該怎么做? (How can we do it?)
We are going to build a node.js application with few routes and authenticate them using tokens. Basic knowledge of node.js and javascript is required.
我們將用很少的路由構建一個node.js應用程序,并使用令牌對其進行身份驗證。 需要具備node.js和javascript的基礎知識。
Step 1 — Open terminal. Start a new project in a directory
步驟1 —打開終端。 在目錄中啟動新項目
cd auth
npm init
This will start a new project. Process will ask for certain information. Provide all the details required. Process will create package.json and it will look something like this.
這將啟動一個新項目。 過程將要求某些信息。 提供所需的所有詳細信息。 流程將創建package.json ,看起來像這樣。
{ "name": "auth", "version": "1.0.0", "description": "application to explain authentication", "main": "server.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "author": "Your name", "license": "ISC"}
Step 2 — Install the dependencies. Again go back to terminal and paste the following line.
第2步 -安裝依賴項。 再次回到終端并粘貼以下行。
npm install express body-parser jsonwebtoken --save
express: Node.js web application framework.
表達: Node.js Web應用程序框架。
body-parser: To get parameters from our POST request.
body-parser:從POST請求中獲取參數。
jsonwebtoken: To create and verify tokens.
jsonwebtoken:創建和驗證令牌。
After installing the dependencies. Our package.json will look something like this:
安裝依賴項后。 我們的package.json將如下所示:
{ "name": "auth", "version": "1.0.0", "description": "application to explain authentication", "main": "server.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "author": "Your name", "license": "ISC", "dependencies": { "body-parser": "^1.17.2", "express": "^4.15.3", "jsonwebtoken": "^7.4.1" }}
Step 3 — Create server
第3步-創建服務器
Let us create a server, serving at port 3000 which sends the index.html when /
route is called. We will also create /login
API which authenticates the user and a /getusers
API which gives list of users. Let’s create dummy data for now and store it in the ‘users’ array. You may also replace them with database calls.
讓我們創建一個服務器,該服務器的端口為3000,當調用/
route時,該服務器發送index.html。 我們還將創建用于驗證用戶身份的/login
API和提供用戶列表的/getusers
API。 現在,讓我們創建虛擬數據并將其存儲在“用戶”數組中。 您也可以將它們替換為數據庫調用。
Step 4 — Build the Client
步驟4 —建立客戶
Let us create a client using HTML, Bootstrap and JavaScript. Our client has two parts: login screen and a place to retrieve users. Login screen will contain text boxes for email and password and a button to send request. We will also add a text box and button to pass the token and get list of users.
讓我們使用HTML,Bootstrap和JavaScript創建客戶端。 我們的客戶有兩個部分:登錄屏幕和一個檢索用戶的地方。 登錄屏幕將包含用于輸入電子郵件和密碼的文本框,以及用于發送請求的按鈕。 我們還將添加一個文本框和一個按鈕來傳遞令牌并獲取用戶列表。
Step 5 — Start the application
步驟5 —啟動應用程序
node server.js
我們的應用程序安全嗎? (Is our app secure?)
No, you might see that even if you don’t pass the token you can get the list of all users. We have not implemented authentication yet. Let’s add authentication to /getusers
API so that users with valid token can retrieve users list.
不,您可能會看到,即使不傳遞令牌,也可以獲得所有用戶的列表。 我們尚未實現身份驗證。 讓我們向/getusers
API添加身份驗證,以便具有有效令牌的用戶可以檢索用戶列表。
如何添加身份驗證? (How to Add Authentication?)
- Include JWT to the server.js file. 將JWT包含在server.js文件中。
var jwt=require('jsonwebtoken');
2. Pass the payload(any object, here pass the user object itself) and a secret string to sign function and create a token.
2.傳遞有效負載(任何對象,這里傳遞用戶對象本身)和一個秘密字符串來簽名函數并創建令牌。
var token=jwt.sign(<user>,<secret>);
3. When the token is created successfully pass the same to client.
3.成功創建令牌后,將其傳遞給客戶端。
res.json({token:token});
You can then store token on client side and pass it every time during the session to authenticate. Let’s change the “getlist” function so that we can pass token to the server when we want to access users list.
然后,您可以在客戶端存儲令牌,并在會話期間每次傳遞令牌以進行身份??驗證。 讓我們更改“ getlist”功能,以便在我們要訪問用戶列表時可以將令牌傳遞給服務器。
Let’s add a middleware to authenticate /getusers
or any secure route that is added in future. Make sure that all routes that needs authentication is below the middleware.
讓我們添加一個中間件來認證/getusers
或將來添加的任何安全路由。 確保所有需要身份驗證的路由都在中間件下方。
In server.js, first we have login route which creates token. After that we have middleware which we will use to verify the token. All the routes which needs authentication are after middleware. The order is very important.
在server.js中,首先我們有創建令牌的登錄路由。 之后,我們將使用中間件來驗證令牌。 所有需要認證的路由都在中間件之后。 順序很重要。
4. To decode, you pass the token and secret key to verify function. Function will return error if the token is invalid or success if token is valid.
4.要進行解碼,請傳遞令牌和密鑰以驗證功能。 如果令牌無效,函數將返回錯誤;如果令牌有效,則函數將返回成功。
jwt.verify(token,"samplesecret",(err,decod)=>{ //your logic})
Call next() so that respective routes are called.
調用next(),以便調用相應的路由。
Final server.js will look like this:
最終的server.js將如下所示:
Final index.html will look like this:
最終的index.html將如下所示:
That’s it. This is a simple example of how to use token to authenticate your app. I have put the complete code on GitHub. You may check it there.
而已。 這是一個簡單的示例,說明如何使用令牌來驗證您的應用程序。 我已經將完整的代碼放在GitHub上。 您可以在那里檢查。
sudheeshshetty/JWT_AuthContribute to JWT_Auth development by creating an account on GitHub.github.com
sudheeshshetty / JWT_Auth 通過在GitHub上創建一個帳戶來貢獻JWT_Auth開發。 github.com
Thanks for reading and do follow me and recommend the same to others by clicking on ? . My twitter handle is sudheeshshetty.
感謝您的閱讀,請關注我并通過單擊?向其他人推薦。 我的推特句柄是sudheeshshetty 。
翻譯自: https://www.freecodecamp.org/news/how-to-make-authentication-easier-with-json-web-token-cc15df3f2228/
如何使用json開發web