美文网首页Java 杂谈
spring boot1.5.7 + spring securi

spring boot1.5.7 + spring securi

作者: 蔺荆门 | 来源:发表于2018-12-05 18:04 被阅读0次

解决这种跨域问题可以通过增加过滤器来实现,为啥说可以呢,因为我也不清楚有没有其他方式可以实现。我实践了几次都是可行的,但是有一些原理我还是不清楚在文末提了一下。欢迎明白的朋友跟我指点一下。

  1. 配置过滤器
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

@Configuration
public class GlobalCorsConfiguration {

    @Bean
    public CorsFilter corsFilter() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.setAllowCredentials(true);
        corsConfiguration.addAllowedOrigin(CorsConfiguration.ALL);
        corsConfiguration.addAllowedHeader(CorsConfiguration.ALL);
        corsConfiguration.addAllowedMethod(CorsConfiguration.ALL);
        UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource();
        urlBasedCorsConfigurationSource.registerCorsConfiguration("/**", corsConfiguration);
        return new CorsFilter(urlBasedCorsConfigurationSource);
    }

}
  1. 处理options请求
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
@Order(-1)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.requestMatchers()
            .antMatchers(HttpMethod.OPTIONS)
            .and()
            .cors();
    }
}

注:至于第二步为啥要处理options请求,是因为如果发出的是非简单请求的话,浏览器会先发送一个options请求来试探一下,所以需要处理一下这个options请求,要不然请求是不会真正发送的。具体可以看这个老司机的文章

一般来说,这两板斧一耍完,跨域就解决了。

抛出问题

  • 问题1:
http.requestMatchers()
      .antMatchers(HttpMethod.OPTIONS)
      .and()
      .cors();

这段代码写了antMatchers之后直接就and了,没有任何权限表达式,像permitAll之类的,这种写是什么意思?

  • 问题2
    处理options的配置我在资源认证服务器上面写不起作用,非得要新建WebSecurityConfig写在这里才可以。这里我想问的是,WebSecurityConfig里面的配置和资源认证服务器里面的配置有什么区别?

相关文章

网友评论

    本文标题:spring boot1.5.7 + spring securi

    本文链接:https://www.haomeiwen.com/subject/namwcqtx.html