Как включить CORS в весенней загрузке с пружинной безопасностью - PullRequest
0 голосов
/ 13 февраля 2020

Я реализовал WebMvcConfigurerAdapter, а также добавил CorsFilter и настроил заголовки.

@EnableWebMvc
@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addCorsMappings( CorsRegistry registry )
    {
        registry.addMapping("/**").allowedOrigins("http://localhost:3000").allowCredentials(false);
    }
}

@Slf4j
public class CustomCorsFilter implements javax.servlet.Filter {

    @Override
    public void init( FilterConfig filterConfig ) throws ServletException
    {

    }

    @Override
    public void doFilter( ServletRequest req, ServletResponse res, FilterChain chain )
            throws IOException, ServletException
    {
        if( req instanceof HttpServletRequest && res instanceof HttpServletResponse )
        {
            HttpServletRequest request = (HttpServletRequest) req;
            HttpServletResponse response = (HttpServletResponse) res;

            // Access-Control-Allow-Origin
            String origin = request.getHeader("Origin");
            response.setHeader("Access-Control-Allow-Origin", "http://localhost:3000");
            response.setHeader("Vary", "Origin");

            // Access-Control-Max-Age
            response.setHeader("Access-Control-Max-Age", "3600");

            // Access-Control-Allow-Credentials
            response.setHeader("Access-Control-Allow-Credentials", "false");

            // Access-Control-Allow-Methods
            response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");

            // Access-Control-Allow-Headers
            response.setHeader("Access-Control-Allow-Headers",
                    "Origin, X-Requested-With, Content-Type, Accept, " + "X-CSRF-TOKEN");

            log.info("********************** Configured ****************************************");
        }

        chain.doFilter(req, res);
    }

    @Override
    public void destroy()
    {

    }
}

У меня есть два других фильтра, которые делают Authentication и Authorisation. Но когда приложение внешнего интерфейса в локальной системе пытается получить доступ к API, я получаю следующую ошибку:

Access to XMLHttpRequest at 'http://3.12.228.75:8090/rest/noauth/otp/sandesha@test.com' from origin 'http://0.0.0.0:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.

Как решить эту проблему? Я использую spring-boot 1.5.10

, и мой WebSecurityConfig класс,

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    @Autowired
    private CustomLogoutHandler logoutHandler;

    @Autowired
    private HttpLogoutSuccessHandler logoutSuccessHandler;

    @Autowired
    private UserModelRepository userModelRepository;

    @Autowired
    private RefreshTokenService refreshTokenService;

    @Autowired
    private AuthTokenModelRepository authTokenModelRepository;

    @Autowired
    private UserActivitiesRepository userActivitiesRepository;

    @Autowired
    private UserSubscriptionRepository userSubscriptionRepository;

    @Autowired
    private HandlerExceptionResolver handlerExceptionResolver;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private UserService userService;

    @Override
    protected void configure( HttpSecurity http ) throws Exception
    {
        http.csrf().disable()

                .authorizeRequests()

                .antMatchers("/rest/noauth/**").permitAll()

                .antMatchers("/rest/login").permitAll()

                .antMatchers("/rest/logout").permitAll()

                .antMatchers("/static/**").permitAll()

                .antMatchers("/ws/**").permitAll()

                .antMatchers("/rest/razorpay/hook").permitAll()

                .antMatchers("/rest/user/cc").permitAll()

                .antMatchers("/v2/api-docs/**", "/configuration/ui/**", "/swagger-resources/**",
                        "/configuration/security/**", "/swagger-ui.html/**", "/webjars/**")
                .permitAll()

                .antMatchers("/rest/file/invoiceFileDownload", "/rest/file/fileDownload", "/rest/file/fileDownload/**")
                .permitAll()

                .anyRequest().authenticated()

                .and()

                .logout().addLogoutHandler(logoutHandler).logoutSuccessHandler(logoutSuccessHandler)
                .logoutUrl("/rest/logout")

                .and()

                .addFilterBefore(
                        new JWTAuthenticationFilter("/rest/login", tokenService(), refreshTokenService,
                                authTokenModelRepository, userService, userActivitiesRepository,
                                handlerExceptionResolver, bCryptPasswordEncoder, redisTemplate),
                        UsernamePasswordAuthenticationFilter.class)

                .addFilterBefore(new JWTAuthorizationFilter(authenticationManager(), authTokenModelRepository,
                        userSubscriptionRepository, handlerExceptionResolver, redisTemplate),
                        UsernamePasswordAuthenticationFilter.class);

        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);

    }

    @Override
    public void configure( AuthenticationManagerBuilder auth ) throws Exception
    {
        auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder);
    }

    @Bean
    public TokenService tokenService()
    {
        return new TokenService(userModelRepository);
    }

}

1 Ответ

0 голосов
/ 14 февраля 2020

Вы должны оставить сконфигурированное значение таким же, как то, что вы на самом деле запрашиваете. Здесь вы запрашиваете у 0.0.0.0:3000 и устанавливаете заголовок как localhost:3000. В org.springframework.web.cors.CorsConfiguration#checkOrigin есть сравнение строк, которое в вашем случае не удастся.

...