即使在 Springboot 应用程序的过滤器中指定 Access-Control-Allow-Origin 标头后,也无法控制跨源请求 [英] Unable to control Cross origin request even after specifying Access-Control-Allow-Origin header inside filter of Springboot application

查看:24
本文介绍了即使在 Springboot 应用程序的过滤器中指定 Access-Control-Allow-Origin 标头后,也无法控制跨源请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的项目中添加了以下过滤器代码 -

I added the following filter code to my project -

package com.package;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Component
//@Slf4j
public class CORSFilter implements Filter {
    private static final Logger logger = LoggerFactory.getLogger(CORSFilter.class);

    @Override
    public void destroy() {
        // Nothing to do
    }

   // @Autowired
   // private SecureFrontEndConfiguration secureFrontEndConfiguration;

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
                         FilterChain chain) throws IOException, ServletException {
        logger.error("Passing through Cors filter");

        HttpServletResponse res = (HttpServletResponse) response;

            res.setHeader("Access-Control-Allow-Origin", "https://some-domain-from-which-I-am-not-calling.com");

            res.addHeader("Access-Control-Allow-Credentials", "true");
    }

    @Override
    public void init(FilterConfig arg0) throws ServletException {
        // Nothing to do
    }
}

我通过点击 API 验证这两个标头出现在响应标头中 -

I verified by hitting the APIs that those two headers are appearing in the response headers -

但是,当我将它托管在一个域上并从托管在另一个域上的应用程序调用时,我仍然能够获得成功响应 -

However, when I host this on a domain and call from an application hosted on another domain, which is not the one I mentioned above against the header, I am still able to get a success response -

2020-06-05 16:47:21,754 259299 [XNIO-3 task-1] INFO  [TokenService.java:57] - API : service/v2/api property api : <user roles>;
2020-06-05 16:47:21,787 259332 [XNIO-3 task-1] INFO  [SomeAuthTokenService.java:50] - Client-Id : <clientid> ,client secret : <secret> , url : https://user management/oauth/tok
en
2020-06-05 16:47:23,519 261064 [XNIO-3 task-1] INFO  [DaoCacheFactory.java:70] - Inside getDaoForWrite returning dao [com.CacheRepository@77019376] for class interface com.CacheDao
2020-06-05 16:47:23,519 261064 [XNIO-3 task-1] INFO  [CacheRepository.java:36] - Inside create() for uuid <User ID> 
2020-06-05 16:47:23,520 261065 [XNIO-3 task-1] INFO  [CacheRepository.java:187] - Inside get() for uuid <User ID> 
2020-06-05 16:47:23,545 261090 [XNIO-3 task-1] INFO  [RedisDAOImpl.java:238] - Response from redis for hmset: OK
2020-06-05 16:47:23,549 261094 [XNIO-3 task-1] INFO  [RedisDAOImpl.java:238] - Response from redis for hmset: OK
2020-06-05 16:47:23,552 261097 [XNIO-3 task-1] INFO  [RedisDAOImpl.java:238] - Response from redis for hmset: OK
2020-06-05 16:47:23,552 261097 [XNIO-3 task-1] INFO  [CacheService.java:121] - Cached profile for user <User ID>
2020-06-05 16:47:23,570 261115 [XNIO-3 task-1] INFO [CORSFilter.java:40] - Passing through Cors filter
2020-06-05 16:47:25,615 263160 [XNIO-3 task-1] WARN  [Errors.java:191] - The following warnings have been detected: HINT: A HTTP GET method, public void com.LendMoneyScheduledService.execute
() throws com.LendNotFoundException, returns a void type. It can be intentional and perfectly fine, but it is a little uncommon that GET method returns always "204 No Content".

2020-06-05 16:47:25,670 263215 [XNIO-3 task-1] INFO  [LoggingFilter.java:155] - 1 * Server has received a request on thread XNIO-3 task-1
1 > GET http://<API domain>/service/v2/api
1 > Accept: text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2
1 > Accept-Encoding: gzip
1 > Authorization: Bearer <token>
1 > Cache-Control: no-cache
1 > Connection: close
1 > Content-Type: application/x-www-form-urlencoded; charset=UTF-8
1 > Host: <API domain>
1 > Pragma: no-cache
1 > User-Agent: Java/1.7.0_79
1 > X-Forwarded-For: <IP - source server from which API call is made>, <some other IP>, <yet another IP>, <yet another IP>
1 > X-Forwarded-Host: <API domain>
1 > X-Forwarded-Port: 443
1 > X-Forwarded-Proto: https
1 > X-Forwarded-Server: <API domain>

2020-06-05 16:47:25,732 263277 [XNIO-3 task-1] INFO  [Service.java:137] - Geting balance for customer : <User ID>
2020-06-05 16:47:26,149 263694 [XNIO-3 task-1] INFO  [Service.java:139] - Available balance for customer : <User ID> is : amount value : 2180.10 currency : INR
2020-06-05 16:47:26,196 263741 [XNIO-3 task-1] INFO  [LoggingFilter.java:155] - 1 * Server responded with a response on thread XNIO-3 task-1
1 < 200
1 < Content-Type: application/json

更早的完整响应(在进行更改之前)-

Earlier complete response (before making change) -

2020-06-05 16:14:28,883 1492564 [XNIO-3 task-9] INFO  [TokenService.java:57] - API : service/v2/api property api : <User roles>;
2020-06-05 16:14:30,028 1493709 [XNIO-3 task-9] INFO  [DaoCacheFactory.java:70] - Inside getDaoForWrite returning dao [com.CacheRepository@11c48119] for class interface com.cCacheDao
2020-06-05 16:14:30,028 1493709 [XNIO-3 task-9] INFO  [CacheRepository.java:36] - Inside create() for uuid <User ID> 
2020-06-05 16:14:30,028 1493709 [XNIO-3 task-9] INFO  [CacheRepository.java:187] - Inside get() for uuid <User ID> 
2020-06-05 16:14:30,034 1493715 [XNIO-3 task-9] INFO  [RedisDAOImpl.java:238] - Response from redis for hmset: OK
2020-06-05 16:14:30,036 1493717 [XNIO-3 task-9] INFO  [RedisDAOImpl.java:238] - Response from redis for hmset: OK
2020-06-05 16:14:30,037 1493718 [XNIO-3 task-9] INFO  [RedisDAOImpl.java:238] - Response from redis for hmset: OK
2020-06-05 16:14:30,039 1493720 [XNIO-3 task-9] INFO  [CacheService.java:121] - Cached profile for user <User ID>
2020-06-05 16:14:30,043 1493724 [XNIO-3 task-9] INFO  [LoggingFilter.java:155] - 9 * Server has received a request on thread XNIO-3 task-9
9 > GET http://<API domain>/service/v2/api
9 > Accept: text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2
9 > Accept-Encoding: gzip
9 > Authorization: Bearer <token>
9 > Cache-Control: no-cache
9 > Connection: close
9 > Content-Type: application/x-www-form-urlencoded; charset=UTF-8
9 > Host: <API domain>
9 > Pragma: no-cache
9 > User-Agent: Java/1.7.0_79
9 > X-Forwarded-For: <IP - source server from which API call is made>, <some other IP>, <yet another IP>, <yet another IP>
9 > X-Forwarded-Host: <API domain>
9 > X-Forwarded-Port: 443
9 > X-Forwarded-Proto: https
9 > X-Forwarded-Server: <API domain>

推荐答案

试试这个没有过滤器的配置类,

Try this configuration class without your filter,

@Configuration
public class WebConfig implements WebMvcConfigurer {

    /**
     * This method will enable CORS
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**").allowedOrigins("*")
            .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
            .allowedHeaders("Content-Type", "Authorization", "cache-control").exposedHeaders("Authorization", "UserID")
            .allowCredentials(true).maxAge(3600);
    }

}

这篇关于即使在 Springboot 应用程序的过滤器中指定 Access-Control-Allow-Origin 标头后,也无法控制跨源请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆