簡體   English   中英

CORS 干擾 Spring Security oauth2

[英]CORS interfering with Spring Security oauth2

我在嘗試從瀏覽器的oauth/token獲取令牌時遇到問題。 我有一個帶有 Spring Security 和 Spring Security oauth 的 Spring Boot 應用程序,我正在嘗試從不同端口中的 javascript SPA 進行身份驗證。

當在后端禁用 CORS 時,我可以使用 Postman 或終端從 oauth 端點獲取令牌沒問題,但由於 CORS 預檢失敗,我無法從 javascript 獲取它們。

如果我啟用 CORS,預檢成功,但現在我收到InsufficientAuthenticationException“沒有客戶端身份驗證。嘗試添加適當的身份驗證過濾器” 據我所知,這是因為 Spring Security 無法從請求中獲取主體。

有沒有人有關於如何處理這個問題的建議?

顯然,Oauth2 端點和過濾器在進入 Spring Security 過濾器鏈之前得到處理,因此添加 CORS 過濾器通常不起作用,但添加具有高順序優先級的 CORS 過濾器 bean 最終會起作用。

這是我的 CORS 專用配置類(改編自官方 spring 指南,稍后我將對其進行調整)

@Configuration
public class CorsConfig {
//IMPORTANT: it has to be a normal configuration class, 
//not extending WebMvcConfigurerAdapter or other Spring Security class
    @Bean
    public FilterRegistrationBean customCorsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        config.addAllowedOrigin("http://localhost:3000");
        config.addAllowedHeader("*");
        config.addAllowedMethod("*");
        source.registerCorsConfiguration("/**", config);
        FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));

        //IMPORTANT #2: I didn't stress enough the importance of this line in my original answer, 
        //but it's here where we tell Spring to load this filter at the right point in the chain
        //(with an order of precedence higher than oauth2's filters)
        bean.setOrder(Ordered.HIGHEST_PRECEDENCE);
        return bean;
    }
}

如果您使用的是 Spring Boot 2,則只是 SrThompson 響應的更新,類FilterRegistrationBean現在是通用的。

所以代碼看起來像這樣:

@Configuration
public class CorsConfig {

    @Bean
    public FilterRegistrationBean<CorsFilter> customCorsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        config.setAllowedMethods(Collections.singletonList("*"));
        config.setAllowedHeaders(Collections.singletonList("*"));
        config.addAllowedOrigin("http://localhost:3000");
        config.addAllowedOrigin("http://production.url");
        config.setAllowCredentials(true);
        source.registerCorsConfiguration("/**", config);
        FilterRegistrationBean<CorsFilter> bean = new FilterRegistrationBean<>(new CorsFilter(source));

        bean.setOrder(Ordered.HIGHEST_PRECEDENCE);
        return bean;
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM