This is the seventh day of my participation in the August More text Challenge. For details, see: August More Text Challenge

1. Knowledge

  • 1 Authentication and Authorization

Authentication: Mainly to confirm identity

Authorization: Grants access to the system

For example: zhang SAN login educational administration system, when the input user name and password (login now generally need to input verification code, etc.) this is a process of certification If authentication is successful, enter the system, and have different permissions to each role, students can only see their own achievements, the achievement of other students cannot view This is the permissions. Today’s JWT can be used for authorization

  • Definition 2 JWT

JWT(JSON Web Token) It defines a compact and self-contained way to securely transfer information between parties as JSON objects. According to this definition, the transfer object is in JSON format.

  • 3 Application Scenarios

3.1 JWT can be used to authorize users to log in with this JWT. Users can access routes, services and resources allowed by this JWT. (Common single sign-on)

3.2 Information Exchange Because JWT can encrypt (symmetric encryption: one public key; asymmetric encryption: public/private key), the authenticity of information can be verified during transmission

  • 4 structure

The JWT structure consists of three parts: the title. Payload. Signature => xxxx.YYYY.zzzz

Header: Usually consists of two parts: token type (JWT); Use the signature algorithm (e.g. HMAC, RSA) and encode the title in Base64Url to form the first part of JWT

eg: { "alg": "HS256", "typ": "JWT" }

Payload: Simple understanding: the information here is the information you want to carry, such as the user name, login time, etc. in JWT can be added here, but the information here is best unclassified, because the JWT is encrypted, so it is not easy to change, but easy to read

Eg: There is a registration statement/public statement

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

Signature: Create the signature section by adding the first two together: If you are using the HMAC SHA256 algorithm, the signature will be created as follows, where secret is the signature algorithm used in the first section

HMACSHA256( base64UrlEncode(header) + "." + base64UrlEncode(payload), secret)

2. Code examples

Simple use with SpringBoot

1. Write a simple utility class to generate tokens using JWT; Authentication token

public class JwtUtil { private String token; Public static String CreateToken(TokenInfo TokenInfo){// The symmetric Algorithm uses the same key Algorithm Algorithm = Algorithm.HMAC256("secret"); String token = ""; try{ token = JWT.create().withIssuer(tokenInfo.getIssuer()) .sign(algorithm); }catch (JWTCreationException exception){throw new UserException(" Failed to create token: "+exception.getMessage()); } return token; } public static void verifyToken(String token){DecodedJWT DecodedJWT = null; try { JWTVerifier verifier = JWT.require(Algorithm.HMAC256("secret")).build(); decodedJWT = verifier.verify(token); }catch (Exception e){throw new UserException("token validation failed "); }}}Copy the code

Take a look at the JWT source code: jwt.create () jwt.java

Jwtcreator.java (for JWT generation, the main thing is to call the corresponding method in this Java class)

Jwtutil. CreateToken can be used to create a token when you log in to jwtutil. CreateToken. When some functions can only be operated by the user with the corresponding permission, you need to verify whether the JWT that the user carries has the jwtutil. verifyToken

When users log in with this JWT, they can access routes, services and resources allowed by this JWT. For example, in a system, many operations can only be accessed after logging in, so we can set up a unified interceptor to intercept, if they are not logged in, they cannot access these interfaces. If you have a custom interface to skip authentication, you do not need to check the following code:

@Component public class JwtInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { String token = request.getHeader("token"); // If not mapped to the method directly through if (! (handler instanceof HandlerMethod)) return true; HandlerMethod = (HandlerMethod) HandlerMethod = (HandlerMethod) handler; Method method = handlerMethod.getMethod(); / / check for passtoken validation If you have just skip authentication One passToken is their custom annotations if (method. IsAnnotationPresent (passToken. Class)) {passToken annotation = method.getAnnotation(PassToken.class); if (annotation ! = null) return true; } if (token == null) throw new UserException(" Log in again without token "); // verifyToken jwtutil.verifytoken (token); return HandlerInterceptor.super.preHandle(request, response, handler); }}Copy the code