自定义验证登录拦截器 :
步骤 1 :
@Aspect
@Component
@Order(1) // 代表执行的顺序 , 数字越小 , 越先执行
public class TokenInterceptor {
public static final String AUTHORIZATION = "Authorization";
public static final String APP_TOKEN = "App-Token";
@Value("${token.check.url}")
protected String checkTokenUrl;
@Value("${module.code}")
protected String moduleCode;
@Autowired
private NucRestTemplate nucRestTemplate;
@Pointcut("@annotation(com.cmft.cmuop.api.annotation.ValidateToken)")
public void annotationPointcut() {
}
@Before("annotationPointcut()")
public void refreshRedis(JoinPoint joinPoint) throws Throwable {
HttpServletRequest request = AppPlatformContext.getCurrentRequest();
String tokenString = this.getTokenString(request);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.add("ip", HttpUtils.getReqIp(request));
headers.add("App-Token", tokenString);
headers.add("CallerModule", moduleCode);
Map<String, Object> params = new HashMap<>();
params.put("moduleCode", moduleCode);
HttpEntity<Map<String, Object>> httpEntity = new HttpEntity<>(params, headers);
ResponseEntity<JSONObject> responseEntity = nucRestTemplate
.postForEntity(String.format("%s%s", checkTokenUrl, tokenString), httpEntity, JSONObject.class);
JSONObject checkTokenResult = responseEntity.getBody();
if(!checkTokenResult.getBooleanValue("state")) {
throw new BusinessException(401, "Unauthorized");
}
this.loadUsersResourcesByModule(checkTokenResult, request);
}
private void loadUsersResourcesByModule(JSONObject checkTokenResult, HttpServletRequest request) {
JSONObject dataJsonObject = checkTokenResult.getJSONObject("data");
request.setAttribute(AppPlatformContext.CURRENT_ACCOUNT_ID, dataJsonObject.getString("accountId"));
}
private String getTokenString(HttpServletRequest request) {
String tokenString = request.getHeader(APP_TOKEN);
if (StringUtils.isEmpty(tokenString)) {
tokenString = request.getHeader(AUTHORIZATION);
}
return tokenString;
}
}
步骤 2 :
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
public @interface ValidateToken {
}
步骤 3 : 在方法中使用
@PostMapping(value = "interface")
@ApiOperation("通用接口")
@ValidateToken // 自己定义的注解
public WebResponse<?> configInterface(@RequestBody @Validated ThirdSystemRequestDTO thirdSystemDTO,
HttpServletRequest request) {
}