數據接口的返回報文
{
"code": 0,
"count": 0,
"data": {},
"msg": "string"
}
數據接口調用總是返回上述報文格式JSON數據,這裏的字段設計是爲了兼容layui的數據表格取數接口。
code字段
接口成功返回時爲0,發生調用錯誤時不爲0
msg字段
接口調用的消息信息,發生調用錯誤時爲錯誤描述信息,建議是直觀友好的信息能夠直接顯示給用戶看。
data字段
接口調用返回的業務數據
count字段
數據分頁時使用,數據的總行數,layui數據表格組件需要該字段
登錄接口例子
登錄成功
{
"code": 0,
"msg": "",
"data": {
"password": "e10adc3949ba59abbe56e057f20f883e",
"user": "admin",
"token": "3b9ce276b01c46d3be5ffc75698782d2"
},
"count": 0
}
登錄失敗
{
"msg": "密碼錯誤!",
"code": -1
}
數據接口的令牌token機制
先調用登錄接口,成功登陸後返回令牌token,然後用令牌作爲參數進一步調用後續的接口。
token參數建議使用@RequestHeader傳輸,可以避免與get請求衝突。
根據安全級別可以把接口劃分爲兩類:不需要令牌token和需要令牌token
登錄接口示例代碼
@ApiOperation(value = "登錄")
@ApiImplicitParams({
@ApiImplicitParam(name = "user", value = "用戶名", dataType = "String", paramType = "query"),
@ApiImplicitParam(name = "password", value = "密碼", dataType = "String", paramType = "query")
})
@RequestMapping(path = "/sys/login", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
@IgnoreToken
public ResponseData login(@RequestParam String user, @RequestParam String password) {
Map<String, Object> map = sysService.login(user, password);
return ResponseData.success(map);
}
需要令牌token的接口示例代碼
@ApiOperation(value = "新增用戶")
@ApiImplicitParams({
@ApiImplicitParam(name = "token", value = "令牌", dataType = "String", paramType = "header"),
@ApiImplicitParam(name = "userName", value = "用戶名", dataType = "String", paramType = "query"),
@ApiImplicitParam(name = "password", value = "密碼", dataType = "String", paramType = "query"),
@ApiImplicitParam(name = "fullName", value = "全名", dataType = "String", paramType = "query"),
@ApiImplicitParam(name = "remark", value = "備註", dataType = "String", paramType = "query")
})
@RequestMapping(path = "/sys/addUser", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
public ResponseData addUser(@RequestHeader String token, @RequestParam String userName, @RequestParam String password, @RequestParam(required = false) String fullName, @RequestParam(required = false) String remark){
throw new SysException("功能未實現!");
}
@IgnoreToken與Spring的AOP機制
通過@IgnoreToken標記接口是否需要校驗令牌,利用Spring框架定義一個通用的切面,輕鬆實現權限的統一校驗。
@IgnoreRule標記接口是否需要進一步校驗接口權限。
@Before("execution(* syslog.controller.*.*(..)) && !@annotation(syslog.IgnoreToken)")
public void checkToken(JoinPoint jp) throws Throwable {
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
String token = request.getHeader("token");
//校驗令牌
SessionUtil.checkSession(token);
//校驗接口權限
String methodName = jp.getSignature().getName();
Method method = jp.getTarget().getClass().getMethod(methodName);
IgnoreRule ignoreRule = method.getDeclaredAnnotation(IgnoreRule.class);
if (ignoreRule != null)
return;
String className = jp.getTarget().getClass().getName();
sysService.checkRule(token, className + "." + methodName);
}