Springboot接口鑒權(quán)簡單方式
今天遇到需要給springboot單獨(dú)的模塊需要做接口鑒權(quán)的機(jī)制惧盹,因為我們是多模塊開發(fā)的項目抵怎。為了接口安全奋救,實(shí)現(xiàn)方式為:
對稱加密+白名單
這種方式就從軟件和網(wǎng)絡(luò)二個方面進(jìn)行了安全保障。
攔截器
類似于jwt那種方式反惕,header中添加對稱加密之后的sign,客戶端請求中演侯,需攜帶這個請求接口姿染。服務(wù)器端攔截器中,獲取該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 = "接口鑒權(quán)失敗娄徊,請在前端系統(tǒng)添加鑒權(quán)值";
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("系統(tǒng)錯誤:接口鑒權(quán)異常");
}
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) {
// 攔截運(yùn)營模塊所有接口請求
registry.addInterceptor(authenticationInterceptor())
.addPathPatterns("/admin/**");
}
@Bean
public AdminInterceptor authenticationInterceptor() {
return new AdminInterceptor();
}
}
該模塊的所有請求admin開頭闽颇,所以只對這個模塊的接口請求起作用的。
網(wǎng)絡(luò)層面寄锐,我們只需要在服務(wù)器(nginx)中配置白名單即可兵多。
這樣的話,客戶端和服務(wù)器端各自保留一份私鑰橄仆,對同一內(nèi)容進(jìn)行加密后剩膘,進(jìn)行接口請求。內(nèi)容可以動態(tài)變化盆顾,私鑰也可以動態(tài)變化怠褐。白名單也是很好的網(wǎng)絡(luò)保障。
大家還有什么更好的辦法您宪,分享一下奈懒。
歡迎關(guān)注我