如何向假客户端添加请求拦截器?

2022-09-02 13:13:51

我希望每次通过假装客户端发出请求时,都与经过身份验证的用户一起设置特定的标头。

这是我的过滤器,我从中获取身份验证并将其设置为spring安全上下文:

@EnableEurekaClient
@SpringBootApplication
@EnableFeignClients
public class PerformanceApplication {
    @Bean
    public Filter requestDetailsFilter() {
        return new RequestDetailsFilter();
    }

    public static void main(String[] args) {
        SpringApplication.run(PerformanceApplication.class, args);
    }

    private class RequestDetailsFilter implements Filter {
        @Override
        public void init(FilterConfig filterConfig) throws ServletException {

        }

        @Override
        public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
            String userName = ((HttpServletRequest)servletRequest).getHeader("Z-User-Details");
            String pass = ((HttpServletRequest)servletRequest).getHeader("X-User-Details");
            if (pass != null)
                pass = decrypt(pass);
            SecurityContext secure = new SecurityContextImpl();
            org.springframework.security.core.Authentication token = new UsernamePasswordAuthenticationToken(userName, pass);
            secure. setAuthentication(token);
            SecurityContextHolder.setContext(secure);
            filterChain.doFilter(servletRequest, servletResponse);
        }

        @Override
        public void destroy() {

        }
    }
    private String decrypt(String str) {
        try {
            Cipher dcipher = new NullCipher();

            // Decode base64 to get bytes
            byte[] dec = new sun.misc.BASE64Decoder().decodeBuffer(str);

            // Decrypt
            byte[] utf8 = dcipher.doFinal(dec);

            // Decode using utf-8
            return new String(utf8, "UTF8");
        } catch (javax.crypto.BadPaddingException e) {
        } catch (IllegalBlockSizeException e) {
        } catch (UnsupportedEncodingException e) {
        } catch (java.io.IOException e) {
        }
        return null;
    }
}

这是我的假客户:

@FeignClient("holiday-client")
public interface EmailClient {
    @RequestMapping(value = "/api/email/send", method = RequestMethod.POST)
    void sendEmail(@RequestBody Email email);
}

在这里,我有一个请求拦截器:

@Component
public class FeignRequestInterceptor implements RequestInterceptor {
    private String headerValue;

    public FeignRequestInterceptor() {
    }

    public FeignRequestInterceptor(String username, String password) {
        this(username, password, ISO_8859_1);
    }

    public FeignRequestInterceptor(String username, String password, Charset charset) {
        checkNotNull(username, "username");
        checkNotNull(password, "password");
        this.headerValue = "Basic " + base64encode((username + ":" + password).getBytes(charset));
    }

    private static String base64encode(byte[] bytes) {
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(bytes);
    }

    @Override
    public void apply(RequestTemplate requestTemplate) {
        requestTemplate.header("Authorization", headerValue);
    }
}

我不知道如何为我的客户端配置此拦截器,以及如何使用用户名和密码设置标头。我怎样才能做到这一点?


答案 1

您实际上并不需要自己的实现,因为软件包中已经存在完全相同的BasicAuthRequestInterceptorFeignRequestInterceptorfeign.auth

话虽如此,您基本上已经设置了几乎所有内容。剩下要做的就是使用特定的用户名和密码定义bean:basicAuthRequestInterceptor

@Bean
public RequestInterceptor basicAuthRequestInterceptor() {
    return new BasicAuthRequestInterceptor("username", "password");
}

答案 2

我知道这个帖子有点旧,但想对这里发生的事情给出一些解释。

如果要自定义假请求,可以使用 .这可以是一个自定义实现,或者您可以重用Feiign库中提供的内容,例如.RequestInterceptorBasicAuthRequestInterceptor

如何注册?好吧,有2种方法可以做到这一点,具体取决于您如何使用Feign。

如果您使用的是没有弹簧的普通假象,那么您必须将拦截器设置为假象构建器。这里有一个例子。

Feign.builder()
     .requestInterceptor(new MyCustomInterceptor())
     .target(MyClient.class, "http://localhost:8081");

如果您使用的是Spring Cloud OpenFeign,并且您使用注释来构建客户端,那么您必须通过将其定义为一个或一个类中的bean来从您的bean中创建一个bean。示例如下@FeignClientRequestInterceptor@Component@Bean@Configuration

@Component
public class MyCustomInterceptor implements RequestInterceptor {
    @Override
    public void apply(RequestTemplate template) {
        // do something
    }
}

另外,您可以查看我在本主题中的一篇文章,也许这可以更好地清除它:使用Spring Cloud Feign自定义每个请求