Springboot接口鉴权简单方式
今天遇到需要给springboot单独的模块需要做接口鉴权的机制,因为我们是多模块开发的项目。为了接口安全,实现方式为:
对称加密+白名单
这种方式就从软件和网络二个方面进行了安全保障。
拦截器
类似于jwt那种方式,header中添加对称加密之后的sign,客户端请求中,需携带这个请求接口。服务器端拦截器中,获取该sign,如果解密成功,说明合法请求。
public class AdminInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object object) throws Exception {
// 从 http 请求头中取出签名
httpServletResponse.setCharacterEncoding("UTF-8");
httpServletResponse.setContentType("application/json; charset=utf-8");
String sign = httpServletRequest.getHeader("Sign");
String decKey = AesEncodeUtil.decrypt(sign);
final String message = "接口鉴权失败,请在前端系统添加鉴权值";
if (Objects.nonNull(decKey)) {
return true;
} else {
try (PrintWriter out = httpServletResponse.getWriter()) {
String responseJson = "{\"message\":\"" + message + "\",\"success\": false,\"code\": 403}";
out.print(responseJson);
} catch (IOException e) {
throw new BgyException("系统错误:接口鉴权异常");
}
return false;
}
}
@Override
public void postHandle(HttpServletRequest httpServletRequest,
HttpServletResponse httpServletResponse,
Object o, ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest httpServletRequest,
HttpServletResponse httpServletResponse,
Object o, Exception e) throws Exception {
}
}
配置该拦截器
@Configuration
public class InterceptorConfig extends WebMvcConfigurationSupport {
@Override
public void addInterceptors(InterceptorRegistry registry) {
// 拦截运营模块所有接口请求
registry.addInterceptor(authenticationInterceptor())
.addPathPatterns("/admin/**");
}
@Bean
public AdminInterceptor authenticationInterceptor() {
return new AdminInterceptor();
}
}
该模块的所有请求admin开头,所以只对这个模块的接口请求起作用的。
网络层面,我们只需要在服务器(nginx)中配置白名单即可。
这样的话,客户端和服务器端各自保留一份私钥,对同一内容进行加密后,进行接口请求。内容可以动态变化,私钥也可以动态变化。白名单也是很好的网络保障。
大家还有什么更好的办法,分享一下。
欢迎大家关注我