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

<br/>點贊再看,養成習慣<br/>redis

開發環境:

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

所用技術:

  1. springboot
  2. restful

項目介紹

基於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;
}

項目結構

  • 請求列表圖片

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

  • 項目結構圖片

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

運行效果

  • token 獲取

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

@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

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

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

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

@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 請求

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

@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 請求

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

@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 請求

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

@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 請求

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

@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. 其餘有更好的簡潔操做習慣,給程序幫留言交流
相關文章
相關標籤/搜索