JSON Web Tokens (JWT) — the only explanation you will ever need

news/2024/5/9 7:27:55/文章来源:https://blog.csdn.net/csdnharrychinese/article/details/130144238
本文摘抄自 Ariel Weinberger 博客
JSON Web Tokens (JWT) — the only explanation you will ever need | by Ariel Weinberger | Medium

JSON Web Tokens (JWT) — the only explanation you will ever need

JSON Web Tokens are changing the world for the better. Acting as the shield of stateless and distributed architectures, JWTs are pretty amazing. But with great responsibility comes great confusion, and I’m here to help shed some light on this wonderful technology.

This article will be divided into two parts: Part 1 covering the JWT standard, and Part 2 being the juicy part, covering common use cases, techniques, misconceptions and frequently asked questions.

Introduction

Hello! My name is Ariel. Over the past years I have worked in various industries (FinTech, Sports, Entertainment, BioTech). I’ve love doing a bit of everything — front-end, back-end, ops and leadership.

Today I am Head of Engineering at Abcam. We support scientists across the globe in achieving amazing breakthroughs in Cancer Research, Alzheimer’s Disease Research and other biology-related matters.

Why do we need JSON Web Tokens (JWTs)?

I always believe that requirements come first. Understanding why we need JWTs rather than diving right into the explanation will surely help.

In the modern web, you will often have several parties communicating with each other. Certain features will naturally be restricted and require some sort of authorization mechanism.

Your typical front-end to back-end usage

The most shallow example would be a front-end application communicating with an API via HTTP requests. Using a JWT, you will be able to authorize the user. You could then take it one step further and use JWTs to perform role checks (for example, when a certain API route should only be available to admin users).

In distributed systems

JWTs are extremely useful in distributed systems and microservices architecture, utilising the Private-Public Key signing method. This method will save you a huge amount of requests and improve the overall scalability of your application. We will talk about that later on in this article.

The three components of a JSON Web Token

Part 1: The JWT Standard

JSON Web Token is a standard. A typical token will consist of a header, a payload and a signature. Let’s talk about each one of those and how they are utilised.

Header

The header contains metadata information about the JSON Web Token.

  • Algorithm (alg): The algorithm used to sign the token. This is useful for the attempted reproduction of the signature (we will talk about that later).
  • Type (typ): The type of the token. In the case of a JWT, this will always have the JWT value.

You will sometimes find extra headers that were added by the issuer. But the above two will most certainly always be there.

Payload

That’s what you’ve been waiting for. The payload will contain the claims of the token. There are several “recommended” standard fields that are defined in the JWT standard. Let’s talk about the most used ones:

  • Issuer (iss): The entity to generate and issue the JSON Web Token (for example, your authentication service or OAuth provider).
  • Subject (sub): The entity identified by this token. For example, if the token is used to authorize a user, sub could be the user ID.
  • Audience (aud): Target audience for this JWT. For example, if the token is intended to be used by your beta testers user pool, you could specify that as an audience. It is advised to reject tokens with no audience.
  • Expiry (exp): Specifies the timestamp (Unix) after which the token should not be accepted. We will talk about short-lived JWTs later on.
  • Issued at (iat): Specifies the date at which the token has been issued.

Now, these are the recommended ones. On top of those, you can feel free to add whatever extra fields you need.

For example, this would be a totally valid JWT payload:

{
"sub": "1dfee8d8-98a5-4314-b4ae-fb55c4b18845",
"email": "ariel@codingly.io",
"name": "Ariel Weinberger",
"role": "ADMIN",
"iat": 1598607423,
"exp": 1598607723
}

IMPORTANT: The payload of a JSON Web Token is, by default, decodable by anyone. In fact, you can paste any JWT into https://jwt.io and immediately see the claims.

Signature

Although we would like to believe that the magic of JWTs happens in the payload, it actually happens in the signature. This is probably the most commonly misunderstood part about JWTs.

Often times, people use the term “encrypt-decrypt” with JSON Web Tokens. You cannot decrypt the signature of a token. That is the idea behind the signature.

The signature is created from the encoded header, encoded payload, a secret (or private key, read further) and a cryptographic algorithm. All these four components allow the creation of a signature.

signature = Crypto(secret, base64(header), base64(payload))

And this is a sample signature:

jbcOUQ2bbiYlfVtprEkaT_S6Y6yQnBDOAKDHIHjvl7g

If you are thinking “that looks like gibberish”, you are absolutely correct. The signature looks like gibberish. But hey, this gibberish is unique and reproducible.

“Everyone can read my tokens! They can change the claims and grant themselves admin access!”

The first part is true. The second part isn’t. JSON Web Tokens are decodable by anyone. In fact, feel free to copy the following token:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxZGZlZThkOC05OGE1LTQzMTQtYjRhZS1mYjU1YzRiMTg4NDUiLCJlbWFpbCI6ImFyaWVsQGNvZGluZ2x5LmlvIiwibmFtZSI6IkFyaWVsIFdlaW5iZXJnZXIiLCJyb2xlIjoiVVNFUiIsImlhdCI6MTU5ODYwODg0OCwiZXhwIjoxNTk4NjA5MTQ4fQ.oa3ziIZAoVFdn-97rweJAjjFn6a4ZSw7ogIHA74mGq0

And paste it directly into https://jwt.io.

You can immediately see all the claims in this token. That is why you should never store sensitive information in the token (no, a user’s role is not sensitive — a password is).

Now you are probably wondering, what prevents people from tampering with the token? Well, the signature does!

When verifying a JSON Web Token, whatever client you use will take the headers and claims, then generate a signature. It will then compare the new signature with the old signature. JWT signatures are not decrypted but rather reproduced and then compared (JWT misconception #1). If you are familiar with the world of hashing, you should now feel at home.

So, somebody tampered with the claims and set their role to ADMIN. The JWT verification will fail as the signature does not match anymore (remember, the signature is generated using the original payload defined by the issuer — where the role is USER).

Generating and signing a new JSON Web Token won’t work for them either — as they (hopefully) don’t have access to the secret or private key you use to sign your tokens. If they do, you are in trouble.

Part 2: Common Misconceptions, FAQs and Techniques

We’ve discussed how JSON Web Tokens work. The value I hope to provide in this article is far beyond that. I hope you will be able to learn something new from this section where I talk about practical use cases, techniques and common misconceptions when using JSON Web Tokens.

JWTs as Passports

JWTs are often used as a user’s passport. All I need in order to send requests on your behalf is your JSON Web Token. Therefore, it is your (and the service provider’s) goal to ensure the token is kept safe from any impersonator.

Always make sure to serve your clients via a secure connection (HTTPS). This will protect you and your clients from man-in-the-middle attacks, as the connection is encrypted.

Note that this approach will not protect you from other types of attacks (XSRF, for example).

Short-lived JWTs and Invalidating Tokens

Short-lived tokens (tokens that expire quickly after they are issued) are highly advised. Some services have their tokens expire as soon as 5 minutes after issuing them.

After the token has expired, the auth server will issue a new access token (this action is called “token refresh”, explanation below) with the most up-to-date claim. For example, if the user role has changed from ADMIN to USER, having short-lived tokens will ensure the user’s token contains the most recent user role.

So to sum it up, short-lived tokens are useful for two main reasons:

  • If your token has been compromised, it will expire quickly after and that will limit the time window during which the attacker is able to use your token and perform operations on your behalf.
  • JWTs are stateless. You cannot invalidate such tokens (that is pretty much the only trade-off in using this type of token). Therefore, short-lived tokens are closest we can get to keeping strong consistency over stuff like user permissions and roles.

JWT Advantages and Should You Trust Your Tokens?

JWTs are stateless. That is a blessing and a curse. To my taste, mostly a blessing.

Why JWTs being stateless is awesome

JWTs are not meant to be stored in a database. In a distributed system, you might have several back-end services for different purposes and business domains. All these services need is a public key (more information on this below) and they can now verify tokens from incoming requests. There is no need to send a request to your auth server for every request (you have no idea how frequently I see this being done). This is a massive performance, resilience and scalability gain.

“But Ariel, why not introduce an API Gateway to check the tokens and route internal traffic to target services?”

You might as well do that. I have no strong opinion about this subject. What I can say, though, is that I always prefer to avoid single points of failure and bottlenecks. However, there are technologies such as KeyCloak that handle this at an ingress level with almost zero overhead.

Should I trust the claims in my token, at all times?

I will leave this decision to you. In general, I put full trust in my JSON Web Tokens and I consider the claims in my tokens to be the source of truth unless the operation is potentially destructive (changing payment method, changing password or email, etcetera). In this case, you could ask the user for an extra factor such as their password.

If you find yourself involving your Auth Service frequently, ensuring permissions against the database for every single operation, you are using JSON Web Tokens wrong.

Refresh Tokens

Nicely bridging from the above section. Refresh Tokens are pretty much a must in every system that uses JWTs.

The way Refresh Tokens work is fairly simple. Upon initial authentication, the user will receive two tokens (note that the names might differ per auth provider):

  • Access Token: Your typical JSON Web Token that is sent with every request. Contains the user claim.
  • Refresh Token: This special kind of token is persisted in a database, mostly owned by an Authentication Service of some sort. This is often not a JWT — but rather a unique hash.

As we already know, the Access Token will be sent with every request (fetch blog posts, create blog post, add comment etcetera) and at some point the token will expired. Then, the front-end will send a refresh request with the refresh token. The auth server will generate a new Access Token (JWT) with the most up-to-date claims, and send it back to the user. The user will use this token until it’s expired, and then refresh again. Over and over.

Refresh tokens can be valid for months, and that is often the case. When the refresh token expires, the user will be signed out and need to authenticate again. Do you remember the last time you had to log into Facebook, Twitter etcetera?

Secret VS Private-Public Key (Keypair)

There are two ways to sign JSON Web Tokens. Let’s consider a very common distributed system where we have several services (Auth Service, Warehouse Service, Order Service and Notification Service).

Common Microservices Architecture

Secret

You could use any string as a secret (for example, dontUseThisSecret123##$%83), and the same secret will be used to verify the signature. However, if you choose to do so, please use a non-trivial secret that is hard to brute-force.

That works okay for monolithic systems. But what if you have several services that serve users? For example; Auth Service, Warehouse Service, Invoice Service, Notification Service and Order Service.

In this case, the Secret approach is seriously risky. All services will need to have access to the secret in order to verify the token. Which means:

  • All services will know the secret. That increases the risk of the secret being exposed or hijacked by an attacker. I mean, when you tell your friend a secret you don’t expect it to be spread around, right?
  • All services technically have the ability to create new tokens — whose responsibility is it to generate tokens? This can introduce semantic problems of ownership.

Key Pair (Public and Private Keys)

This is my favorite approach when working with JWTs. This utilizes a pair of keys — private and public.

Following this approach, the issuer of our token (Auth Service) will use a private key to sign the tokens (using RSA or ECSA algorithms). As the name implies, this key will be private and won’t be shared with any other service.

Any other service interested in verifying incoming tokens will have the public key. Public keys are able to verify tokens but not sign new ones. Therefore, the risks mentioned above are eliminated. There is absolutely no risk in exposing the public keys.

Using this approach, you could even let external parties verify the identity of your users. Which, in some cases, can actually be useful.

Where Should I Store The JSON Web Tokens?

This is probably the most common question you will see about JSON Web Tokens on Stackoverflow. I will try to touch it briefly, but would rather refer you to other external resources as I am no security expert.

You always have to remember that JWTs are passports. If somebody gets access to one of your user’s tokens, he/she can send requests on behalf of you. This is bad.

Storing tokens in Local Storage is incredibly popular because it’s comfortable. However, this is not the most secure way to do things. It’s very XSS (Cross-Site-Scripting) vulnerable.

Storing your tokens in a HttpOnly cookie (not a regular cookie) would be preferable. It would be better against XSS attacks, but still vulnerable to CSRF attacks. This can of course introduce annoying challenges in terms of CORS policies, but hey — it is security we’re dealing with here.

I advise you to learn more from this Stackoverflow answer.

What If I Want to Encrypt My Tokens Anyway?

In some cases you might want to apply an encryption over your token, to prevent hijackers from reading your claims. This is mostly common in server-to-server communication.

That is totally fine — feel free to apply whatever encryption you prefer over your token, as long as the receiving end can securely decrypt and view the token.

Either way, remember that performing communication over HTTPS is a must and will dramatically increase communication security.

Summary

This is my first post on Medium, and also my best attempt at sheding some light on the whole “JSON Web Token thing”. Hopefully this helped you. I would like to welcome any suggestions and extra information in the comments. I will do my best to keep this article up-to-date with recents developments and techniques.

___

Useful Resources

  • jwt.io by Auth0: documentation and interactive decoding of JSON Web Tokens
  • jsonwebtoken at NPM: my favorite library for dealing with JSON Web Tokens
  • JSON Web Token on Wikipedia
  • JSON Web Token (JWT) RFC by Internet Engineering Task Force (IETF)

Let’s Get in Touch

You are most welcome to follow me here on Medium. In addition, feel free to check out:

  • NestJS Zero to Hero — Modern TypeScript Back-end Development on Udemy (4.7 ⭐ with over 70,000 students)
  • Serverless Framework Bootcamp on Udemy (4.7 ⭐ with over 30,000 students)
  • My Twitter ProfileFollow me for free educational content and discounts.
  • My LinkedIn Profile: Let’s connect!
  • Feel free to contact me at ariel@codingly.io
Jwt
Web Development
Software Development
Nodejs
Security

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.luyixian.cn/news_show_286439.aspx

如若内容造成侵权/违法违规/事实不符,请联系dt猫网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

第1章-JVM与Java体系结构

1、本系列博客,主要是面向Java8的虚拟机。如有特殊说明,会进行标注。 2、本系列博客主要参考尚硅谷的JVM视频教程,整理不易,所以图片打上了一些水印,还请读者见谅。后续可能会加上一些补充的东西。 3、尚硅谷的有些视频…

国家出手管人工智能AI了

我是卢松松,点点上面的头像,欢迎关注我哦! 全球都在封杀AI,国家也出手了,人工智能AI的强监管来了!这次反应速度算是很快了。国家出手,AI必须管。 国家网信办拟针对生成式人工智能服务出台管理办法&#…

【Redis数据库】异地公网远程登录连接Redis教程

文章目录1. Linux(centos8)安装redis数据库2. 配置redis数据库3. 内网穿透3.1 安装cpolar内网穿透3.2 创建隧道映射本地端口4. 配置固定TCP端口地址4.1 保留一个固定tcp地址4.2 配置固定TCP地址4.3 使用固定的tcp地址连接转发自CSDN远程穿透的文章:公网远程连接Redi…

算法之归并排序

文章目录一、归并排序(递归版)二、归并排序(非递归版)一、归并排序(递归版) 归并排序思想:将数组划分为两个区间,左区间,右区间 然后对这两个区间内容进行排序 &#xff…

linux 修改主机名称

1、hostname命令进行临时更改 如果只需要临时更改主机名&#xff0c;可以使用hostname命令&#xff1a; sudo hostname <new-hostname> 例如&#xff1a; 只需重新打开session终端&#xff0c;就能生效&#xff0c; 但是&#xff0c;重启计算机后会回到旧的主机名。…

总结一下Redis的缓存雪崩、缓存击穿、缓存穿透

缓存是提高系统性能的一种常见手段&#xff0c;其中Redis是一种常用的高性能缓存数据库。但是在使用缓存时&#xff0c;可能会遇到一些问题&#xff0c;比如缓存击穿、缓存穿透、缓存雪崩等问题&#xff0c;本文将介绍这些问题的概念、原因以及解决方案。 缓存击穿 缓存击穿指…

深度学习中的目标识别

博主简介 博主是一名大二学生&#xff0c;主攻人工智能研究。感谢让我们在CSDN相遇&#xff0c;博主致力于在这里分享关于人工智能&#xff0c;c&#xff0c;Python&#xff0c;爬虫等方面知识的分享。 如果有需要的小伙伴可以关注博主&#xff0c;博主会继续更新的&#xff0c…

拓展系统命令

文章目录拓展系统命令使用方式拓展系统命令快速运行方法命令 - ZFASTRUN安全运行方法命令 - ZFASTSAFERUN快速运行Query方法命令 - ZFASTQUERY安全运行Query方法 命令 - ZSAFEQUARY防止调试时误将数据提交命令 - ZTRN在Terminal执行SQL语句命令 - ZSQL安全Global命令 - ZSAFEKI…

Windows命令提示符之常见命令--动态更新

序言&#xff1a; 在大家接触Windows电脑的过程中&#xff0c;一般是直接通过鼠标来进行操作&#xff0c;很少甚至没有用到过命令来执行操作&#xff0c;而想必大家都看过电影里面的黑客大神都是通过密密麻麻的指令来操作的&#xff0c;并且执行的速度也会比我们用鼠标块&…

二进制插入与查找组成一个偶数最接近的两个素数

二进制插入 链接&#xff1a;二进制插入_牛客题霸_牛客网 (nowcoder.com) 描述&#xff1a;给定两个32位整数n和m&#xff0c;同时给定i和j&#xff0c;将m的二进制数位插入到n的二进制的第j到第i位,保证n的第j到第i位均为零&#xff0c;且m的二进制位数小于等于i-j1&#xff…

在unreal中的基于波叠加的波浪水面材质原理和制作

关于水的渲染模型 如何渲染出真实的水体和模拟&#xff0c;是图形学&#xff0c;游戏开发乃至仿真领域很有意思的一件事 记得小时候玩《Command & Conquer: Red Alert 3》&#xff0c;被当时的水面效果深深震撼&#xff0c;作为一款2008年出的游戏&#xff0c;现在想起它…

没想到大厂Adobe还有这些“猫腻”!

北京时间周四晚间&#xff0c;图像及视频生产力工具大厂Adobe发布公告&#xff0c;宣布旗下的视频创作应用Premiere Pro将喜提一系列新的AI功能。这也是Adobe上个月发布AIGC创作功能“萤火虫”后的最新动作。综合Adobe的官方公告和演示视频&#xff0c;最大亮点就是基于文字的视…

什么是线性回归?线性回归有什么特征?

什么是线性回归 线性回归定义与公式 线性回归(Linear regression)是利用回归方程(函数)对一个或多个自变量(特征值)和因变量(目标值)之间关系进行建模的一种分析方式。 特点&#xff1a;只有一个自变量的情况称为单变量回归&#xff0c;多于一个自变量情况的叫做多元回归 线…

剑指 Offer (第 2 版)

&#xff08;简单&#xff09;剑指 Offer 03. 数组中重复的数字 找出数组中重复的数字。 在一个长度为 n 的数组 nums 里的所有数字都在 0&#xff5e;n-1 的范围内。数组中某些数字是重复的&#xff0c;但不知道有几个数字重复了&#xff0c;也不知道每个数字重复了几次。请…

python实现图像的平移、镜像、旋转(不调用CV库)

python实现图像的平移、镜像、旋转&#xff08;不调用CV库&#xff09; 老师布置的作业。。。。。 平移图像 图像的平移在几何变换中算是最简单的变换之一&#xff0c;话不多说&#xff0c;直奔主题 由图可知&#xff0c;在opencv中图像的原点一般为左上角&#xff0c;设初始…

1 Spark的环境搭建

1 Spark的环境搭建 1.1 Windows - Spark安装 一、下载并安装软件 \1. 下载并安装Java8&#xff1a;https://www.oracle.com/java/technologies/downloads/ &#xff08;1&#xff09; 原因&#xff1a;Spark由Scala语言开发。而Scala代码会被编译成Java字节码。因此Spark的…

总结821

学习目标&#xff1a; 4月&#xff08;复习完高数18讲内容&#xff0c;背诵21篇短文&#xff0c;熟词僻义300词基础词&#xff09; 学习内容&#xff1a; 暴力英语&#xff1a;早上背颂并默写第19篇文章《I always knew I was going to be rich》&#xff0c;还有两三篇就达成…

一图看懂 xlwt 模块:读写 Excel 文件的数据和格式信息, 资料整理+笔记(大全)

本文由 大侠(AhcaoZhu)原创&#xff0c;转载请声明。 链接: https://blog.csdn.net/Ahcao2008 一图看懂 xlwt 模块&#xff1a;读写 Excel 文件的数据和格式信息, 资料整理笔记&#xff08;大全&#xff09;摘要模块图类关系图模块全展开【xlwt】统计常量模块1 xlwt.compat2 xl…

中核科技:科技匠心 智启未来

​  2023 年4月 13—15 日&#xff0c;2023年易派客工业品展览会、石油石化工业展览会、第七届中国石油和化工行业采购年会&#xff0c;在苏州国际博览中心胜利召开。本次展会展览面积53000平方米&#xff0c;参展企业500余家&#xff0c;汇集了中国工业制造领域的大型国企央…

第一章 webpack与构建发展简史

官方loader和插件 Loaders | webpack Plugins | webpack 为什么需要构建工具&#xff1f; 初识webpack webpack默认配置文件&#xff1a;webpack.config.js 可以通过webpack --config <config_file_name>指定配置文件 rules是个数组&#xff0c;一个打包配置可以有多…