webmvcconfiguer addcorsmappings暴露的头文件不工作

6vl6ewon  于 2021-07-07  发布在  Java
关注(0)|答案(1)|浏览(460)

我想返回一个etag头,但是我的客户机无法读取它,因为它没有公开。我有以下代码:

@Configuration
public class WebConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(@NonNull CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedHeaders("*")
                .allowedMethods("*")
                .allowedOrigins("*")
                .exposedHeaders("ETag");
    }

    @Bean
    public ShallowEtagHeaderFilter shallowEtagHeaderFilter() {
        return new ShallowEtagHeaderFilter();
    }
}

但是客户端仍然无法读取etag。唯一有效的方法是:

@ApiResponses({
            @ApiResponse(code = 200, message = "OK"),
            @ApiResponse(code = 500, message = "System Error")
    })
    @ApiOperation(value = "returns the meals", response = MealDTO.class, responseContainer = "List", produces = MediaType.APPLICATION_JSON_VALUE)
    @GetMapping("/meal")
    public List<MealDTO> getMeals(
            @ApiParam(name = "page", type = "Integer", value = "Number of the page", example = "2")
            @RequestParam(required = false) Integer page,
            @ApiParam(name = "size", type = "Integer", value = "The size of one page", example = "5")
            @RequestParam(required = false) Integer size,
            @ApiParam(name = "sortBy", type = "String", value = "sort criteria", example = "name.asc,price.desc")
            @RequestParam(required = false) String sortBy,
            @ApiParam(name = "userId", type = "long", value = "ID of the User", example = "-1")
            @PathVariable Long userId,
            HttpServletResponse response
    ) {
        log.debug("Entered class = MealController & method = getMeals");
        response.setHeader("Access-Control-Expose-Headers", "ETag");
        return this.mealService.getMealsByUserId(page, size, sortBy, userId);
    }

为每个端点手动设置公开的标头。这张Map不是应该做的吗?ExposedHeader根本不适合我。
更新:
从下面的评论中,我看到它可能与websecurityconfigureradapter有关,我还补充说:

@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    private final UserDetailsService userDetailsService;

    public WebSecurityConfig(@Qualifier("userServiceImpl") UserDetailsService userDetailsService) {
        this.userDetailsService = userDetailsService;
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
                .cors()
                .and()
                .addFilter(new AuthenticationFilter(authenticationManager()))
                .addFilter(new AuthorizationFilter(authenticationManager()))
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);

//        http.headers().cacheControl().disable();
    }

    //region Beans
    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Collections.singletonList("*"));
        configuration.setAllowedMethods(Collections.singletonList("*"));
        configuration.setAllowedHeaders(Collections.singletonList("*"));
        configuration.setAllowCredentials(true);
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }
    //endregion
}

更新2:
显示我是如何从我的客户那里打电话的:

export const getMealByIdApi: (mealId: number, etag: string | null) => Promise<Meal | void> = (mealId, etag) => {
    let _config = config;
    if (etag) {
        _config.headers['If-None-Match'] = etag;
    }

    return axiosInstance
        .get<Meal>(`/meal/${mealId}`, _config)
        .then(response => {
            log(`[getMealByIdApi] [${response.status}] Successful API call for meal with id ${mealId}.`);
            const result: Meal = response.data;
            result.etag = response.headers['etag'];
            return result;
        })
        .catch(err => {
            if (err.response.status === 304) {
                log(`[getMealByIdApi] [304] Successful API call for meal with id ${mealId}.`);
                return;
            }

            throw err;
        });
}

如果我没有在endpoint中显式指定response.setheader(“access control expose headers”,“etag”),那么头中就没有etag;

rpppsulh

rpppsulh1#

根据axios获取对响应头字段的访问权限。我们需要将“etag”添加到“access control expose headers”中,这样我们就可以访问 response.headers['etag'] . 因为你已经添加了 ShallowEtagHeaderFilter 还曝光了 addCorsMappings . "应将“etag”添加到cors请求的响应头“access control expose headers”中。
为了确保您的请求是cors,您可以调试 DefaultCorsProcessor#processRequest 方法,并检查 CorsUtils.isCorsRequest(request) 返回真值。

public boolean processRequest(@Nullable CorsConfiguration config, HttpServletRequest request,
        HttpServletResponse response) throws IOException {

    response.addHeader(HttpHeaders.VARY, HttpHeaders.ORIGIN);
    response.addHeader(HttpHeaders.VARY, HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD);
    response.addHeader(HttpHeaders.VARY, HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS);

    if (!CorsUtils.isCorsRequest(request)) {
        return true;  // will not add response header if not CORS
    }

    ...add response header

如果返回false,您可以从 CorsUtils#isCorsRequest 说明:
如果请求是有效的cors请求,则通过检查源报头的存在并确保源不同,返回true。

相关问题