Untitled

mail@pastecode.io avatar
unknown
plain_text
2 months ago
8.5 kB
1
Indexable
Never
@Slf4j
@RequiredArgsConstructor
public class CommonHeaderFilter extends OncePerRequestFilter {
    public static final String X_API_KEY = "x-api-key";

    private final String configApiKey;

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    @NonNull HttpServletResponse response,
                                    @NonNull FilterChain filterChain)
            throws ServletException, IOException {
        if (SecurityContextHolder.getContext().getAuthentication()
                instanceof AuthenticationToken) {
            log.debug("It is already authenticated");
            filterChain.doFilter(request, response);
            return;
        }

        String key = request.getHeader(X_API_KEY);
        if (StringUtils.hasText(key) && configApiKey.equals(key)) {
            filterChain.doFilter(request, response);
        } else {
            sendError(response);
        }
    }

    private void sendError(HttpServletResponse response) throws IOException {
        response.resetBuffer();
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.setStatus(HttpStatus.UNAUTHORIZED.value());
        response.getOutputStream().print(
                new ObjectMapper().writeValueAsString(new ResultDTO(HttpStatus.UNAUTHORIZED)));
        response.flushBuffer();
    }
}
///////////////////////////////
@Slf4j
public class HealthCheckFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain filterChain)
            throws ServletException, IOException {
        String requestURI = request.getRequestURI();

        if (requestURI.equals("/monitor/ok.htm")) {
            log.info("HealthCheckFilter : " + requestURI);

            response.setContentType(TEXT_HTML_VALUE);
            response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
            response.setHeader("pragma", "no-cache");
            response.setDateHeader("Expires", 0);
            response.getWriter().print(true);

        } else {
            filterChain.doFilter(request, response);
        }
    }
}
////////////////////////////
@Configuration
public class DispatcherConfig implements WebMvcConfigurer {

    @Autowired
    private Environment environment;

    @Override
    public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
        SortHandlerMethodArgumentResolver sortResolver = new SortHandlerMethodArgumentResolver();
        PageableHandlerMethodArgumentResolver resolver =
                new PageableHandlerMethodArgumentResolver(sortResolver);

        resolver.setOneIndexedParameters(true);
        resolver.setPageParameterName("pageNumber");
        resolver.setSizeParameterName("pageSize");
        resolver.setFallbackPageable(PageRequest.of(0, 20));

        argumentResolvers.add(resolver);
    }

    @Override
    public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
        configurer.mediaType("json", MediaType.APPLICATION_JSON);
        configurer.defaultContentType(MediaType.APPLICATION_JSON);
    }

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        converters.add(new MappingJackson2HttpMessageConverter());
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/resources/**")
                .addResourceLocations("/resources/");

        registry.addResourceHandler("/swagger-ui.html")
                .addResourceLocations("classpath:/META-INF/resources/");

        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");
    }

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        String origins = environment.getProperty("cors.origins");
        registry.addMapping("/**")
                .allowedOriginPatterns(origins)
                .allowedMethods("POST", "GET", "PUT", "OPTIONS", "DELETE")
                .allowCredentials(true).maxAge(3600);
    }
}
///////////////////////////////
@Configuration
public class FilterConfig {

    @Value("${allowed.ip.list}")
    private String[] allowedIpList;

    @Value("${allowed.hq.ip}")
    private String hqIp;

    @Value("${config.api.key}")
    private String configApiKey;

    @Bean
    public FilterRegistrationBean<HealthCheckFilter> healthCheckFilter() {
        FilterRegistrationBean<HealthCheckFilter> registrationBean = new FilterRegistrationBean<>();
        registrationBean.setFilter(new HealthCheckFilter());
        registrationBean.addUrlPatterns("/monitor/ok.htm");
        registrationBean.setOrder(1);
        return registrationBean;
    }

    @Bean
    @Profile({Profiles.LOCAL, Profiles.DEV, Profiles.TEST})
    public FilterRegistrationBean<SwaggerAuthenticationFilter> swaggerAuthenticationFilter() {
        FilterRegistrationBean<SwaggerAuthenticationFilter> registrationBean =
                new FilterRegistrationBean<>();
        registrationBean.setFilter(new SwaggerAuthenticationFilter());
        registrationBean.setOrder(2);
        return registrationBean;
    }

    @Bean
    public FilterRegistrationBean<ServerAuthenticationFilter> serverAuthenticationFilter() {
        FilterRegistrationBean<ServerAuthenticationFilter> registrationBean = new FilterRegistrationBean<>();
        registrationBean.setFilter(new ServerAuthenticationFilter(allowedIpList, hqIp));
        registrationBean.setOrder(3);
        return registrationBean;
    }

    @Bean
    public FilterRegistrationBean<CommonHeaderFilter> commonHeaderFilter() {
        FilterRegistrationBean<CommonHeaderFilter> registrationBean =
                new FilterRegistrationBean<>();
        registrationBean.setFilter(new CommonHeaderFilter(configApiKey));
        registrationBean.setOrder(4);
        return registrationBean;
    }
}
/////////////////////////////
@Configuration
public class RootConfig {

    @Bean
    public static PBEConfig environmentVariablesConfiguration() {
        return EncryptorConfig.environmentVariablesConfiguration();
    }

    @Bean(name = "encryptorBean")
    public static StringEncryptor configurationEncryptor() {
        StandardPBEStringEncryptor configurationEncryptor =
                new StandardPBEStringEncryptor();
        configurationEncryptor.setConfig(environmentVariablesConfiguration());
        return configurationEncryptor;
    }

    @Bean
    public ObjectMapper objectMapper() {
        return new ObjectMapper();
    }

    @Bean
    public ModelMapper modelMapper() {
        return new ModelMapper();
    }

    @Bean
    public RestTemplate xmlRestTemplate() {
        Jaxb2RootElementHttpMessageConverter jaxb2RootElementHttpMessageConverter =
                new Jaxb2RootElementHttpMessageConverter();
        List<MediaType> supportedMediaTypes = new ArrayList<>();
        supportedMediaTypes.add(MediaType.TEXT_XML);
        supportedMediaTypes.add(MediaType.APPLICATION_XML);
        jaxb2RootElementHttpMessageConverter.setSupportedMediaTypes(
                supportedMediaTypes);
        jaxb2RootElementHttpMessageConverter.setDefaultCharset(StandardCharsets.UTF_8);

        MappingJackson2HttpMessageConverter jsonHttpMessageConverter =
                new MappingJackson2HttpMessageConverter();
        List<MediaType> jsonMediaTypes = new ArrayList<>();
        jsonMediaTypes.add(MediaType.APPLICATION_JSON);
        jsonHttpMessageConverter.setSupportedMediaTypes(jsonMediaTypes);

        RestTemplate textRestTemplate = new RestTemplate();

        List<HttpMessageConverter<?>> messageConverters =
                textRestTemplate.getMessageConverters();
        messageConverters.add(jaxb2RootElementHttpMessageConverter);
        messageConverters.add(jsonHttpMessageConverter);
        textRestTemplate.setMessageConverters(messageConverters);

        return textRestTemplate;
    }

    @Bean(name = "multipartResolver")
    public MultipartResolver multipartResolver() {
        return new CommonsMultipartResolver();
    }
}
Leave a Comment