使用AbstractPreAuthenticatedProcessingFilter在REST服务中读取JWT令牌

时间:2018-06-14 13:40:26

标签: spring spring-boot spring-security spring-security-oauth2 angular2-jwt

以下场景:我的Spring Boot 2.0 REST服务获取Angular 6客户端通过API网关发出的请求,该网关与Keycloak通信。因此,请求由已经过身份验证的用户(由API网关完成)完成。有关用户及其角色的信息打包在JWT令牌中,该令牌是请求的一部分(在带有承载令牌的Authorization标头中)。

如何在服务端处理令牌?

我构建TokenPreAuthenticatedProcessingFilter(基于AbstractPreAuthenticatedProcessingFilter)并在WebSecurityConfigurerAdapter中对其进行了配置,如下所示:

    protected void configure(HttpSecurity http) throws Exception {
    http.antMatcher("/**")
            .cors()
            .and()
            .authorizeRequests()
            .mvcMatchers(HttpMethod.GET, "/health", "/info").anonymous()
            .anyRequest().authenticated()
            .and()
            .addFilterBefore(tokenPreAuthenticatedFilter(), RequestHeaderAuthenticationFilter.class)
            .sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.NEVER)
            .and()
            .csrf().disable();

到目前为止一直很好,但是在达到(并运行)Controller中的终点后,请求被重定向,客户端获取HTTP状态代码302作为响应而不是数据。

问题:

  1. 此方案的AbstractPreAuthenticatedProcessingFilter方法是否正确? (我已在文档hier http://springcert.sourceforge.net/sec-3/preauth.html中阅读,它应该是),
  2. 如果是,那么如何避免重定向?
  3. 如果没有,怎么做其他正确的方式?

1 个答案:

答案 0 :(得分:0)

您似乎已将WebSecurityConfigurerAdapter设置为MVC类型的处理器,这就是为什么要获得302而不是200和数据的原因。您不需要cors,因此请将其关闭,您应该对路径使用ant匹配器,而不是mvc匹配器。我不确定会话创建策略,但通常将其设置为无状态。然后将登录表单设置为“禁用”。因此,最终的配置将类似于:

http.cors().and().csrf().disable().authorizeRequests()
        .anyRequest().authenticated()
        .antMatchers(HttpMethod.GET, "/health", "/info").anonymous()
        .and()
        .addFilterBefore(tokenPreAuthenticatedFilter(), RequestHeaderAuthenticationFilter.class)
        .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
        .and().formLogin().disable();

我没有其余的代码,因此我无法测试此配置,但我希望它可以使您走上正确的道路。

相关问题