关于restful:restful风格请求基于token鉴权实例

39次阅读

共计 4414 个字符,预计需要花费 12 分钟才能阅读完成。

点赞再看,养成习惯

开发环境:

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

我的项目构造

  • 申请列表图片

  • 我的项目构造图片

运行成果

  • 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

// 次要 @UserLoginToken 施展验证作用,否则验证胜利
@UserLoginToken
@GetMapping("/authToken")
public String getMessage(){return "身份验证胜利";}
  • get 申请

@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 申请

@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 申请

@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 申请

@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 申请

@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. 程序有问题找程序帮

正文完
 0