Like it and see. Make it a habit
Development environment:
- jdk 8
- intellij idea
- Maven 3.6
Technology used:
- springboot
- restful
Project introduction
Based on the restful design example, JWT can do token effect verification, realize the addition, deletion, check and change, and at the same time, with custom annotations, convenient filtering token verification
Custom annotations
1. Annotations that need to be validated
@Target({ElementType.METHOD, ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) public @interface UserLoginToken { boolean required() default true; } / / intercept (AuthenticationInterceptor) code public Boolean preHandle (it it, HttpServletResponse httpServletResponse, Object object) throws Exception { String token = httpServletRequest.getHeader("token"); // Retrieve token from HTTP request header // If not mapped to method directly via if(! (object instanceof HandlerMethod)){ return true; } HandlerMethod handlerMethod=(HandlerMethod)object; Method method=handlerMethod.getMethod(); // Check if there are passtoken comments, Skip certification if (method. IsAnnotationPresent (PassToken. Class)) {PassToken PassToken = method. The getAnnotation (PassToken. Class); if (passToken.required()) { return true; }} / / check if there is any need to user permissions the annotation of the if (method. IsAnnotationPresent (UserLoginToken. Class)) {UserLoginToken UserLoginToken = method.getAnnotation(UserLoginToken.class); If (userLogintoken.required ()) {// Perform authentication if (token == null) {throw new RuntimeException(" No token, please login again "); } // Get the user ID in the token String userId; try { userId = JWT.decode(token).getAudience().get(0); } catch (JWTDecodeException j) { throw new RuntimeException("token error"); } String user = jedis.get(userId); If (user == null) {throw new RuntimeException(" user does not exist, please log in again "); } // Verify token JSONObject jsonObject1= jsonObject.parseObject (user); JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(jsonObject1.getString("planType"))).build(); try { jwtVerifier.verify(token); } catch (JWTVerificationException e) { throw new RuntimeException("token error"); } return true; } } return true; }Copy the code
The project structure
- Request List image
- Project structure picture
Running effect
- Token access
@GetMapping("/token") public JSONObject token(HttpServletResponse response ){ Date timeOut=DateUtil.offsetMinute(new Date(),time); JSONObject JSONObject =new JSONObject(); String usecase = new JWTController().getFile("usecase.json"); JSONObject jsonObject1=JSONObject.parseObject(usecase); String token=JWT.create().withExpiresAt(timeOut).withAudience(jsonObject1.getString("objectId")) .sign(Algorithm.HMAC256(jsonObject1.getString("planType"))); response.setStatus(200); jsonObject.put("token", token); jedis.set(jsonObject1.getString("objectId"), usecase); return jsonObject; }Copy the code
- Authentication token
@userLoginToken @getMapping ("/authToken") public String getMessage(){return "Authentication succeeded "; }Copy the code
- A get request
@UserLoginToken
@GetMapping(value="/plan/{id}")
public String getPlan(@PathVariable String id, HttpServletResponse response) {
jedis.connect();
if (jedis.get(id) == null) {
response.setStatus(404);
return "No such record";
}
response.setStatus(200);
return jedis.get(id);
}
Copy the code
- A post request
@UserLoginToken
@ResponseBody
@PostMapping(path="/plan")
public String addPlan(@RequestBody JSONObject jsonObject, HttpServletResponse response) throws IOException, ProcessingException {
String data = jsonObject.toString();
Boolean jsonValidity = Validator.isJSONValid(data);
if(jsonValidity) {
String uuid = UUID.randomUUID().toString();
jedis.set(uuid, data);
return "Create Success" + "\n" + uuid;
}
else {
response.setStatus(400);
return "JSON Schema not valid!";
}
}
Copy the code
- The delete request
@UserLoginToken
@DeleteMapping(value="/plan/{id}")
public String deletePlan(@PathVariable String id, HttpServletResponse response) {
jedis.connect();
if (jedis.get(id) == null) {
response.setStatus(404);
return "No such record";
}
jedis.del(id);
response.setStatus(200);
return "Deleted Success" + "\n" + id;
}
Copy the code
- Patch request
@UserLoginToken
@PatchMapping(value="/plan/{id}")
public String patchPlan(@RequestBody JSONObject jsonObject, @PathVariable String id, HttpServletResponse response) {
jedis.connect();
if (jedis.get(id) == null) {
response.setStatus(404);
return "No such record";
}
String data = jsonObject.toString();
String redisDate=jedis.get(id);
Map redisData=JSONUtil.toBean(redisDate,Map.class);
Map map=JSONUtil.toBean(data,Map.class);
for(Object o:map.keySet()){
redisData.put(o,map.get(o));
}
jedis.set(id, JSONUtil.toJsonStr(redisData));
response.setStatus(200);
return "Patched Success" + "\n" + id;
}
Copy the code
- Put request
@UserLoginToken
@PutMapping(value="/plan/{id}")
public String updatePlan(@RequestBody JSONObject jsonObject, @PathVariable String id, HttpServletResponse response) throws IOException, ProcessingException {
jedis.connect();
if (jedis.get(id) == null) {
response.setStatus(404);
return "No such record";
}
String data = jsonObject.toString();
if(Validator.isJSONValid(data)) {
jedis.set(id, data);
response.setStatus(200);
return "Updated Success" + "\n" + id;
}
else {
response.setStatus(400);
return "Invalid JSON!";
}
}
Copy the code
Project summary
- Restful combined with JWT for token effect verification, all requested tokens are added to headers
- The project also adds schema.json, a standard used to define JSON data constraints
- Others have better concise operation habits, leave a message for the program help