带有Jersey和Spring Security OAuth2的Spring Boot


问题内容

遵循Spring Boot的示例:来自GitHub的示例代码,一切似乎都能正常工作。

但是,当我将Spring Boot Security OAuth2集成到项目中时,我的OAuth2端点将停止工作。日志中有一个警告:

2017-05-04 08:56:24.109 WARN 2827 --- [nio-8080-exec-1] o.glassfish.jersey.servlet.WebComponent : A servlet request to the URI http://127.0.0.1:8080/oauth/token contains form parameters in the request body but the request body has been consumed by the servlet or a servlet filter accessing the request parameters. Only resource methods using @FormParam will work as expected. Resource methods consuming the request body by other means will not work as expected.

这让我觉得即使我没有注册端点,Jersey也正在捕获它并处理主体,这使Spring MVC无法接受请求…

我的球衣配置是:

@Component
public class JerseyConfig extends ResourceConfig {

    public JerseyConfig() {
        register(InfoController.class);
    }

}

我的信息控制器非常简单:

@Component
@Path("/me")
@Produces("application/json")
public class InfoController {
  @GET
  public String meAction() {
    return "Hi";
  }
}

最后,我尝试拨打的电话正在日志中引起警告:

curl -X POST -u CLIENT_APPLICATION:123456789 http://127.0.0.1:8080/oauth/token -H "Accept: application/json" -d "password=aaa&username=aa&grant_type=password&client_id=CLIENT_APPLICATION"

有两个项目(之间存在已知的不兼容spring-boot-starter-jersey,并spring-security-oauth2在这个意义上?

删除Jersey配置可使其全部正常工作,但是我需要在控制器上使用它。

我对OAuth2的配置是:

@Configuration
public class OAuth2ServerConfiguration {
  @Configuration
  @EnableResourceServer
  protected static class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {
    @Override
    public void configure(ResourceServerSecurityConfigurer resources) {
      resources.resourceId("OAuth2 Server");
    }
    @Override
    public void configure(HttpSecurity http) throws Exception {
      // @formatter:off
      http
          .authorizeRequests()
          .antMatchers("/oauth/token").permitAll()
          .antMatchers("/*").authenticated();
      // @formatter:on
    }
  }
}

然后是安全性配置本身:

@Configuration
@EnableWebSecurity
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {

  private final ApiUserDetailsService userDetailsService;

  @Autowired
  public WebSecurityConfiguration(ApiUserDetailsService userDetailsService) {
    this.userDetailsService = userDetailsService;
  }

  @Override
  protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.userDetailsService(userDetailsService);
  }

  @Bean
  @Override
  public AuthenticationManager authenticationManagerBean() throws Exception {
    return super.authenticationManagerBean();
  }
}

提前致谢!


问题答案:

似乎Jersey正在尝试处理OAuth终结点,应该这样做。原因是Jersey的默认映射是/*,这意味着它将处理所有URL的请求。您可以通过以下两种方式进行更改:

  1. 使用不同的映射@ApplicationPathResourceConfig子类之上添加一个
@Component
@ApplicationPath("/api")
public class JerseyConfig extends ResourceConfig {}
  1. 您可以在application.properties文件中添加映射
    spring.jersey.application-path=/api
    

这将为/api您的所有Jersey终结点添加前缀,并且还会导致Jersey仅处理以开头的请求,而不处理所有请求/api