java 如何在 Spring Boot 中更改允许的标头

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40202908/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 05:00:01  来源:igfitidea点击:

How to alter allowed headers in Spring Boot

javaspringauth0

提问by Hyman Wooding

I'm currently using Auth0 (and an Angular 2 GUI), which sends a header of the type "x-xsrf-token"in the request to a Spring Boot API.

我目前正在使用 Auth0(和一个 Angular 2 GUI),它将"x-xsrf-token"请求中类型的标头发送到 Spring Boot API。

I get the error:

我收到错误:

"XMLHttpRequest cannot load http://localhost:3001/ping. Request header field x-xsrf-token is not allowed by Access-Control-Allow-Headers in preflight response."

“XMLHttpRequest 无法加载http://localhost:3001/ping。在预检响应中,Access-Control-Allow-Headers 不允许请求标头字段 x-xsrf-token。”

This is fair enough as the list of Access-Control-Response-Headers in Response Headers does not include x-xsrf-token(when debugging the request in the network tab in Chrome).

这很公平,因为响应标头中的访问控制响应标头列表不包括x-xsrf-token(在 Chrome 的网络选项卡中调试请求时)。

I have tried a number of solutions, the closest I think I have come is to override the configure method in AppConfig, and add in my own CorsFilter, like below:

我尝试了许多解决方案,我认为最接近的是覆盖中的配置方法AppConfig,并添加我自己的方法CorsFilter,如下所示:

(Imports removed for brevity)

@Configuration
@EnableWebSecurity(debug = true)
@EnableGlobalMethodSecurity(prePostEnabled = true)
@Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
public class AppConfig extends Auth0SecurityConfig {

    @Bean
    public Auth0Client auth0Client() {
        return new Auth0Client(clientId, issuer);
    }

    @Bean
    public Filter corsFilter() {
        UrlBasedCorsConfigurationSource source = new     UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        config.addAllowedOrigin("*");
        config.addAllowedHeader("Content-Type");
        config.addAllowedHeader("x-xsrf-token");
        config.addAllowedHeader("Authorization");
        config.addAllowedHeader("Access-Control-Allow-Headers");
        config.addAllowedHeader("Origin");
        config.addAllowedHeader("Accept");
        config.addAllowedHeader("X-Requested-With");
        config.addAllowedHeader("Access-Control-Request-Method");
        config.addAllowedHeader("Access-Control-Request-Headers");
        config.addAllowedMethod("OPTIONS");
        config.addAllowedMethod("GET");
        config.addAllowedMethod("PUT");
        config.addAllowedMethod("POST");
        config.addAllowedMethod("DELETE");
        source.registerCorsConfiguration("/**", config);

        return new CorsFilter(source);
    }

    @Override
    protected void authorizeRequests(final HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/ping").permitAll().antMatchers("/").permitAll().anyRequest()
            .authenticated();
    }

    String getAuthorityStrategy() {
        return super.authorityStrategy;
    }

    @Override
    protected void configure(final HttpSecurity http) throws Exception {
        http.csrf().disable();
        http.addFilterAfter(auth0AuthenticationFilter(auth0AuthenticationEntryPoint()),
            SecurityContextPersistenceFilter.class)
            .addFilterBefore(simpleCORSFilter(), Auth0AuthenticationFilter.class);
        authorizeRequests(http);http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);

        http.cors();
        }
    }

Unfortunately I have had no success with this, and still see the x-xsrf-tokenmissing in the response header of my get request.

不幸的是,我没有成功,并且仍然x-xsrf-token在我的 get 请求的响应头中看到丢失。

My base project is this: https://github.com/auth0-samples/auth0-spring-security-api-sample/tree/master/01-Authentication/src/main

我的基本项目是这样的:https: //github.com/auth0-samples/auth0-spring-security-api-sample/tree/master/01-Authentication/src/main

Any ideas would be welcome.

欢迎任何想法。

回答by Hyman Wooding

Ultimately I solved this myself. I removed this dependency here in the pom.xml file:

最终我自己解决了这个问题。我在 pom.xml 文件中删除了这个依赖项:

<dependency>
            <groupId>com.auth0</groupId>
            <artifactId>auth0-spring-security-api</artifactId>
            <version>0.3.1</version>
</dependency> 

because it is an open source project on github, here https://github.com/auth0/auth0-spring-security-api. I added the source code to my project in its own package, and added its dependencies to my pom.xml file. Then I changed the doFilter method in the Auth0CORSFilter to include my x-xsrf-token:

因为是github上的开源项目,这里https://github.com/auth0/auth0-spring-security-api。我将源代码添加到我自己的项目包中,并将其依赖项添加到我的 pom.xml 文件中。然后我更改了 Auth0CORSFilter 中的 doFilter 方法以包含我的 x-xsrf-token:

@Override
public void doFilter(final ServletRequest req, final ServletResponse res, final FilterChain chain) throws IOException, ServletException {
    final HttpServletResponse response = (HttpServletResponse) res;
    response.setHeader("Access-Control-Allow-Origin", "*");
    response.setHeader("Access-Control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE");
    response.setHeader("Access-Control-Max-Age", "3600");
    response.setHeader("Access-Control-Allow-Headers", "Authorization, x-xsrf-token, Access-Control-Allow-Headers, Origin, Accept, X-Requested-With, " +
            "Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers");
    chain.doFilter(req, res);
}

Unfortunately, I now won't be able to switch versions as easily if I need to, I also have a slightly more cluttered codebase, however as I am new to Spring this was far easier than spending hours trying to override the Auth0CORSFilter Bean, if that was ever possible.

不幸的是,如果需要,我现在无法轻松切换版本,我的代码库也稍微有些混乱,但是由于我是 Spring 的新手,这比花费数小时尝试覆盖 Auth0CORSFilter Bean 容易得多,如果那是有可能的。

回答by arcseldon

Believe this is already under discussion on the issue you posted herebut thought it worth replying on SOF since you have raised the question here too.

相信这已经在讨论您在此处发布的问题但认为值得在 SOF 上回复,因为您也在这里提出了问题。

What you can do, is modify your AppConfigto override the CORS Filter setting from the default library configwith your own updated CORS Filter implementation

您可以做的是修改您的AppConfig以使用您自己更新的CORS 过滤器实现覆盖默认库配置中的 CORS 过滤器设置

I think in your case, this might be just appending x-xsrf-tokento this line:

我认为在你的情况下,这可能只是将x-xsrf-token附加到这一行:

response.setHeader("Access-Control-Allow-Headers", "Authorization, Access-Control-Allow-Headers, Origin, Accept, X-Requested-With, " +
                "Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers");

However, as i have stated in the github issue (linked above), if you send me your HAR file I can verify this is definitely the case and provides a working solution for you.

但是,正如我在 github 问题(上面链接)中所述,如果您将您的 HAR 文件发送给我,我可以验证确实如此,并为您提供了一个可行的解决方案。

回答by kuhajeyan

try,

尝试,

@Bean
    public FilterRegistrationBean corsFilter() {
        UrlBasedCorsConfigurationSource source = new     UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        config.addAllowedOrigin("*");

        config.addAllowedHeader("*");       
        config.addAllowedMethod("*");        
        source.registerCorsConfiguration("/**", config);



        FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
        bean.setOrder(0);
        return bean;


    }

https://spring.io/blog/2015/06/08/cors-support-in-spring-framework

https://spring.io/blog/2015/06/08/cors-support-in-spring-framework