JWT based authentication

Introduction to JWT


JWT (json web token) is a JSON-based open standard for transferring claims between web application environments.
JWT claims are generally used to transfer authenticated user identity information between identity providers and service providers in order to obtain resources from resource servers. For example, it is used for user login.


Session-based login authentication


In the traditional user login authentication, because http is stateless, the session method is used. If the user logs in successfully, the server will guarantee a session, and of course will give the client a sessionId, the client will save the sessionId in a cookie, and each request will carry this sessionId.


The cookie+session mode is usually stored in memory, and the session sharing problem that the service will face from single service to multi-service, as the number of users increases, the overhead will increase. This is not the case with JWT, only the server needs to generate a token, the client saves this token, and each request carries this token, and the server can authenticate and parse it.


What the JWT looks like after generating the encoding


eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoiend6IiwiYWdlIjoiMTgifQ.UQmqAUhUrpDVV2ST7mZKyLTomVfg7sYkEjmdDI5XF8Q

Composition of JWT

The first part we call it the header (header), the second part we call it the payload (payload), the third part is the visa (signature).

header

The header of jwt carries two parts of information:

  • Declare type, here is jwt
  • The algorithm that declares encryption usually uses HMAC SHA256 directly

The full header looks like the following JSON:

{
  'typ': 'JWT',
  'alg': 'HS256'
}

The header is then base64 encrypted (this encryption can be decrypted symmetrically), forming the first part.

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9

playload

The payload is where the valid information is stored. The name seems to refer to the cargo carried on the plane, and these valid information consists of three parts

  • Declaration registered in the standard
  • public statement
  • private statement

标准中注册的声明 (建议但不强制使用) :

  • iss: jwt签发者
  • sub: jwt所面向的用户
  • aud: 接收jwt的一方
  • exp: jwt的过期时间,这个过期时间必须要大于签发时间
  • nbf: 定义在什么时间之前,该jwt都是不可用的.
  • iat: jwt的签发时间
  • jti: jwt的唯一身份标识,主要用来作为一次性token,从而回避重放攻击。

公共的声明 :
公共的声明可以添加任何的信息,一般添加用户的相关信息或其他业务需要的必要信息.但不建议添加敏感信息,因为该部分在客户端可解密.

私有的声明 :
私有声明是提供者和消费者所共同定义的声明,一般不建议存放敏感信息,因为base64是对称解密的,意味着该部分信息可以归类为明文信息。

定义一个payload:

{
  "name": "zwz",
  "age": "18"
}

然后将其进行base64加密,得到Jwt的第二部分。

eyJuYW1lIjoiend6IiwiYWdlIjoiMTgifQ

signature

jwt的第三部分是一个签证信息,这个签证信息由三部分组成:

  • header (base64后的)
  • payload (base64后的)
  • secret

这个部分需要base64加密后的header和base64加密后的payload使用.连接组成的字符串,然后通过header中声明的加密方式进行加盐secret组合加密,然后就构成了jwt的第三部分。

UQmqAUhUrpDVV2ST7mZKyLTomVfg7sYkEjmdDI5XF8Q
密钥secret是保存在服务端的,服务端会根据这个密钥进行生成token和验证,所以需要保护好。

java方式实现

Maven

<dependency>
    <groupId>com.auth0</groupId>
    <artifactId>java-jwt</artifactId>
    <version>3.1.0</version>
</dependency>
加密代码
[java]  view plain  copy
  1. public class JwtToken {  
  2.     public static String createToken() throws Exception{  
  3.         Map<String, Object> map = new HashMap<String, Object>();  
  4.         map.put("alg""HS256");  
  5.         map.put("typ""JWT");  
  6.         String token = JWT.create()  
  7.                 .withHeader(map)//header  
  8.                 .withClaim("name""zwz")//payload  
  9.                 .withClaim("age""18")  
  10.                 .sign(Algorithm.HMAC256("secret"));//加密  
  11.         return token;  
  12.     }  
  13. }  

验证代码
[java]  view plain  copy
  1. public static void verifyToken(String token,String key) throws Exception{  
  2.         JWTVerifier verifier = JWT.require(Algorithm.HMAC256(key))  
  3.                 .build();   
  4.             DecodedJWT jwt = verifier.verify(token);  
  5.             Map<String, Claim> claims = jwt.getClaims();  
  6.             System.out.println(claims.get("name").asString());  
  7.     }  

JWT总结

1、因为json的通用性,所以JWT是可以进行跨语言支持的,像JAVA,JavaScript,NodeJS,PHP等很多语言都可以使用。
2、payload部分,JWT可以在自身存储一些其他业务逻辑所必要的非敏感信息。
3、便于传输,jwt的构成非常简单,字节占用很小,所以它是非常便于传输的。它不需要在服务端保存会话信息, 所以它易于应用的扩展

JWT官方网站:https://jwt.io/

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325772365&siteId=291194637