如何使用json開發web_如何通過使用JSON Web令牌簡化應用程序的身份驗證

如何使用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?)

  1. 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

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/395391.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/395391.shtml
英文地址,請注明出處:http://en.pswp.cn/news/395391.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

c++ 實現錄音并且指定到文件_通話自動錄音,留下美好回憶,記錄完整錄音證據...

手機通話&#xff0c;如果自動錄音多好&#xff0c;許多人與我一樣抱有這個想法。記得華為Android版本5.0時代&#xff0c;手機沒有自動錄音功能&#xff0c;我一直到網上下載自動通話錄音軟件&#xff0c;有時甚至是下載ROOT版的帶自動通話功能的EMUI版本進行刷機安裝。那個時…

2639-Bone Collector II (01背包之第k優解)

題目鏈接&#xff1a; http://acm.hdu.edu.cn/showproblem.php?pid2639 求第k優解的關鍵代碼&#xff1a; 用兩個數組記錄兩種狀態&#xff08;選擇或不選擇&#xff09;&#xff0c;并且只要記錄前k次。在這兩個數組中都是前k次可能的最優解。所以我們只要把這兩個數組做比較…

html自動按鍵,VBS腳本和HTML DOM自動操作網頁

本來是想通過JS實現對其他頁面的控制&#xff0c;發現跨域無法獲取頁面DOM來操作。接著考慮bat&#xff0c;發現也實現不了&#xff0c;于是想到vbs。vbs還是很強大啊&#xff0c;病毒之類很多都是vbs腳本啊。vbs打開瀏覽器&#xff0c;然后通過dom來操作頁面&#xff0c;可以實…

opencv在同一窗口打印多張圖片

首先&#xff0c;由于cv2處理的圖片是通過ndarray的格式操作的&#xff0c;也就是說通過array的拼接就可以實現圖片的拼接&#xff0c;那么之后就可以通過簡單的imshow將合并的圖片打印從而達到在一個窗口中顯示多張圖片的目的。 import cv2 import numpy as npimg1 cv2.imrea…

dj打碟怎么學_學DJ打碟 - Rane聲卡連接

上一篇內容中&#xff0c;老師講過在學DJ打碟的時候&#xff0c;是離不開對軟件方面的操作&#xff0c;其實每一個學習過程&#xff0c;當你學會之后&#xff0c;在“回頭看”的時候&#xff0c;都會覺得&#xff1a;原來學DJ打碟這么簡單啊&#xff0c;這就是已經學習過的人會…

微信企業號第三方應用開發[一]——創建套件

注&#xff1a;文中綠色部分為摘自微信官方文檔 第三方應用提供給企業的是一個應用&#xff0c;但是應用必須在套件下創建&#xff0c;所以第一步是要創建套件。 注冊成為應用提供商&#xff0c;必須輸入以下信息&#xff1a; 信息項要求及說明企業Logo應用提供商的企業Logo&am…

advanced east_SpriteKit Advanced —如何構建2,5D游戲(第二部分)

advanced eastby Luke Konior盧克科尼爾(Luke Konior) SpriteKit Advanced —如何構建2,5D游戲(第二部分) (SpriteKit Advanced — How to build a 2,5D game (Part II)) 介紹 (Intro) This article shows how to write basic shaders in the SpriteKit. It’s split into two…

html原生上傳,一個基于HTML5及原生JS的文件上傳組件--JohnUploader

運行效果圖一、組件介紹基本特點基于HTML5的FileReader和FormData可以完成多文件選擇&#xff0c;并預覽完成文件的異步上傳原生XHR對象&#xff0c;適配多瀏覽器代碼class JohnUploader{url;fileField;vollay;/**** param url 文件上傳的地址* param fileField 一個"文件…

[20170617]vim中調用sqlplus.txt

[20170617]vim中調用sqlplus.txt --//以前寫過一篇emacs下調用sqlplus的文章,一直想學emacs,受限制自己掌握vim,對學習它沒有興趣,原鏈接如下: --//http://blog.itpub.net/267265/viewspace-1309032/ --//實際上vim也有插件連接數據庫,我覺得不好用,一直沒這樣用. --//今天在整…

centos redis驗證_centos7中安裝、配置、驗證、卸載redis

本文介紹在centos7中安裝、配置、驗證、卸載redis等操作&#xff0c;以及在使用redis中的一些注意事項。一 安裝redis1 創建redis的安裝目錄利用以下命令&#xff0c;切換到/usr/local路徑cd /usr/local鍵入以下命令&#xff0c;新建一個redis目錄&#xff0c;用于放置redis軟件…

實習生解雇_我們解雇了我們的頂尖人才。 我們做出的最佳決定。

實習生解雇by Jonathan Solrzano-Hamilton喬納森索洛薩諾漢密爾頓(JonathanSolrzano-Hamilton) 我們解雇了我們的頂尖人才。 我們做出的最佳決定。 (We fired our top talent. Best decision we ever made.) “You will never be able to understand any of what I’ve create…

微信企業號第三方應用開發[二]——創建應用

在應用套件里添加應用 當你創建完應用套件后&#xff0c;需要在套件配置應用&#xff0c;應用的信息填寫如下。 基本信息&#xff1a; 信息項要求及說明應用Logo應用的Logo&#xff0c;小于2M&#xff0c;640*640&#xff0c;在授權頁會被用于展示。應用名稱應用的名稱&#xf…

es6新增的html標簽,javascript – 如何導入已在html中的標簽中定義的es6模塊?

我可以在我的html文件me.html中定義一個模塊&#xff1a;import Atom from ./atom.js;console.log("definition of getAtom")export default function getAtom(){return new Atom(atom);}console.log("exported getAtom")另見>是否可以將該“匿名”模塊…

jQ效果:簡單的手風琴效果

實現效果如圖所示&#xff1a; html結構&#xff1a; <div class"item_box box10"><div class"item_box_wp"><div class"voice_2"><ul><li class"li1" id"li1"><div class"fold"…

golang 日志分析_容器日志采集利器:Filebeat深度剖析與實踐

在云原生時代和容器化浪潮中&#xff0c;容器的日志采集是一個看起來不起眼卻又無法忽視的重要議題。對于容器日志采集我們常用的工具有filebeat和fluentd&#xff0c;兩者對比各有優劣&#xff0c;相比基于ruby的fluentd&#xff0c;考慮到可定制性&#xff0c;我們一般默認選…

機器學習做自動聊天機器人_建立聊天機器人需要什么? 讓我們找出答案。

機器學習做自動聊天機器人by Vanco Stojkov通過Vanco Stojkov 建立聊天機器人需要什么&#xff1f; 讓我們找出答案。 (What does it take to build a chatbot? Let’s find out.) Without any delay, the image below shows what we are building:沒有任何延遲&#xff0c;下…

UVA 11582 Colossal Fibonacci Numbers!【數學】

大一剛開始接觸ACM就買了《算法競賽入門經典》這本書&#xff0c;當時只能看懂前幾章&#xff0c;而且題目也沒做&#xff0c;粗鄙地以為這本書不適合自己。等到現在快大三了再回過頭來看&#xff0c;發現劉老師還是很棒的&#xff01; 扯遠了。。。 題意&#xff1a;問f[a^b]%…

Codeforces 919D Substring (拓撲圖DP)

手動博客搬家: 本文發表于20180716 10:53:12, 原地址https://blog.csdn.net/suncongbo/article/details/81061500 給定一個\(n\)個點\(m\)條邊的有向圖&#xff08;不一定無環&#xff09;&#xff0c;每個點上有一個小寫字母。要找一條路徑&#xff0c;使得路徑上出現次數最多…

layui自定義查詢條件html頁面,Layui的數據表格+springmvc實現搜索功能的例子_飛雲_前端開發者...

如下所示&#xff1a;主要在前端頁面加&#xff1a;搜索ID&#xff1a;useridcontent搜索在reload:function () {var keyWord$("#keyWord").val();var keyType$("#key_type option:selected").val();table.reload(contenttable,{method:post,where:{keyWor…

mysql+keepalived 雙主熱備高可用

理論介紹&#xff1a;我們通常說的雙機熱備是指兩臺機器都在運行&#xff0c;但并不是兩臺機器都同時在提供服務。當提供服務的一臺出現故障的時候&#xff0c;另外一臺會馬上自動接管并且提供服務&#xff0c;而且切換的時間非常短。MySQL雙主復制&#xff0c;即互為Master-Sl…