简体   繁体   English

<spring boot>请求的资源上不存在“Access-Control-Allow-Origin”header</spring>

[英]<Spring Boot> No 'Access-Control-Allow-Origin' header is present on the requested resource

I am starting to lose my mind here.我开始在这里失去理智。 My project is ran on Spring boot and React, I am trying to implement a logout functionality.我的项目在 Spring 引导和 React 上运行,我正在尝试实现注销功能。 I want to make this work:我想让这个工作:

  1. User is logged in用户已登录
  2. User clicks on Log out用户点击注销
  3. The JWT token cookie gets deleted, user gets redirected to localhost:3000 JWT 令牌 cookie 被删除,用户被重定向到 localhost:3000

From react app (localhost:3000), i want to call the "/exit" endpoint on Spring Boot server (localhost:8080/exit).从 React 应用程序 (localhost:3000),我想在 Spring 引导服务器 (localhost:8080/exit) 上调用“/exit”端点。 There are no other issues with cors apart from this with my implementation (no errors when fetching data from the server, logging in or registering a user).除了我的实现之外,cors 没有其他问题(从服务器获取数据、登录或注册用户时没有错误)。

Here is the code (Spring Boot):这是代码(Spring Boot):

(UserController.java) (用户控制器.java)

    @RequestMapping("/exit")
    public void exit(HttpServletRequest request, HttpServletResponse response) {
        // token can be revoked here if needed
        new SecurityContextLogoutHandler().logout(request, null, null);
        try {
            //sending back to client app
            response.sendRedirect(request.getHeader("referer"));
            System.out.println("called logout endpoint");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

(SecurityConfig.java) (安全配置.java)

 @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors();
        http.csrf().disable();
        http.authorizeRequests();
        http.sessionManagement().sessionCreationPolicy(STATELESS);
        http.authorizeRequests().antMatchers("/login/**", "/register/**").permitAll();
        http.authorizeRequests().antMatchers("/student/**").hasAuthority(Role.STUDENT.getCode());
        http.authorizeRequests().antMatchers("/teacher/**").hasAuthority(Role.TEACHER.getCode());
        http.authorizeRequests().antMatchers("/coordinator/**").hasAnyAuthority(Role.COORDINATOR.getCode(), Role.ADMIN.getCode());
        http.authorizeRequests().antMatchers("/admin/**").hasAuthority(Role.ADMIN.getCode());
        http.authorizeRequests().antMatchers("/exit").permitAll();
        http.authorizeRequests().anyRequest().authenticated();
        http
                .logout()
                .logoutUrl("/exit")
                .deleteCookies("access_token")
                .logoutSuccessUrl("http://localhost:3000");
        http.addFilter(new CustomAuthenticationFilter(authenticationManagerBean(), jwtAlgorithm(), userRepository));
        http.addFilterBefore(new CustomAuthorizationFilter(userDetailsService, jwtAlgorithm()), UsernamePasswordAuthenticationFilter.class);
    }

(SecurityConfig.java) (安全配置.java)

    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        final CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(List.of("http://localhost:3000/", "http://localhost:3000"));
        configuration.setAllowedMethods(List.of("GET", "POST", "PUT", "DELETE", "PUT", "OPTIONS", "PATCH", "DELETE"));
        configuration.setAllowedHeaders(List.of("Authorization", "Cache-Control", "Content-Type", "Access-Control-Allow-Origin"));
        configuration.setAllowCredentials(true);
        configuration.setExposedHeaders(List.of("Authorization", "Access-Control-Allow-Origin"));
        final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }

All I want is to get rid of the damn我只想摆脱该死的

Access to XMLHttpRequest at 'http://localhost:3000/' (redirected from 'http://localhost:8080/exit') from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. CORS 政策阻止了从来源“http://localhost:3000”访问位于“http://localhost:3000/”(从“http://localhost:8080/exit”重定向)的 XMLHttpRequest 策略:无“访问” -Control-Allow-Origin' header 出现在请求的资源上。

error.错误。 Without essentially turning the cors completely off.基本上没有完全关闭 cors。

I've looked over most posts here asking similar questions, I haven't found the answer.我看了这里问类似问题的大多数帖子,我还没有找到答案。 Nothing worked yet.还没有任何效果。 The error remains the same.错误保持不变。

Can you please help me?你能帮我么? Thank you.谢谢你。

It has to be related to response.sendRedirect line.它必须与response.sendRedirect行相关。 With this command, it is as if you have sent a request to the client side, from the server side.使用此命令,就好像您已从服务器端向客户端发送请求一样。 So the CORS policy comes into play again.于是CORS policy再次发挥作用。 I have no experience with React, but I think you need to configure the WebServer on which the React application is running.我没有使用 React 的经验,但我认为您需要配置运行 React 应用程序的 WebServer。 Or, instead of sendRedirect, you can return 200 OK and do this redirect on the client side.或者,您可以返回200 OK并在客户端执行此重定向,而不是 sendRedirect。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Spring 启动 OAuth 客户端配置给出“No 'Access-Control-Allow-Origin' header 存在于请求的资源上。” - Spring boot OAuth Client config giving "No 'Access-Control-Allow-Origin' header is present on the requested resource." CORS 策略:请求的资源上不存在“访问控制允许来源”header Spring 引导 Rest API & VUE - CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource Spring Boot Rest API & VUE angular 9 和 spring 启动 2 中请求的资源上不存在“访问控制允许来源”header - No 'Access-Control-Allow-Origin' header is present on the requested resource in angular 9 and spring boot 2 CORS 策略:请求的资源 Spring Boot Rest API 上不存在“Access-Control-Allow-Origin”标头 - CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource Spring Boot Rest API Angular 和 Spring Boot:请求的资源上不存在“Access-Control-Allow-Origin”标头。 如何通过angular和spring boot解决 - Angular and Spring boot: No 'Access-Control-Allow-Origin' header is present on the requested resource. How to solve it by angular and spring boot 请求的资源上不存在Access-Control-Allow-Origin标头 - No Access-Control-Allow-Origin header is present on the requested resource 请求的资源 (Ingress) 上不存在“Access-Control-Allow-Origin”标头 - No 'Access-Control-Allow-Origin' header is present on the requested resource (Ingress) 尽管存在请求的资源,但没有“ Access-Control-Allow-Origin”标头存在 - No 'Access-Control-Allow-Origin' header is present on the requested resource despite it is there CORS Spring Security 配置 - 404 请求的资源上不存在“Access-Control-Allow-Origin”标头 - CORS Spring Security configuration - 404 No 'Access-Control-Allow-Origin' header is present on the requested resource Java Spring:请求的资源上不存在“Access-Control-Allow-Origin”标头 - Java Spring: No 'Access-Control-Allow-Origin' header is present on the requested resource
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM