当前位置: 首页 > 知识库问答 >
问题:

由于Spring 5中的access/CORS问题,无法访问后端的URL[重复]

充昌勋
2023-03-14
const httpOptions = {
headers: new HttpHeaders({
  'Content-Type': 'application/json',
  'Authorization': 'Basic mybase64basicauth'
  })
};

...
this.campaignsSubscription = this.http.get<Campaign[]>(this.campaignsUrl, httpOptions)
@Configuration
@EnableWebFlux
public class WebConfig implements WebFluxConfigurer {

   @Override
   public void addCorsMappings(CorsRegistry registry) {

    registry.addMapping("/**")
            .allowedOrigins("http://localhost:4200")
            .allowedMethods("PUT", "DELETE", "GET", "OPTIONS", "POST", "PATCH")
            .allowedHeaders("Authorization", "Content-Type")
            // .allowedHeaders("Content-Type")
            .allowCredentials(true).maxAge(3600);

    // Add more mappings...
   }
}
/*@CrossOrigin(origins = "http://localhost:4200",
    allowedHeaders = "*",
    methods = { RequestMethod.DELETE, RequestMethod.GET, RequestMethod.HEAD, RequestMethod.OPTIONS, RequestMethod.PATCH, RequestMethod.PUT},
    allowCredentials = "true"
    )*/
@CrossOrigin
@RestController
@RequestMapping("/api/campaign")
public class CampaignResource {

private CampaignRepository campaignRepository;

public CampaignResource(CampaignRepository campaignRepository) {
    this.campaignRepository = campaignRepository;
}


@GetMapping("/all")
public Flux<Campaign> getAll() {
    return campaignRepository
            .findAll();

 ...

但我在Chrome控制台中得到以下错误:

        zone.js:2969 OPTIONS http://localhost:8081/api/campaign/all 401 (Unauthorized)

   'http://localhost:8081/api/campaign/all' from origin 
   'http://localhost:4200' has been blocked by CORS policy: Response to 
   preflight request doesn't pass access control check: No 'Access- 
    Control-Allow-Origin' header is present on the requested resource.

我知道基本的auth是正确的,因为它在邮递员中工作。

共有1个答案

闻人志
2023-03-14

使用Spring Security 5.x时······

答案有两个方面:

1)必须在SecurityWebFilterChain中添加:

.pathMatchers(HttpMethod.OPTIONS, "/**").permitAll()**strong text**
@CrossOrigin(origins = "http://localhost:4200",
        allowedHeaders = "*",
        methods = { RequestMethod.DELETE, RequestMethod.GET, RequestMethod.HEAD, RequestMethod.OPTIONS, RequestMethod.PATCH, RequestMethod.PUT},
        allowCredentials = "true"
        )
@Configuration
@EnableWebFluxSecurity
@EnableReactiveMethodSecurity
public class SecurityConfig {

    @Bean
    SecurityWebFilterChain springWebFilterChain(ServerHttpSecurity http) {
        return http
                .authorizeExchange()
                .pathMatchers(HttpMethod.OPTIONS, "/**").permitAll()
                .pathMatchers("/login", "/logout").permitAll()
                .pathMatchers("/i18n/**",
                        "/css/**",
                        "/fonts/**",
                        "/icons-reference/**",
                        "/img/**",
                        "/js/**",
                        "/vendor/**").permitAll()
                .pathMatchers(HttpMethod.GET,"/api/**").authenticated()
                .anyExchange()
                .authenticated()
                .and()
               .formLogin()
                .and()
                .httpBasic()
                /*.loginPage("/login")
                .and()
                .logout()
                .logoutUrl("/logout")*/
                .and()
                .csrf().disable()
                .build();
    }


    //in case you want to encrypt password
    @Bean
    public BCryptPasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}
 类似资料:
  • 问题内容: 我正在使用Java8和aws-java-sdk1.10.43来获取S3文件的预签名URL。我确实获得了一个链接,但是浏览到该链接会导致此错误: 您提供的授权机制不受支持。请使用AWS4-HMAC-SHA256 要强调的是,我希望生成一个可以通过电子邮件发送并在浏览器中打开的URL,而不是使用Java代码从该URL中读取。 我正在使用下面的代码,并且我相信发现我需要以某种方式将setSS

  • 2.Github使用代码https://reduxapp.herokuapp.com/auth/callback?code=9536286A59228E7784A1重定向回来,并触发githubSendCode('9536286A59228E7784A1')操作 你可以在网络呼叫选项中看到呼叫是通过的,但POST呼叫从来没有发生过。然后出现控制台错误: 下面是我的操作函数:

  • XMLHttpRequest无法加载http://localhost:8080/nobelgrid/api/users/create/。请求的资源上没有“访问-控制-允许-来源”标头。因此,不允许访问源'http://localhost:63342'。响应的HTTP状态代码为500。 谁能帮帮我吗? 更新: 但我还有一个错误。我会做另一个问题,因为我认为这是一个不同的论点。 提前感谢!

  • 我有以下功能可以将图片的较小版本合并到图片本身的较大版本: 然而,我得到了以下错误: CORS策略阻止了从源“http://localhost:53594”访问“http://xxxxxxx.com/testpicture.jpg”上的映像:请求的资源上没有“access-control-allow-origin”标头。 我使用了“匿名”交叉起源声明,应该可以解决这个问题,但它似乎没有造成任何影响

  • React应用程序在端口3000上,而我的服务器在端口4000上。根据我的还原操作,我把这条路由称为 即使我已经向服务器添加了这些CORS设置: 我错过了什么?

  • 问题内容: 我真的很想用Struts2来解决问题- 通过省略部分路径,我可以访问JSP页面。请注意该路径应该包括在内。关键是要看路径中的单词。 这是文件: 我可以通过: 和通过: 请注意,在两个URL中,我都可以删除,为什么? 来源:http: //www.mkyong.com/misc/how-to-use-mkyong- tutorial/ 有人可以看完上面的教程,告诉我怎么了吗? 问题答案: