学无先后,达者为师

网站首页 编程语言 正文

spring-boot设置跨域访问方式

作者:小黑孩666 更新时间: 2022-07-22 编程语言

一、创建一个配置类。实现WebMvcConfigurer接口

@Configuration
public class WebMvcConfiguration implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOriginPatterns("*")
                .allowedHeaders("*")
                .allowedMethods("*")
                .allowCredentials(true)
                .maxAge(3600);
    }
}
二、还可以继承WebSecurityConfigurerAdapter类,然后重写configure方法
 String[] url={
          "/admins/login","/doc.html","/**/*.css","/**/*.js","/swagger-resources","                /v2/api-docs"
        };

        http.cors();

        http.csrf().disable();//禁止防止跨域请求,如果无此配置,白名单路径的异步访问也会出现403错误
        http.authorizeRequests() //请求需要被授权才可以访问
                .antMatchers(url)//匹配某些路径
                .permitAll()//允许直接访问
                .anyRequest()//
                .authenticated();

                

原文链接:https://blog.csdn.net/xiaoheihai666/article/details/125684854

栏目分类
最近更新