JWT(Json Web Token):一种在Web应用中安全传递信息的规范



What is JSON Web Token?

JSON Web Token (JWT) is an open standard (RFC 7519) that defines a compact and self-contained way for securely transmitting information between parties as a JSON object. This information can be verified and trusted because it is digitally signed. JWTs can be signed using a secret (with the HMAC algorithm) or a public/private key pair using RSA.

JSON Web Token(JWT)是一个开放规范(RFC7519),该规范为安全的信息传递定义了一个紧凑自包含的方式。由于信息是被数字签名的,所以信息是可以被认证和信任的。JWT可以通过一个秘钥也可以通过公钥/私钥对的方式进行签名。

Although JWTs can be encrypted to also provide secrecy between parties, we will focus on signed tokens. Signed tokens can verify the integrity of the claims contained within it, while encrypted tokens hide those claims from other parties. When tokens are signed using public/private key pairs, the signature also certifies that only the party holding the private key is the one that signed it.


Let's explain some concepts further.

  • Compact: Because of their smaller size, JWTs can be sent through a URL, POST parameter, or inside an HTTP header. Additionally, the smaller size means transmission is fast.

  • Self-contained: The payload contains all the required information about the user, avoiding the need to query the database more than once.


  • 紧凑: 由于他们信息传递内容之小,JWTs可以通过URL、Post参数或是HTTP头的方式进行发送。另外,传递的信息小意味着传输快。

  • 自包含: 载荷包含了所有关于用户所需要的信息,避免了查询数据库超过一次的需要。

When should you use JSON Web Tokens?

Here are some scenarios where JSON Web Tokens are useful:

  • Authentication: This is the most common scenario for using JWT. Once the user is logged in, each subsequent request will include the JWT, allowing the user to access routes, services, and resources that are permitted with that token. Single Sign On is a feature that widely uses JWT nowadays, because of its small overhead and its ability to be easily used across different domains.

  • Information Exchange: JSON Web Tokens are a good way of securely transmitting information between parties. Because JWTs can be signed—for example, using public/private key pairs—you can be sure the senders are who they say they are. Additionally, as the signature is calculated using the header and the payload, you can also verify that the content hasn't been tampered with.


  • 认证: 这是使用JWT最常用的应用场景。只要用户已登录,后续的每次请求都将包含JWT,从而使得用户能够获取只有令牌才被允许的服务和资源。单点登录是目前广泛使用JWT的一个功能,因为它的开销很小,并且具有很容易跨领域使用的能力。

  • 信息交换: JWTs是双方之间安全信息传递的一种良好方式。由于JWTs可以被签名,比如使用公钥/私钥对,你可以确保发送者就是他所说的那个人。另外,由于签名是使用头部和载荷通过计算得到的,所以通过比较签名可以验证内容没有被篡改。

What is the JSON Web Token structure?

In its compact form, JSON Web Tokens consist of three parts separated by dots (.), which are:

  • Header
  • Payload
  • Signature

Therefore, a JWT typically looks like the following.



  • 头部
  • 载荷
  • 签名



Let's break down the different parts.



The header typically consists of two parts: the type of the token, which is JWT, and the hashing algorithm being used, such as HMAC SHA256 or RSA.


For example:

  "alg": "HS256",
  "typ": "JWT"

Then, this JSON is Base64Url encoded to form the first part of the JWT.



The second part of the token is the payload, which contains the claims. Claims are statements about an entity (typically, the user) and additional metadata.There are three types of claims: registered, public, and private claims.

  • Registered claims: These are a set of predefined claims which are not mandatory but recommended, to provide a set of useful, interoperable claims. Some of them are: iss (issuer), exp (expiration time), sub (subject), aud (audience), and others.

    Notice that the claim names are only three characters long as JWT is meant to be compact.

  • Public claims: These can be defined at will by those using JWTs. But to avoid collisions they should be defined in the IANA JSON Web Token Registry or be defined as a URI that contains a collision resistant namespace.

  • Private claims: These are the custom claims created to share information between parties that agree on using them and are neither registered or public claims.


  • 注册声明: 这里有一组预定义的声明,这些声明不是强制的,而是推荐的,用于提供一组有用的可互操作的声明。其中一些是:iss(发行者),exp(过期时间),sub (subject), aud(观众),以及其他。


  • 公共声明: 这些声明可以由使用JWTs的人进行定义. 但是为了避免冲突,这些声明应该在IANA JSON Web Token Registry中定义过,或者被定义为包含一个抗冲突名称空间的URI。

  • 私有声明: 这些是自定义的声明,用于在双方同意使用它们的情况下共享信息,而不是注册或公开声明。

An example payload could be:


  "sub": "1234567890",
  "name": "John Doe",
  "admin": true

The payload is then Base64Url encoded to form the second part of the JSON Web Token.



To create the signature part you have to take the encoded header, the encoded payload, a secret, the algorithm specified in the header, and sign that.


For example if you want to use the HMAC SHA256 algorithm, the signature will be created in the following way:

举个例子,如果你想使用HMAC SHA256算法,那么签名将通过如下的方式计算获得:

  base64UrlEncode(header) + "." +

The signature is used to verify the message wasn't changed along the way, and, in the case of tokens signed with a private key, it can also verify that the sender of the JWT is who it says it is.


Putting all together

The output is three Base64-URL strings separated by dots that can be easily passed in HTML and HTTP environments, while being more compact when compared to XML-based standards such as SAML.


The following shows a JWT that has the previous header and payload encoded, and it is signed with a secret.


Encoded JWT

If you want to play with JWT and put these concepts into practice, you can use jwt.io Debugger to decode, verify, and generate JWTs.

如果您想要使用JWT并将这些概念付诸实践,您可以使用jwt.io Debugger进行解码、验证和生成JWTs。

JWT.io Debugger

How do JSON Web Tokens work?

JSON Web Tokens是如何工作的?

In authentication, when the user successfully logs in using their credentials, a JSON Web Token will be returned and must be saved locally (typically in local storage, but cookies can be also used), instead of the traditional approach of creating a session in the server and returning a cookie.


There are security considerations that must be taken into account with regards to the way tokens are stored. These are enumerated in Where to Store Tokens.

在令牌以什么样的方式存储这个问题上,有一些安全性的问题需要纳入到考虑范围。这些问题在Where to Store Tokens进行了说明。

Whenever the user wants to access a protected route or resource, the user agent should send the JWT, typically in the Authorization header using the Bearer schema. The content of the header should look like the following:


Authorization: Bearer <token>

This is a stateless authentication mechanism as the user state is never saved in server memory.The server's protected routes will check for a valid JWT in the Authorization header, and if it's present, the user will be allowed to access protected resources. As JWTs are self-contained, all the necessary information is there, reducing the need to query the database multiple times.


This allows you to fully rely on data APIs that are stateless and even make requests to downstream services. It doesn't matter which domains are serving your APIs, so Cross-Origin Resource Sharing (CORS) won't be an issue as it doesn't use cookies.


The following diagram shows this process:


How does a JSON Web Token works

Do note that with signed tokens, all the information contained within the token is exposed to users or other parties, even though they are unable to change it. This means you should not put secret information within the token.


Why should we use JSON Web Tokens?

我们为什么要用JSON Web Tokens?

Let's talk about the benefits of JSON Web Tokens (JWT) when compared to Simple Web Tokens (SWT) and Security Assertion Markup Language Tokens (SAML).

与简单的Web令牌(SWT)和安全断言标记语言令牌(SAML)相比,让我们讨论一下JSON Web令牌(JWT)的好处。

As JSON is less verbose than XML, when it is encoded its size is also smaller, making JWT more compact than SAML. This makes JWT a good choice to be passed in HTML and HTTP environments.


Security-wise, SWT can only be symmetrically signed by a shared secret using the HMAC algorithm. However, JWT and SAML tokens can use a public/private key pair in the form of a X.509 certificate for signing. Signing XML with XML Digital Signature without introducing obscure security holes is very difficult when compared to the simplicity of signing JSON.


JSON parsers are common in most programming languages because they map directly to objects. Conversely, XML doesn't have a natural document-to-object mapping. This makes it easier to work with JWT than SAML assertions.


Regarding usage, JWT is used at Internet scale. This highlights the ease of client-side processing of the JSON Web token on multiple platforms, especially mobile.

关于使用,JWT在互联网规模使用。这突出显示了在多个平台上的JSON Web标记的客户端处理的易用性,尤其是移动端。

Comparing the length of an encoded JWT and an encoded SAMLComparison of the length of an encoded JWT and an encoded SAML

If you want to read more about JSON Web Tokens and even start using them to perform authentication in your own applications, browse to the JSON Web Token landing page at Auth0.

如果您想阅读更多关于JSON Web令牌的内容,甚至开始使用它们在您自己的应用程序中执行身份验证,请浏览到Auth0的JSON Web Token landing page页面。
发布了198 篇原创文章 · 获赞 219 · 访问量 122万+

Symfony LexikJWTAuthenticationBundle无法进行身份验证


<div class="post-text" itemprop="text"> <p>I'm encountering an issue with the JWT Auth bundle on Symfony 3. I've followed instructions from their github README but just can't seem to figure out where I've gone wrong or what is going wrong.</p> <p>I am using Symfony 3.1.1, With LexikJWTAuthenticationBundle 2.0 And FriendsofSymfony userbundle.</p> <p><strong>The problem:</strong> Whenever I try to log in as instructed in their example via (with user and password substituted):</p> <pre><code>curl -X POST -d _username=johndoe -d _password=test </code></pre> <p>I get:</p> <pre><code>{"code":401,"message":"Bad credentials"} </code></pre> <p>If I generate the token manually via:</p> <pre><code> $jwtManager = $this->container->get('lexik_jwt_authentication.jwt_manager'); $userManager = $this->container->get('fos_user.user_manager'); $user = $userManager->findUserByEmail('emailhere'); dump($jwtManager->create($user)); </code></pre> <p>I get given quite a lengthy token. And then using that in postman as a Header with key "Authorization" value: "Bearer "</p> <p>I then try to call an endpoint under the firewalled url and the failure_handler is triggered. It manages to extract from the token the data, ie the email I encoded in the token and so on. But I always get the failure.</p> <p>My other data is:</p> <p>security.yml security: encoders: FOS\UserBundle\Model\UserInterface: bcrypt</p> <pre><code>role_hierarchy: ROLE_ADMIN: ROLE_USER ROLE_SUPER_ADMIN: ROLE_ADMIN # http://symfony.com/doc/current/book/security.html#where-do-users-come-from-user-providers providers: in_memory: memory: ~ fos_userbundle: id: fos_user.user_provider.username firewalls: # disables authentication for assets and the profiler, adapt it according to your needs dev: pattern: ^/(_(profiler|wdt)|css|images|js)/ security: false login: pattern: ^/api/login stateless: true anonymous: true form_login: check_path: /api/login_check success_handler: lexik_jwt_authentication.handler.authentication_success failure_handler: lexik_jwt_authentication.handler.authentication_failure require_previous_session: false api: pattern: ^/api stateless: true guard: authenticators: - lexik_jwt_authentication.jwt_token_authenticator main: pattern: ^/ form_login: provider: fos_userbundle # csrf_token_generator: security.csrf.token_manager logout: true anonymous: true </code></pre> <p>config.yml</p> <pre><code>lexik_jwt_authentication: private_key_path: %jwt_private_key_path% public_key_path: %jwt_public_key_path% pass_phrase: %jwt_key_pass_phrase% token_ttl: %jwt_token_ttl% # key under which the user identity will be stored in the token payload user_identity_field: email # token encoding/decoding settings encoder: # token encoder/decoder service - default implementation based on the namshi/jose library service: lexik_jwt_authentication.encoder.default # crypto engine used by the encoder service crypto_engine: openssl # encryption algorithm used by the encoder service signature_algorithm: RS256 # token extraction settings token_extractors: authorization_header: # look for a token as Authorization Header enabled: true prefix: Bearer name: Authorization cookie: # check token in a cookie enabled: false name: BEARER query_parameter: # check token in query string parameter enabled: false name: bearer </code></pre> <p>routing.yml</p> <pre><code>api_login_check: path: /api/login_check </code></pre> <p>If anyone has any suggestions please let me know. I'm stumped over this.</p> </div> 问答


©️2019 CSDN 皮肤主题: 程序猿惹谁了 设计师: 上身试试