• (新)Spring Security如何实现跨域


    浏览器出于安全的考虑,使用 XMLHttpRequest对象发起 HTTP请求时必须遵守同源策略,否则就是跨域的HTTP请求。

    默认情况下是被禁止的。 同源策略要求源相同才能正常进行通信,即协议、域名、端口号都完全一致。

    前后端分离项目,前端项目和后端项目一般都不是同源的,所以肯定会存在跨域请求的问题。

    所以我们就要处理一下,让前端能进行跨域请求。

    一、先对SpringBoot配置,运行跨域请求

    1. @Configuration
    2. public class CorsConfig implements WebMvcConfigurer {
    3. @Override
    4. public void addCorsMappings(CorsRegistry registry) {
    5. registry.addMapping("/**")
    6. // 设置允许跨域请求的域名
    7. .allowedOriginPatterns("*")
    8. // 是否允许cookie
    9. .allowCredentials(true)
    10. // 设置允许的请求方式
    11. .allowedMethods("GET", "POST", "DELETE", "PUT")
    12. // 设置允许的header属性
    13. .allowedHeaders("*")
    14. // 跨域允许时间
    15. .maxAge(3600);
    16. }
    17. }

    二、开启SpringSecurity的跨域访问

    由于我们的资源都会收到SpringSecurity的保护,所以想要跨域访问还要让SpringSecurity运行跨域访问。

    1. /**
    2. * 配置Spring Security的过滤链。
    3. *
    4. * @param http 用于构建安全配置的HttpSecurity对象。
    5. * @return 返回配置好的SecurityFilterChain对象。
    6. * @throws Exception 如果配置过程中发生错误,则抛出异常。
    7. */
    8. @Bean
    9. SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
    10. http
    11. // 添加JWT认证过滤器jwtAuthenticationTokenFilter在UsernamePasswordAuthenticationFilter之前
    12. .addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class)
    13. // 禁用CSRF保护
    14. .csrf(csrf -> csrf.disable())
    15. // 设置会话创建策略为无状态
    16. .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
    17. // 配置授权规则 指定user/login路径.允许匿名访问(未登录可访问已登陆不能访问). 其他路径需要身份认证
    18. .authorizeHttpRequests(auth -> auth.requestMatchers("/user/login").anonymous().anyRequest().authenticated())
    19. // 配置异常处理
    20. .exceptionHandling(exception -> exception.accessDeniedHandler(accessDeniedHandler).authenticationEntryPoint(authenticationEntryPoint))
    21. //开启跨域访问
    22. .cors();
    23. // 构建并返回安全过滤链
    24. return http.build();
    25. }

  • 相关阅读:
    uniapp小程序长按识别关注公众号
    java中(String)类常用方法
    【网络安全】内网杀器之Cobalt Strike
    python-kafka客户端封装
    CSS如何画出平行四边形
    Google Earth Engine(GEE)——10分钟短文快速了解地球引擎和森林面积损失计算
    黄金回收价格和国际金价差多少?
    linux-log系统日志输出等级
    文心一言vsGPT-4全面对比
    数据库基础(一)【MySQL】
  • 原文地址:https://blog.csdn.net/weixin_55772633/article/details/139899996