restful風格請求,基於token鑑權例項

程式幫發表於2021-01-05

點贊再看,養成習慣

開發環境:

  1. jdk 8
  2. intellij idea
  3. maven 3.6

所用技術:

  1. springboot
  2. restful

專案介紹

基於restful風格做的設計例項,即可jwt做token效驗,實現增刪查改,同時搭配自定義註解,方便過濾token驗證

自定義註解

1.需要做驗證的註解

@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;
}

專案結構

  • 請求列表圖片

image

  • 專案結構圖片

image

執行效果

  • token 獲取

image

@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;
}
  • 驗證token

image

//主要@UserLoginToken發揮驗證作用,否則驗證成功
@UserLoginToken
@GetMapping("/authToken")
public String getMessage(){
    return "身份驗證成功 ";
}
  • get 請求

image

@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);
}
  • post 請求

image

@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!";
    }
}
  • delete 請求

image

@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;
}
  • patch 請求

image

@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;
}
  • put 請求

image

@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!";
    }
}

專案總結

  1. restful 結合jwt做token效驗,所有請求的token放入headers中
  2. 專案還加入schema.json,Json Schema就是用來定義json資料約束的一個標準
  3. 其他有更好的簡潔操作習慣,希望留言交流
  4. 程式有問題找程式幫

相關文章