需要做的事
调用端携带Header信息
被调用端验证Header信息
调用端
feign配置类 FeignConfigure.java
@Configuration
public class FeignConfigure {
@Bean
public BasicAuthRequestInterceptor basicAuthRequestInterceptor(){
return new BasicAuthRequestInterceptor("test"/*自定义用户名*/,"test"/*自定义密码*/);
}
}
接口调用类
@FeignClient(contextId = "避免多个接口类重复注册需要指定不同的id 无实际意义", value = "调用服务名",configuration = FeignConfigure.class/*这里就是上面的配置类*/)
public interface IOpenData {
@RequestMapping(value = "/open/last_data", method = RequestMethod.GET)
String queryOpenData(@RequestParam("startDate") String startDate, @RequestParam("limit") Integer limit);
}
被调用端
拦截注解 FeignToken.java
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface FeignToken {
boolean required() default true;
}
feign 拦截类
public class FeignAuthInterceptor implements HandlerInterceptor {
/**
* token生成在 BasicAuthRequestInterceptor 中
*
* this.headerValue = "Basic " + base64Encode((username + ":" + password).getBytes(charset));
*/
private static final String CONST_FEIGN_TOKEN = "Basic dGVzdDp0ZXN0";
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String token = request.getHeader("authorization");
if (!(handler instanceof HandlerMethod)) {
return true;
}
HandlerMethod handlerMethod = (HandlerMethod) handler;
Method method = handlerMethod.getMethod();
if (method.isAnnotationPresent(FeignToken.class)) {
FeignToken userToken = method.getAnnotation(FeignToken.class);
if (userToken.required()) {
// 执行认证
if (token == null || !token.equals(CONST_FEIGN_TOKEN)) {
// TODO token错误
}
return true;
} else {
return true;
}
}
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
}
}
启用拦截 InterceptorConfigure.java
@Configuration
public class InterceptorConfigure implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(authenticationInterceptor())
.addPathPatterns("/**");
}
@Bean
public FeignAuthInterceptor authenticationInterceptor() {
return new FeignAuthInterceptor();
}
}
接口 OpenDataController.java
@RestController
@RequestMapping("open")
public class OpenDataController {
@GetMapping("last_data")
@FeignToken /*授权拦截 token*/
public String lastData(String startDate,Integer limit){
return "testController";
}
}