0

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

如何在服务端处理令牌?

我构建了一个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();

到目前为止一切顺利,但是在控制器中到达(并运行)端点后,请求被重定向并且客户端获得 HTTP 状态代码 302 作为响应而不是数据。

问题:

  1. 这种情况下的方法AbstractPreAuthenticatedProcessingFilter是否正确?(我已经阅读了http://springcert.sourceforge.net/sec-3/preauth.html的文档,它应该是),
  2. 如果是,那么如何避免重定向?
  3. 如果没有,如何以其他正确的方式做到这一点?
4

1 回答 1

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();

我没有你的其余代码,所以我无法测试这个配置,但我希望它可能会让你在正确的道路上走很长一段路。

于 2018-06-19T21:12:32.857 回答