SpringSecurity-2.7中跨域问题

2024-01-02 13:09:43

SpringSecurity-2.7中跨域问题

访问测试
  • 异步请求
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <button id="btn">发起异步请求</button>
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    <script>
      let btnEl = document.querySelector('#btn');
      btnEl.onclick = function () {
        console.log('click......................');
        axios({
          url: 'http://localhost:8080/login',
          method: 'post',
          data: {
            username: 'zhangsan',
            password: '123456',
          },
        }).then((res) => {
          console.log(res);
        });
      };
    </script>
  </body>
</html>

  • 请求测试

SpringSecurity-配置

  • config
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        /**
         * 请求配置
         * authorizeHttpRequests: 开启权限请求管理,针对 http 请求进行授权配置
         * mvcMatchers: 匹配请求
         * - permitAll: 代表放行该资源,该资源位公共资源,无需认证和授权可以直接访问
         * - anyRequest().authenticated(): 代表所有请求,必须认证之后才能访问
         * - formLogin: 代表开启表单认证
         * <strong>放行资源必须放在认证资源之前</strong>
         */
        http.authorizeHttpRequests((authorizeHttpRequests) ->
                authorizeHttpRequests
                        // 非普通请求(比如请求新增了自定义头部信息,比如Jwt头),会发送预检 Option 请求,这里直接让他通过
                        .antMatchers(HttpMethod.OPTIONS, "/login").permitAll()
                        .anyRequest().authenticated()
        );
     
     /**
      * 跨域配置
      */
     http.cors().configurationSource(corsConfigurationSource());
    }
    
    @Bean
    CorsConfigurationSource corsConfigurationSource() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowCredentials(true);
        configuration.setAllowedMethods(Arrays.asList("*"));
        configuration.setAllowedHeaders(Arrays.asList("*"));
        configuration.setMaxAge(Duration.ofHours(1));
        configuration.setAllowedOriginPatterns(Arrays.asList("*"));
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }
    

文章来源:https://blog.csdn.net/weixin_43340420/article/details/135336871
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。