【问题标题】:CORS Spring Security configuration - 404 No 'Access-Control-Allow-Origin' header is present on the requested resourceCORS Spring Security 配置 - 404 请求的资源上不存在“Access-Control-Allow-Origin”标头
【发布时间】:2019-06-18 06:59:52
【问题描述】:

我正在尝试在我的 Java Spring 项目上设置 CORS。

另外,我有一个带有登录页面的 Angular CLI 应用程序,我想使用我的 Spring API 对用户进行身份验证。

我在客户端收到错误

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.

我在服务器日志中得到了这个:

No mapping found for HTTP request with URI [/authenticateUser]

我尝试了其他线程的一些示例,但客户端错误没有改变,所以我有点困惑在哪里配置 cors

我有一个 AppSecurityConfigextends WebSecurityConfigurerAdapter

@Configuration
@EnableWebSecurity
public class AppSecurityConfig extends WebSecurityConfigurerAdapter {

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {

    User.UserBuilder users = User.withDefaultPasswordEncoder();

    auth.inMemoryAuthentication()
            .withUser(users.username("user1").password("password").roles("ROLE1"))
            .withUser(users.username("user2").password("password").roles("ROLE2"))
            .withUser(users.username("user3").password("password").roles("ROLE3"));
}

@Override
protected void configure(HttpSecurity http) throws Exception {

    http.cors()
        .and()
        .authorizeRequests()
        .anyRequest()
        .authenticated()
        .and()
        .formLogin()
            .loginPage("/loginPageUrl")
            .loginProcessingUrl("/authenticateUser")
            .permitAll();
}

我的 Angular 服务发出请求:

authenticateUser(json: any) {
return this.http.post('http://localhost:8085/authenticateUser'
  , json, {headers : new HttpHeaders()
    .set('Authorization', '')
    });

}

传入的json是:

{ username: this.username, password: this.password }

将以下方法添加到我的 AppSecurityConfig 类解决了“请求的资源上不存在“无 'Access-Control-Allow-Origin' 标头”错误。

@Bean
CorsConfigurationSource corsConfigurationSource() {
    CorsConfiguration configuration = new CorsConfiguration();
    configuration.setAllowedOrigins(Arrays.asList("http://localhost:4200"));
    configuration.setAllowedMethods(Arrays.asList("GET","POST"));
    configuration.addAllowedHeader("content-type");
    configuration.addAllowedHeader("Access-Control-Allow-Origin");
    configuration.addAllowedHeader("Authorization");
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", configuration);
    return source;
}

【问题讨论】:

    标签: java angular spring spring-security


    【解决方案1】:

    在我看来,缺少Access-Control-Allow-Origin 标头不应该与端点缺少映射问题有任何关系。这可能是另一个问题,但与 CORS 无关。

    首先,您应该检查浏览器网络选项卡中的请求和响应标头(当 UI 向 API 发出请求时),以查看响应中是否确实缺少与 CORS 相关的标头。

    这些标题以 - Access-Control-Allow-* 开头,控制来源的是 - Access-Control-Allow-Origin

    您的安全配置代码http.cors() 尝试按照以下逻辑添加CorsFilter(粘贴http.cors() 的Java Doc)

    添加要使用的 CorsFilter。如果名为 corsFilter 的 bean 是 提供,使用 CorsFilter。否则,如果 corsConfigurationSource 是 定义,然后使用 CorsConfiguration。否则,如果 Spring MVC 在使用 HandlerMappingIntrospector 的类路径上。

    因此,如果您没有按照上面的要求提供,那么您需要提供。

    请参阅this answer 尤其是。 3 节。自定义 CORS 配置

    如果时间允许,通过 Spring 提供的过滤器org.springframework.web.filter.CorsFilter 了解逻辑。

    【讨论】:

    • 非常感谢。添加 CorsConfigurationSource 修复了该问题(添加了要发布的代码)。我现在有一个 403 响应,我会花一些时间查看。
    • @user2670815:为了获得更好的帮助,您可以随时附上网络标签的浏览器屏幕截图,其中包含尽可能多的详细信息。
    【解决方案2】:

    试试这个:

    @Configuration
    public class WebConfig extends WebMvcConfigurerAdapter {
    
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/**").allowedOrigins("http://domain1.com","http://domain2.com"
                        "http://domain3.com");
        }
    }
    

    addCorsMappings 方法添加到您的配置类并设置允许的来源网址,这些网址是您的Angular 应用程序的网址。

    在您的情况下,它将是:

    registry.addMapping("/**").allowedOrigins("http://localhost:4200");
    

    允许来自 Angular 应用的请求。

    【讨论】:

    • 我们可以使用:registry.addMapping("/**").allowedOrigins("*");
    • 完成,客户端出现同样的错误。还有 WebMvcConfigurerAdapter 折旧通知。
    • 我注意到我在 tomcat 日志上也有“没有找到带有 URI [/authenticateUser] 的 HTTP 请求的映射”
    猜你喜欢
    • 2014-07-06
    • 2017-04-11
    • 2022-07-28
    • 1970-01-01
    • 2017-10-08
    • 2020-02-13
    • 2019-08-12
    • 2017-08-19
    相关资源
    最近更新 更多