Hello everyone, I am Orange long, yesterday shared the “OAuth 2.0 licensing agreement”, we can review the specific four, each of the characteristics, applicable business scenarios, the most complete licensing code mechanism process is what.

Today, Tangerine will share “token mechanism” with you.

What is the core of OAuth 2.0?

Looking back at the story of user visits to customers in the first OAuth article, there is a key term temporary access to qr codes

When the user shows a series of information and actions to get the QR code, it can go to meet the customer.

This qr code goes back to OAuth, which is actually a token. So what exactly is a token?

In fact, it is the result after authorization. The previous series of operations are to obtain the final token. Only with token credentials can we access the routes, services, resources and so on that the token can request.

So the core of OAuth 2.0 is to issue access tokens and use access tokens.

Tokens in OAuth 2.0

OAuth’s website does not limit the format of the tokens but currently only supports one, bearer.

It can be a random string or a custom data structure, but it must meet three criteria.

Unique, discontinuous, and unpredictable.

Third, JWT

1. What is it

JSON Web Token is an open standard based on the RFC7519 protocol that defines a compact, self-contained way to securely transfer data between parties as JSON objects.

 

Simple understanding: it is a set of customized structured data that generates tokens in a structured way

One is to make the data returned to the client meaningful

On the other hand, self-coding ability and strong expansibility

You can also secure your data with signatures, and JWT needs to be transmitted in environments such as HTML and HTTP

On the one hand, you need to do URLEncode to protect against garbled and lost data

The other is encryption to avoid theft

Introduction: Jwt. IO/Introductio…

Tangerine chang translated: github.com/AFlymamba/t…

 

Of 2,

The interior contains three parts, header, payload and signature, which are connected by a. (dot)

Here is a simple JWT example:

header.payload.signature
Copy the code

1) Header

The first part of a JWT is the Header, which usually consists of two parts, Type and sign

Type denotes the token type, in this case “JWT”

In addition, sign indicates the signature algorithm adopted, which can be HMAC SHA256 or RSA

Here is a simple example:

{
  "type": "JWT",
  "sign": "HS256"
}
Copy the code

Finally, the generated header needs to URLEncode this JSON string to get a string.

JSONObject headerJson = JSONUtil.createObj();
String headerStr = base64UrlEncode(headerJson);
Copy the code
  • It’s a payload.

The second part of the JWT is Payload, which is the most valuable part of the JWT

These include Claims, which are Claims about entities (usually users) and other data

Simple understanding is the part of the data that is customized.

JWT officially has three types of declaration, namely registration declaration, public declaration and private declaration.

Registration declarations: A set of declarations predefined by the framework, each of which is not mandatory, but recommended, to provide a useful, actionable set of data.

Public statement: JWT user – defined, but need to be careful not to conflict with official data.

Private declaration: Applies to data transmission. After the communication parties agree on the data structure, the data can be shared.

Payload is a compact declaration of three characters long.

In particular, learn the official recommendation: the Registration Statement

Selected data definitions for scenarios as examples

Iss: Issuer (JWT)

Exp: expression time (JWT expiration time)

Sub: Subject

Aud: Audience

The json structure of the payload is shown as follows:

{
    "sub": 1,
    "name": "John",
    "admin": true
}
Copy the code

Finally, the generated payload is a string of JSON strings that you need to URLEncode to get a string.

 JSONObject payloadJson = JSONUtil.createObj();
 String payloadStr = base64UrlEncode(payloadJson); 
Copy the code
  • Signature (= signature)

The second part of JWT is Signature, and JWT needs to be transmitted over the network

With headers and payloads carrying data, relevant encryption algorithms need to be done to ensure security

The signature is the result of encrypting header.payload data.

Before creating a signature, obtain the header, payload, secret, and signature algorithm. The following is an example for generating a signature:

String headerStr = base64UrlEncode(header); String payloadStr = base64UrlEncode(payload); String secret = "xxxxx"; String headerPayload = headerStr + "." + payloadStr; String signature = HMACSHA256(headerPayload, secret);Copy the code

What are the functions of signature?

(1) Ensure that header and payload are not modified during transmission.

② If the signature algorithm uses asymmetric encryption (such as RSA), it can verify the signature to determine who owns the private key.

Combining the three pieces of information, you get back to what JWT is, which is essentially a string of headers.payload-signature.

3. How to use JWT

In an authorized login scenario, the server issues a token to the client after the user successfully logs in

After that, each request of the user needs to carry the token. If the token is not carried, it is considered to have no credentials and cannot be accessed. If the token is carried legally and reasonably, it is allowed.

Consider: how to submit token?

OAuth officially has three ways, as follows

Form-encoded Body Parameter

Method 2: URI Query Parameter

Mode 3: Authorization Request Header

4. Advantages and disadvantages of JWT

Everything has two sides.

Advantages:

1) Has meaning compared to random strings (self-encoding capability)

2) Encryption protects the transmission process of header and payload from theft

Disadvantages:

Biggest weakness: What is done cannot be undone

After JWT is issued from the server, it is actually rampage during the validity period, it is not stored on the server, it is difficult to change the JWT state.

Don’t open an API in your code to test colleagues to obtain tokens. If you do, develop manual generation.

Open source components

1. Why open source

Header and payload in the JWT need to be base64URLEncode. To ensure the security of transmission, encryption algorithms need to be introduced for signatures. Handwritten signatures are prone to errors and high security risks.

Open source components have a feature that, out of the box, they mask the complexity of the underlying implementation (for example, encapsulating Base64 operations, symmetric/asymmetric algorithm implementations, etc.), allowing developers to focus on the upper API calls and business implementation.

When choosing open source components in JWT, we care about two things: API level and open source activity.

API level: whether the interface for generating JWT and verifying JWT is provided.

Open source activity: indicates that there are bugs to be found.

2, JJWT

Liverpoolfc.tv: github.com/jwtk/jjwt

The following example shows how to use JJWT simply in SpringBoot:

1) Introduce dependencies

<! -- JWT --> <dependency> <groupId> IO. Jsonwebtoken </groupId> <artifactId> JJWT </artifactId> <version>0.7.0</version> </dependency>Copy the code

2) Generate JWT

# claim Map<String, Object> Claims = new HashMap<>(2); claims.put("authId", activityUser.getId()); claims.put("authRole", "user"); String jwt = Jwts.builder() .setClaims(claims) .setSubject("api") .setIssuedAt(new Date()) .setExpiration(expirationAt) .signWith(SignatureAlgorithm.HS512, signingKey) .compact();Copy the code

3) Use JWT

Here the JWT is submitted as the Authorization Header Header

4) Verify JWT

① Custom SpringMVC interceptor, in the preHandler method to intercept

  • Custom interceptors
public class TokenInterceptor implements HandlerInterceptor { @Override public boolean preHandler(HttpServletRequest Request, HttpServletResponse Response, Object handler) throws Exception {// Easy to display, hard coding String tokenKey = "Bearer"; String tokenSecret = "xxx"; Token = request. GetHeader (tokenKey); // call Jwts open source tools to provide a method, Claims = jwts.parser ().setSigningKey(signingKey).parseclaiMSjws (tokenKey).getBody(); // Hard code Boolean judgeResult = this.isNullOrExpired(Claims); // Subsequent business logic}} /** * Determines whether the token has expired ** @param Claims Map object after the token has been decrypted. * @return true expires, otherwise false. */ public boolean isNullOrExpired(Claims claims) { return ObjectUtil.isNull(claims) || DateUtil.date().after(claims.getExpiration()); }Copy the code
  • Inject the Spring container
@Component public class InterceptorConfig implements WebMvcConfigurer { @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new TokenInterceptor ()) .addPathPatterns("/api/**") .excludePathPatterns("/api/oauth/login"); }}Copy the code

② If the check fails, the back end responds to 401

{"message": "user session expired, please log in again!" , "statusCode": 401 }Copy the code

③ If the check succeeds, the service interface is accessed

Five, the summary

OAuth 2.0: Tokenization and Tokenization

1. The core of OAuth 2.0 is to issue tokens and use access tokens.

2. The advantages and disadvantages of JWT

3. Use of open source JWT component JJWT.

The next article will give you the interpretation of “hand in hand to take you to the ground to achieve the four roles in OAuth 2.0”, thank you for your attention, if you feel benefit, welcome to like, forward, comment, thank you for recognition!