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

如何使用json开发web_如何通过使用JSON Web令牌简化应用程序的身份验证相关推荐

  1. python后端开发web_最简易的python web框架的后端实现

    1.源代码 #!/usr/bin/python #encoding=utf-8 from flask import json, Flask, request app = Flask(__name__) ...

  2. web api json_使用JSON Web令牌对Node ES6 API进行身份验证

    web api json In this guide, we'll be implementing token based authentication in our own node.js A.P. ...

  3. 带有Spring Cloud Microservices的JSON Web令牌

    在Keyhole,我们已经发布了几个有关微服务的博客 . 我们已经讨论了微服务环境中使用的架构模式,例如服务发现和断路器 . 我们甚至在平台和工具上发布了博客,例如最近关于Service Fabric ...

  4. Web 开发人员必备的随机 JSON 数据生成工具

    在 Web 开发中,经常会需要一些测试数据来测试接口或者功能时候正确.JSON Generator 就是这样一款生成随机 JSON 数据的在线工具,Web 开发人员必备,记得收藏和分享啊. 您可能感兴 ...

  5. 【开发环境】Ubuntu 中使用 VSCode 开发 C/C++ ⑤ ( tasks.json 中的 args 数组配置分析 | 编译并执行 C++ 程序 )

    文章目录 一.tasks.json 中的 args 数组配置分析 二.编译并执行 C++ 程序 可以参考官方提供的文档 : https://code.visualstudio.com/docs/cpp ...

  6. 【开发环境】Ubuntu 中使用 VSCode 开发 C/C++ ④ ( 创建 tasks.json 编译器构建配置文件 | tasks.json 编译器构建配置文件分析 )

    文章目录 一.创建 tasks.json 编译器构建配置文件 二.tasks.json 编译器构建配置文件分析 可以参考官方提供的文档 : https://code.visualstudio.com/ ...

  7. openresty开发系列25--openresty中使用json模块

    openresty开发系列25--openresty中使用json模块 web开发过程中,经常用的数据结构为json,openresty中封装了json模块,我们看如何使用 一)如何引入cjson模块 ...

  8. JSON开发详解-张晨光-专题视频课程

    JSON开发详解-25人已学习 课程介绍         JSON 是轻量级的文本数据交换格式,JSON 文本格式在语法上与创建 JavaScript 对象的代码相同,JSON 比 XML 更小.更快 ...

  9. IOS开发基础之网易新闻JSON转模型数组第2天

    IOS开发基础之网易新闻JSON转模型数组第2天 // // HMHeadline.h // 01-网易新闻搭建 // // Created by 鲁军 on 2021/4/11. //#import ...

最新文章

  1. Mac 下 IDEA 启动慢的问题
  2. Android之jni解决JNIEnv跨线程问题
  3. 带你认识7种云化测试武器
  4. NotImplementedError: Cannot convert a symbolic Tensor报错与解决
  5. 双向循环链表涉及双向指针的基本操作(C语言)
  6. python排序算法实现_排序算法整理(Python实现)
  7. java 静态方法 变量_Java变量的初始化及静态方法的实现
  8. 电脑公司最新稳定win7系统下载
  9. 阿里面试官最新分享的Java面试宝典,含8大核心内容讲解
  10. QT出现应用程序无法正常启动0xc000007b的错误
  11. 你不得不看的“互联网+企业购”大趴攻略
  12. 【顶】(与同事合作的快乐)技术人员也需要先学会做人,再学会做事,再是能成事,最后是成名得利...
  13. 计算机组成与系统结构(课程设计)
  14. 二级计算机c语言解题技巧,2010年全国计算机等级考试二级C语言考试题型解题技巧...
  15. 5s注销了id新建id服务器出错,iphone5s手机如何重新设置苹果id账户
  16. 文件上传中关于MultipartResolver的配置
  17. NDK开发-Android下摄像头YUV数据获取与H264编码(FFmpeg、x264)总结
  18. ​数字基建狂潮中:区块链处于什么位置?
  19. 这5款PC工具不容错过,抓紧收藏起来
  20. k米评分容易得高分的歌_有品上架纯麦K歌无线麦克风,小米电视即插即用,客厅秒变KTV...

热门文章

  1. java----DBUtils知识点补充
  2. java---连接池的学习
  3. sql 命令使用简单记录
  4. java并发编程实战:第十四章----构建自定义的同步工具
  5. bzoj3503: [Cqoi2014]和谐矩阵
  6. JS 三级联动 下拉列表
  7. 【转】/usr/bin/python^M: bad interpreter: No such file
  8. oracle左右连接的另外表示方法
  9. Java常见的几种内存溢出及解决方法
  10. Git上传项目到github