配置支持跨域后,spring security免登陆失效

首先说,使用注解 @CrossOrigin是可以正常使用的,但是对于多个接口类需要多个@CrossOrigin注解,所以使用了下面代码来配置支持跨域:

@Configuration
public class CorsConfiguration implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry corsRegistry) {
        // 允许跨域访问资源定义: /api/ 所有资源
        corsRegistry.addMapping("/api/**")
                // 只允许本地的9000端口访问
                .allowedOrigins("http://localhost:9000", "http://127.0.0.1:9000")
                // 允许发送Cookie
                .allowCredentials(true)
                // 允许所有方法
                .allowedMethods("GET", "POST", "PUT", "DELETE", "HEAD");
    }
}

然后竟然发现,原本免登陆访问的配置失效了。
免登陆访问的配置如下:

@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    RestfulAccessDeniedHandler restfulAccessDeniedHandler;
    @Autowired
    RestAuthorizationEntryPoint restAuthorizationEntryPoint;

    @Override
    public void configure(WebSecurity webSecurity) {
        //配置免登录接口
        webSecurity.ignoring().antMatchers("/user/*" // 用户下的注册和登陆接口
        ).antMatchers(HttpMethod.GET,
                "/css/**", "/js/**",
                "/doc.html", "/webjars/**", "/swagger-resources/**", "/v2/api-docs/**" // swagger-ui
                ,"/message" // 拉取留言列表
//        ).antMatchers(HttpMethod.POST, ""
        ); // 回调接口
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable() // 使用jwt,不用csrf,解决跨域问题
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) // 不使用session
                .and().authorizeRequests().antMatchers(HttpMethod.POST, "/login/**").permitAll()
                .and().authorizeRequests().anyRequest().authenticated() // 其他一定要登录
                .and()
                .headers().cacheControl();// 用不到缓存
        // 添加jwt登录授权过滤器
        http.addFilterBefore(jwtAuthencationTokenFilter(), UsernamePasswordAuthenticationFilter.class);
        // 添加自定义未授权和未登录结果返回
        http.exceptionHandling().accessDeniedHandler(restfulAccessDeniedHandler)
                .authenticationEntryPoint(restAuthorizationEntryPoint);
    }

    @Bean
    PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public JwtAuthencationTokenFilter jwtAuthencationTokenFilter() {
        return new JwtAuthencationTokenFilter();
    }
}

你可能感兴趣的:(配置支持跨域后,spring security免登陆失效)