Spring Security+Spring Boot 无法访问静态资源 401-跨域问题解决

  • 401告诉我没有权限,一开始我还以为时静态资源没有开放
package cn.hcnet2006.blog.hcnetwebsite.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

- 
@Configuration
public class CorsConfig extends WebMvcConfigurerAdapter {
    @Override
    public void addCorsMappings(CorsRegistry registry) {

        registry.addMapping("/**")
                .allowCredentials(true)
                .allowedHeaders("*")
                .allowedOrigins("*")
                .allowedMethods("*");


}}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
要使用Spring Security解决CORS跨域问题,可以按照以下步骤进行配置: 1. 添加CORS配置类:创建一个类,继承自`WebSecurityConfigurerAdapter`,并重写`configure(HttpSecurity http)`方法。 ```java @Configuration public class CorsConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.cors(); } @Bean public CorsConfigurationSource corsConfigurationSource() { CorsConfiguration configuration = new CorsConfiguration(); configuration.addAllowedOrigin("*"); // 允许所有来源 configuration.addAllowedMethod("*"); // 允许所有请求方法 configuration.addAllowedHeader("*"); // 允许所有请求头 UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); source.registerCorsConfiguration("/**", configuration); return source; } } ``` 2. 启用CORS配置:在Spring Boot应用的入口类上添加`@EnableWebSecurity`注解。 ```java @EnableWebSecurity public class MyApplication { public static void main(String[] args) { SpringApplication.run(MyApplication.class, args); } } ``` 通过以上配置,Spring Security会自动处理跨域请求,并允许所有来源、所有请求方法和所有请求头。你可以根据需要调整配置,例如指定允许的来源、方法和头部信息。 请注意,如果你的应用程序中使用了其他Spring Security配置,你需要将CORS配置类的优先级调整到较低的位置,以确保CORS配置被正确应用。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值