Spring Security+ReactJS - 预检请求

发布于 2025-01-15 23:22:57 字数 2202 浏览 1 评论 0 原文

我正在开发一个项目,其中 FE 作为 React,BE 作为 Springboot。我正在尝试将 FE 添加到应用程序中。注册后,我尝试登录该应用程序。登录成功后,我们得到JWT Token。为此,我们需要在正文中发送用户名、密码和授权类型,在标头中发送基本身份验证详细信息。当


var postData = {
      username: a,
      password: b,
      grant_type:'c'
    };

    let axiosConfig = {
      headers: {
          'Content-Type': 'application/json;charset=UTF-8',
          "Access-Control-Allow-Origin": "*",
          "Accept": "application/json" ,
          "Authorization":"Basic" + " " +base64.encode("U" + ":" + "p")
      }
    };
    
    axios.post('http://localhost:9003/login/token', postData,axiosConfig)
    .then((res) => {
      console.log("RESPONSE RECEIVED: ", res);
    })
    .catch((err) => {
      console.log("AXIOS ERROR: ", err);
    })

我运行这个程序时,我收到错误,

Access to XMLHttpRequest at 'http://localhost:9003/login/token' from origin 'http://localhost:3000' 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.

我的 Spring boot 代码是

 @Override
      
      @CrossOrigin(origins = "*", allowedHeaders = "*") public void
      configure(HttpSecurity http) throws Exception {
        
      
      http.cors().and().exceptionHandling() .authenticationEntryPoint( (request,
      response, authException) ->
      response.sendError(HttpServletResponse.SC_UNAUTHORIZED))
      .and().authorizeRequests().antMatchers("/*").authenticated().and().httpBasic();
    
      http.exceptionHandling().authenticationEntryPoint(new
      CustomAuthenticationEntryPoint());
     
      
      
      }


     @Override
    @CrossOrigin(origins = "*",allowedHeaders="*")
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {

        endpoints.pathMapping("/oauth/token", "/login/token").tokenStore(tokenStore())
                .tokenEnhancer(jwtAccessTokenConverter()).authenticationManager(authenticationManager)
                .userDetailsService(userDetailsService);

有人知道如何解决这个问题吗?

I am working on a project with FE as react and BE as Springboot. I am trying to add FE to the application. After registration, I have tried to login to the application. After successful login, we get JWT Token. For that we need to send username, password and grant type in body and Basic authentication details in header. The is


var postData = {
      username: a,
      password: b,
      grant_type:'c'
    };

    let axiosConfig = {
      headers: {
          'Content-Type': 'application/json;charset=UTF-8',
          "Access-Control-Allow-Origin": "*",
          "Accept": "application/json" ,
          "Authorization":"Basic" + " " +base64.encode("U" + ":" + "p")
      }
    };
    
    axios.post('http://localhost:9003/login/token', postData,axiosConfig)
    .then((res) => {
      console.log("RESPONSE RECEIVED: ", res);
    })
    .catch((err) => {
      console.log("AXIOS ERROR: ", err);
    })

When I run this program, I got the error,

Access to XMLHttpRequest at 'http://localhost:9003/login/token' from origin 'http://localhost:3000' 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.

And My Spring boot Code is

 @Override
      
      @CrossOrigin(origins = "*", allowedHeaders = "*") public void
      configure(HttpSecurity http) throws Exception {
        
      
      http.cors().and().exceptionHandling() .authenticationEntryPoint( (request,
      response, authException) ->
      response.sendError(HttpServletResponse.SC_UNAUTHORIZED))
      .and().authorizeRequests().antMatchers("/*").authenticated().and().httpBasic();
    
      http.exceptionHandling().authenticationEntryPoint(new
      CustomAuthenticationEntryPoint());
     
      
      
      }


     @Override
    @CrossOrigin(origins = "*",allowedHeaders="*")
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {

        endpoints.pathMapping("/oauth/token", "/login/token").tokenStore(tokenStore())
                .tokenEnhancer(jwtAccessTokenConverter()).authenticationManager(authenticationManager)
                .userDetailsService(userDetailsService);

Anybody know how to solve this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

千纸鹤带着心事 2025-01-22 23:22:57

根据 MDN 文档,凭证请求的飞行前响应标头应包含一组特定的Access-Control-Allow-Origin 而不是通配符 * 。可以通过扩展 WebSecurityConfigurerAdapter 来设置服务的 cors 配置。

我们的 spring-boot 项目面临类似的挑战,以下配置帮助克服了 cors 故障

@EnableWebSecurity
public class DefaultAuthConfiguration extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
       http.cors(cors -> {
            CorsConfigurationSource cs = resources -> {
                CorsConfiguration corsConfiguration = new CorsConfiguration();
                corsConfiguration.setAllowedOrigins(List.of("http://localhost:3000","http://localhost:3001"));
                corsConfiguration.setAllowedMethods(List.of("POST", "GET", "PUT", "DELETE", "OPTIONS"));
                corsConfiguration.setAllowedHeaders(List.of("Authorization",
                        "Content-Type",
                        "X-Requested-With",
                        "Accept",
                        "X-XSRF-TOKEN"));
                corsConfiguration.setAllowCredentials(true);
                return corsConfiguration;
            };

            cors.configurationSource(cs);
        });
    }
}

As per MDN docs, the pre-flight response headers for a credentialed request should include a specific set of Access-Control-Allow-Origin and not a wild-card * .The cors config for the service can be setup by extending the WebSecurityConfigurerAdapter.

We faced a similar challenge with our spring-boot project and the following configuration helped overcome the cors failure

@EnableWebSecurity
public class DefaultAuthConfiguration extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
       http.cors(cors -> {
            CorsConfigurationSource cs = resources -> {
                CorsConfiguration corsConfiguration = new CorsConfiguration();
                corsConfiguration.setAllowedOrigins(List.of("http://localhost:3000","http://localhost:3001"));
                corsConfiguration.setAllowedMethods(List.of("POST", "GET", "PUT", "DELETE", "OPTIONS"));
                corsConfiguration.setAllowedHeaders(List.of("Authorization",
                        "Content-Type",
                        "X-Requested-With",
                        "Accept",
                        "X-XSRF-TOKEN"));
                corsConfiguration.setAllowCredentials(true);
                return corsConfiguration;
            };

            cors.configurationSource(cs);
        });
    }
}

GRAY°灰色天空 2025-01-22 23:22:57

下面这个类配置 CORS 策略,它对我有用。我认为你的问题是 @CrossOrigin 应该位于控制器类中。

@Configuration
public class AppConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**");
    }
}

如果您想要更多配置,请点击此链接 https://spring.io/guides/gs /rest-service-cors/

This class below to config CORS policy it worked for me.And i think your poblem is @CrossOrigin should be located in controller class.

@Configuration
public class AppConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**");
    }
}

If you want more config follow this link https://spring.io/guides/gs/rest-service-cors/

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文