预期的CORS过滤器仅应用于预检一次,并允许随后的请求通过Oauth2ProcessingFilter

时间:2019-06-25 12:12:24

标签: spring spring-security spring-security-oauth2

我有一个通过Keycloak进行身份验证的Angular前端应用程序,然后从那里调用传递给accesss_token的Spring Backend Resource服务器,以便通过keycloak进行验证 因为它是后端的CORS应用程序,所以我在WebSecurityConfigAdapter上添加了@Bean corsConfigurationSource(),优先级为Ordered.HIGHEST PREFERNCE,以便优先于Oauth2ProcessingFiter。初始OPTION请求与CORS过滤器的响应标头一起传递,第二个实际资源请求也通过CORS filtr和OAuth2Processfilter不会被调用,因此即使该用户位于密钥斗篷中,它也是匿名用户。

@EnableWebSecurity
@Order(Ordered.HIGHEST_PRECEDENCE)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
    http.cors().and()
            .authorizeRequests()
           .anyRequest()
           .authenticated();
}

 @Bean

  CorsConfigurationSource corsConfigurationSource() {
    CorsConfiguration configuration = new CorsConfiguration();
    configuration.setAllowedOrigins(Arrays.asList("*"));
    configuration.setAllowedHeaders(Arrays.asList("authorization"));
    configuration.setAllowedMethods(Arrays.asList("GET","POST"));
    UrlBasedCorsConfigurationSource source = new 
  UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", configuration);
    return source;
 }
 }

  @SpringBootApplication
  @EnableResourceServer
  public class VehicleApplication {

public static void main(String[] args) {
    SpringApplication.run(VehicleApplication.class, args);
}
    }

  application.yml

    security:
    oauth2:
    resource:
    user-info-uri: http://localhost:8080/auth/realms/VMS/protocol/openid- 
     connect/userinfo


     pom.xml
        <dependency>
        <groupId>org.springframework.security.oauth.boot</groupId>
        <artifactId>spring-security-oauth2-autoconfigure</artifactId>
        <version>2.1.6.RELEASE</version>
        </dependency>

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

预期的CORS过滤器仅应用于预检一次,并允许随后的请求通过Oauth2ProcessingGilter

1 个答案:

答案 0 :(得分:0)

解决了此问题,从Angular中删除了CORS过滤器,添加了proxy.conf.js,因此由应用发出请求而不是浏览器,然后Oauth2Processing过滤器完成了使用keycloak检查令牌的工作