首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从角到Spring安全OAuth启用服务器调用时发生CORS错误

从角到Spring安全OAuth启用服务器调用时发生CORS错误
EN

Stack Overflow用户
提问于 2022-01-30 05:43:19
回答 2查看 343关注 0票数 0

我有一个角度的项目,它将发送一个头授权与价值比。UI被集成到Keycloak,令牌被刷新并通过角度拦截器放置在标头上,所有这些都在UI上很好。

在其余部分,服务器运行Spring + Security + OAuth2ResourceServer。

我有一个Security类,它启用Security,它创建默认的cors过滤器。

然而,在运行在http://localhost:4200上的浏览器上,我得到了CORS错误。

因此,我在CorsFilter类中创建了一个单独的SpringApplication bean。

代码语言:javascript
复制
@Bean
public CorsFilter getCorsFilter() {
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    CorsConfiguration config = new CorsConfiguration();
    config.setAllowCredentials(true);
    config.setAllowedOriginPatterns(Arrays.asList("http://localhost:4200"));
    config.addAllowedHeader("*");
    config.addAllowedMethod("*");
    source.registerCorsConfiguration("/**", config);
    return new CorsFilter(source);
}

不过,我在UI上还是得到了CORS错误。

以下Spring安全配置

代码语言:javascript
复制
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors()        
            .antMatcher("/api/**")
            .authorizeRequests()
            .antMatchers(HttpMethod.GET)
            .hasAnyAuthority("SCOPE_read", "SCOPE_profile", "ROLE_USER")
            .antMatchers(HttpMethod.POST)
            .hasAnyAuthority("SCOPE_read", "SCOPE_profile", "ROLE_USER")
                    .anyRequest().authenticated()
        .and()
          .oauth2ResourceServer()
            .jwt();
    }
}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2022-01-30 05:51:39

经过一天的分析,确定了如何定制默认的CorsFilter。

我定义的新鲜CorsFilter bean没有被spring安全性所识别。因此,我不得不定制http.cors()如下所示。

代码语言:javascript
复制
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {// @formatter:off
        http.cors(corsCustomiser())        
            .antMatcher("/api/**")
            .authorizeRequests()
            .antMatchers(HttpMethod.GET)
            .hasAnyAuthority("SCOPE_read", "SCOPE_profile", "ROLE_USER")
            .antMatchers(HttpMethod.POST)
            .hasAnyAuthority("SCOPE_read", "SCOPE_profile", "ROLE_USER")
                    .anyRequest().authenticated()
        .and()
          .oauth2ResourceServer()
            .jwt();
    }//@formatter:on

    private Customizer<CorsConfigurer<HttpSecurity>> corsCustomiser() {
        return new Customizer<CorsConfigurer<HttpSecurity>>() {
            @Override
            public void customize(CorsConfigurer<HttpSecurity> t) {
                t.configurationSource(getCorsConfiguration());              
            }           
        };
    }   
    
    private CorsConfigurationSource getCorsConfiguration() {    
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        config.setAllowedOriginPatterns(Arrays.asList("http://localhost:4200"));
        config.addAllowedHeader("*");
        config.addAllowedMethod("*");
        source.registerCorsConfiguration("/**", config);
        return source;
    }
}
票数 0
EN

Stack Overflow用户

发布于 2022-01-30 06:08:06

首先添加"/oauth/token“如下:

代码语言:javascript
复制
@Override
public void configure(WebSecurity web) throws Exception {
    web.ignoring().antMatchers(HttpMethod.OPTIONS, "/oauth/token");
} 

然后设置过滤器:

代码语言:javascript
复制
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
@WebFilter("/*")
public class CorsFilter implements Filter {

    public CorsFilter() {
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, 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-Allow-Headers", "x-requested-with, authorization");
        response.setHeader("Access-Control-Max-Age", "3600");
        if ("OPTIONS".equalsIgnoreCase(((HttpServletRequest) req).getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
        } else {
            chain.doFilter(req, res);
        }
    }

    @Override
    public void destroy() {
    }

    @Override
    public void init(FilterConfig config) throws ServletException {
    }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70912161

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档