<br/>點贊再看,養成習慣<br/>
redis
基於restful風格作的設計實例,便可jwt作token效驗,實現增刪查改,同時搭配自定義註解,方便過濾token驗證spring
1.須要作驗證的註解json
@Target({ElementType.METHOD, ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) public @interface UserLoginToken { boolean required() default true; } //攔截類(AuthenticationInterceptor)代碼 public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object object) throws Exception { String token = httpServletRequest.getHeader("token");// 從 http 請求頭中取出 token // 若是不是映射到方法直接經過 if(!(object instanceof HandlerMethod)){ return true; } HandlerMethod handlerMethod=(HandlerMethod)object; Method method=handlerMethod.getMethod(); //檢查是否有passtoken註釋,有則跳過認證 if (method.isAnnotationPresent(PassToken.class)) { PassToken passToken = method.getAnnotation(PassToken.class); if (passToken.required()) { return true; } } //檢查有沒有須要用戶權限的註解 if (method.isAnnotationPresent(UserLoginToken.class)) { UserLoginToken userLoginToken = method.getAnnotation(UserLoginToken.class); if (userLoginToken.required()) { // 執行認證 if (token == null) { throw new RuntimeException("無token,請從新登陸"); } // 獲取 token 中的 user id 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("用戶不存在,請從新登陸"); } // 驗證 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; }
@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; }
//主要@UserLoginToken發揮驗證做用,不然驗證成功 @UserLoginToken @GetMapping("/authToken") public String getMessage(){ return "身份驗證成功 "; }
@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); }
@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!"; } }
@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; }
@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; }
@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!"; } }