Springboot is a simple method for interface authentication
Today we encountered the mechanism of interface authentication for a separate module of Springboot, because we are a multi-module development project. To ensure interface security, the implementation is as follows:
Symmetric encryption + whitelist
This way from the software and network two aspects of security.
The interceptor
Similar to JWT, after adding symmetric encryption in header, the client request needs to carry this request interface. Server-side interceptor, obtain the sign, if decrypted successfully, indicating a legitimate request.
public class AdminInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object Object) throws the Exception {/ / signature from the HTTP request header httpServletResponse setCharacterEncoding (" utf-8 "); httpServletResponse.setContentType("application/json; charset=utf-8"); String sign = httpServletRequest.getHeader("Sign"); String decKey = AesEncodeUtil.decrypt(sign); Final String message = "Interface authentication failed. Please add an authentication value to the front-end system "; 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(" system error: interface authentication exception "); } 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 { } }Copy the code
Configure the interceptor
@Configuration public class InterceptorConfig extends WebMvcConfigurationSupport { @Override public void AddInterceptors (InterceptorRegistry registry) {/ / intercept all operation module interface request registry. AddInterceptor (authenticationInterceptor ()) .addPathPatterns("/admin/**"); } @Bean public AdminInterceptor authenticationInterceptor() { return new AdminInterceptor(); }}Copy the code
All requests for this module start with admin, so only interface requests for this module are valid.
At the network level, we just need to configure the whitelist in the server (nginx).
In this case, the client and the server each keep a private key, encrypt the same content, and make the interface request. Content can change dynamically, as can the private key. Whitelists are also good network security.
We have any better way, share.
Welcome to follow me