java - Spring 安全访问控制允许来源 : * (CORS) issue on invalid JWT token

标签 java spring-boot spring-security jwt microservices

我在 Spring Boot 应用程序中配置了 Spring Security 的 JWT 安全性。我有问题

Access-Control-Allow-Origin: *

header ,也称为 CORS。我配置了应用程序,因此每个服务器响应中都存在 header ,但是一旦 JWT token 无效,服务器响应就会出现 403 错误代码,而没有 Access-Control-Allow-Origin: * header 。这会导致浏览器将错误消息写入控制台:

Failed to load http://... No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://...' is therefore not allowed access. The response had HTTP status code 403.



这似乎是错误的,我想获得 Access-Control-Allow-Origin: * header 作为响应,即使 JWT token 无效并且服务器响应带有 403 错误代码。

现在我尝试了什么和我的代码。

依赖项:
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.0.5.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>
...

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>

据我了解,这个问题可能是由过滤器链中的过滤器顺序引起的,我尝试将 JWT JwtAuthenticationFilter 放在 CorsFilter 或 CsrfFilter 之后,创建 CorsConfigurationSource bean。这在 https://docs.spring.io/spring-security/site/docs/current/reference/html5/#cors 中描述并在 How to configure CORS in a Spring Boot + Spring Security application? 讨论和 https://github.com/spring-projects/spring-boot/issues/5834 ,但似乎没有任何帮助
@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Value("${com.faircloud.common.security.header}")
    private String header;
    @Value("${com.faircloud.common.security.prefix}")
    private String prefix;
    @Value("${com.faircloud.common.security.validateLink}")
    private String validateLink;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().and().authorizeRequests()
                .antMatchers("/v2/api-docs", "/configuration/ui", "/swagger-resources/**", "/configuration/**",
                        "/swagger-ui.html", "/webjars/**")
                .permitAll()
                .and().authorizeRequests().anyRequest().authenticated().and()
                .addFilterAfter(new JwtAuthenticationFilter(header, prefix, validateLink),
                        CsrfFilter.class)
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    }

    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        final CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(ImmutableList.of("*"));
        configuration.setAllowedMethods(ImmutableList.of("HEAD", "GET", "POST", "PUT", "DELETE", "PATCH"));
        // setAllowCredentials(true) is important, otherwise:
        // The value of the 'Access-Control-Allow-Origin' header in the response must
        // not be the wildcard '*' when the request's credentials mode is 'include'.
        configuration.setAllowCredentials(true);
        // setAllowedHeaders is important! Without it, OPTIONS preflight request
        // will fail with 403 Invalid CORS request
        configuration.setAllowedHeaders(ImmutableList.of("Authorization", "Cache-Control", "Content-Type"));
        final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }
}

这里是 JwtAuthenticationFilter 类。请注意,为了验证 token ,它会通过 http 调用其他微服务。我的应用程序也没有登录端点,因为登录是在其他微服务应用程序上实现的。
public class JwtAuthenticationFilter extends BasicAuthenticationFilter {

    private String header;
    private String prefix;
    private String validateLink;

    public JwtAuthenticationFilter(String header, String prefix, String validateLink) {
        super(new AuthenticationManager() {
            public Authentication authenticate(Authentication authentication) throws AuthenticationException{
                return null;
            }
        });
        this.header = header;
        this.prefix = prefix;
        this.validateLink = validateLink;
    } 

    @Override
    protected void doFilterInternal(HttpServletRequest request, 
            HttpServletResponse response, 
            FilterChain chain)
            throws ServletException, IOException {

        // 1. get the authentication header. Tokens are supposed to be passed in the
        // authentication header
        String headerValue = request.getHeader(header);

        // 2. validate the header and check the prefix
        if (headerValue == null || !headerValue.startsWith(prefix)) {
            chain.doFilter(request, response); // If not valid, go to the next filter.
            return;
        }
        // 3. Get the token     
        String token = headerValue.replace(prefix, ""); 

        try {

            GatewayResponse gatewayResponse = validate(token);

            String userId = gatewayResponse.getUserId();

            /*
            Roles could come from gateway or loaded from current
            microservice database by user id. They are
            hardcoded here to illustrate how to populate
            SecurityContextHolder
            */
            List<String> authorities = new LinkedList<String>();
            authorities.add("USER");
            authorities.add("ADMIN");

            UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(userId, null,
                    authorities.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList()));
            SecurityContextHolder.getContext().setAuthentication(auth);
            addTokenToResponse(gatewayResponse.getAuthHeader(), response);
        } catch (Exception e) {
            // In case of failure. Make sure it's clear; so guarantee user won't be
            // authenticated
            SecurityContextHolder.clearContext();
        }

        // go to the next filter in the filter chain
        chain.doFilter(request, response);
    }

    private void addTokenToResponse(String authHeaderValue, HttpServletResponse response) {
        response.addHeader(header, prefix+authHeaderValue);
    }

    private GatewayResponse validate(String token) {
        /HTTP call here, returns null if invalid token
        ...
    }
}

最佳答案

有类似的问题,无法使其与 CorsConfigurationSource 一起使用。只有基于过滤器的 CORS 支持有帮助:

@Bean
public FilterRegistrationBean filterRegistrationBean() {
    final CorsConfiguration config = new CorsConfiguration();

    config.setAllowCredentials(true);
    config.addAllowedOrigin("http://localhost:4200");
    config.addAllowedHeader("*");
    config.addAllowedMethod("*");

    final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", config);

    FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
    bean.setOrder(Ordered.HIGHEST_PRECEDENCE);

    return bean;
}

关于java - Spring 安全访问控制允许来源 : * (CORS) issue on invalid JWT token,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53727397/

相关文章:

java - 无法在 Android 上的 Xamarin 中使用 PayPal SDK 找到明确的 Activity 类付款 Activity

java - 是否可以在 Linux 下构建 JNI .dll?

Javafx Control EventHandler MouseClicked 所有 isxDown() 方法 false

spring-boot - 禁用分布式跟踪以进行开发

java - 如何在junit中控制日志级别

tomcat - 当我构建应用程序以对抗 SLO(单点注销)时停止工作

java - Android 应用程序可以创建本地 session ,其他使用同一应用程序的人无需中间服务器即可连接到该 session 吗?

spring-boot - --spring.output.ansi.enabled 在哪里配置?

authentication - spring-security:无需身份验证的授权

java - Spring 过滤器没有被调用