cors允许自定义身份验证过滤器| spring boot

whlutmcx  于 2021-07-15  发布在  Java
关注(0)|答案(3)|浏览(325)

我有一个奇怪的要求,只使用cookie对请求进行身份验证。有一个用php编写的主服务,它的会话使用一个名为 PHPSESSID .

┌─────────┐
                   │         │
         ┌─────────┤ Browser ├───────────────┐
         │         │         │               │
         │         └─────────┘               │
  ┌──────▼─────┐                  ┌──────────▼──────────┐
  │            │                  │                     │
  │ PHP Server ◄──────────────────┤ Spring Boot Service │
  │            │                  │                     │
  └──────┬─────┘                  └──────────┬──────────┘
         │                                   │
         │                                   │
         │         ┌───────────┐             │
         │         │           │             │
         └─────────► Database  ◄─────────────┘
                   │           │
                   └───────────┘

web应用程序使用的服务的一小部分是由spring引导服务提供的。现在,我想使用php会话id对来自spring服务的请求进行身份验证,同时我想分配cor。但当启用自定义安全过滤器时,由于cors错误,从web应用程序发送的请求将失败。

Web安全配置.java

@Configuration
@EnableWebSecurity(debug = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // When following custom authentication filter is added to the filter chain, 
        // requests from browser will fail due CORS error
        // without it, everything just works fine
        http.addFilterBefore(new MainAppAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);

        http.csrf().disable() //
                .authorizeRequests() //
                .anyRequest().permitAll() //
                .and().httpBasic();
    }

    @Bean
    public FilterRegistrationBean corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.addAllowedOrigin("http://localhost");
        config.addAllowedHeader("*");
        config.addAllowedMethod("*");
        source.registerCorsConfiguration("/**", config);
        FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
        bean.setOrder(0);
        return bean;
    }
}

mainappauthenticationfilter.java文件

public class MainAppAuthenticationFilter extends GenericFilterBean {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {

        var httpRequest = (HttpServletRequest) request;
        var cookies = httpRequest.getCookies();

        // check the session with PHP service
        var user = userIsValid(cookie);

        if(user != null) {
            Authentication authentication = new UsernamePasswordAuthenticationToken(user.getName(), null,
                            AuthorityUtils.createAuthorityList(user.getRole()));
            SecurityContextHolder.getContext().setAuthentication(authentication);
            chain.doFilter(request, response);
        } else {
            var httpResponse = (HttpServletResponse) response;
            httpResponse.sendError(401);
        }
    }
}

使用自定义身份验证筛选器时如何启用cors?

x6492ojm

x6492ojm1#

你可以试试这个:

http.csrf().disable().cors().and()
    .authorizeRequests()
    .anyRequest().permitAll()
    .and().httpBasic();
amrnrhlw

amrnrhlw2#

@Bean
public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        // Configure your Cors COnfig
        source.registerCorsConfiguration("/**", config);
        return new CorsFilter(source);
    }

然后将http.cors()添加到配置中。

kgsdhlau

kgsdhlau3#

问题似乎是我如何添加允许的cors方法和allowcredentials。

@Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        config.addAllowedOrigin("http://localhost");
        config.addAllowedHeader("*");
        config.addAllowedMethod("OPTIONS");
        config.addAllowedMethod("GET");
        config.addAllowedMethod("POST");
        config.addAllowedMethod("PUT");
        config.addAllowedMethod("DELETE");
        source.registerCorsConfiguration("/**", config);
        return new CorsFilter(source);
    }

出于某种原因 cors() 在安全配置中,来自chrome浏览器的post请求将失败(但在firefox上可以工作)。

http.csrf().disable().cors().and().authorizeRequests().anyRequest().permitAll();

相关问题