带有Spring Boot REST应用程序的OAuth2 – 无法使用令牌访问资源

我想在我的REST spring启动项目中使用OAuth2。 使用一些示例我已经为OAuth2创建了配置:

@Configuration public class OAuth2Configuration { private static final String RESOURCE_ID = "restservice"; @Configuration @EnableResourceServer protected static class ResourceServerConfiguration extends ResourceServerConfigurerAdapter { @Override public void configure(ResourceServerSecurityConfigurer resources) { // @formatter:off resources .resourceId(RESOURCE_ID); // @formatter:on } @Override public void configure(HttpSecurity http) throws Exception { // @formatter:off http .anonymous().disable() .authorizeRequests().anyRequest().authenticated(); // @formatter:on } } @Configuration @EnableAuthorizationServer protected static class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter { private TokenStore tokenStore = new InMemoryTokenStore(); @Autowired @Qualifier("authenticationManagerBean") private AuthenticationManager authenticationManager; @Autowired private UserDetailsServiceImpl userDetailsService; @Override public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception { // @formatter:off endpoints .tokenStore(this.tokenStore) .authenticationManager(this.authenticationManager) .userDetailsService(userDetailsService); // @formatter:on } @Override public void configure(ClientDetailsServiceConfigurer clients) throws Exception { // @formatter:off clients .inMemory() .withClient("clientapp") .authorizedGrantTypes("password", "refresh_token", "trust") .authorities("USER") .scopes("read", "write") .resourceIds(RESOURCE_ID) .secret("clientsecret") .accessTokenValiditySeconds(1200) .refreshTokenValiditySeconds(3600); // @formatter:on } @Bean @Primary public DefaultTokenServices tokenServices() { DefaultTokenServices tokenServices = new DefaultTokenServices(); tokenServices.setSupportRefreshToken(true); tokenServices.setTokenStore(this.tokenStore); return tokenServices; } } } 

这是我的SecurityConfiguration类:

 @Configuration @EnableWebSecurity @Order(1) public class SecurityConfiguration extends WebSecurityConfigurerAdapter { @Autowired private UserDetailsService userDetailsService; @Override protected void configure(HttpSecurity http) throws Exception { http.csrf().disable(); http .authorizeRequests().antMatchers("/api/register").permitAll() .and() .authorizeRequests().antMatchers("/api/free").permitAll() .and() .authorizeRequests().antMatchers("/oauth/token").permitAll() .and() .authorizeRequests().antMatchers("/api/secured").hasRole("USER") .and() .authorizeRequests().anyRequest().authenticated(); } @Override @Bean public AuthenticationManager authenticationManagerBean() throws Exception { return super.authenticationManagerBean(); } @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } } 

我尝试用2个简单的请求检查我的应用程序:

 @RequestMapping(value = "/api/secured", method = RequestMethod.GET) public String checkSecured(){ return "Authorization is ok"; } @RequestMapping(value = "/api/free", method = RequestMethod.GET) public String checkFree(){ return "Free from authorization"; } 

首先,我检查了两个请求:

/ api / free返回代码200和字符串“Free from authorization”

/ api / secured返回{“timestamp”:1487451065106,“status”:403,“error”:“禁止”,“消息”:“拒绝访问”,“路径”:“/ api / secured”}

似乎他们工作正常。

然后我得到access_token(使用我的用户数据库中的凭据)

/的OAuth /令牌?grant_type =密码&用户名= EMAILA&密码= emailo

响应:

{ “的access_token”: “3344669f-c66c-4161-9516-d7e2f31a32e8”, “token_type”: “承载”, “refresh_token”: “c71c17e4-45ba-458C-9d98-574de33d1859”, “expires_in”:1199, “范围” :“读写”}

然后我尝试向需要身份validation的资源发送请求(带有我获得的令牌):

/ API /固定?=的access_token 3344669f-c66c-4161-9516-d7e2f31a32e8

这是回复:

{“timestamp”:1487451630224,“status”:403,“error”:“禁止”,“消息”:“拒绝访问”,“路径”:“/ api / secured”}

我无法理解访问被拒绝的原因。 我不确定配置,似乎他们是不正确的。 另外,我仍然没有清楚地理解扩展WebSecurityConfigurerAdapter的类中的方法configure(HttpSecurity http)和扩展ResourceServerConfigurerAdapter的另一个方法的关系。 感谢您的任何帮助!

如果您使用的是spring boot 1.5.1或最近更新过它,请注意它们更改了spring security oauth2( Spring Boot 1.5发行说明 )的过滤顺序。

根据发行说明,尝试将以下属性添加到application.properties/yml,在此之后,资源服务器filter将在您的其他filter之后用作后备 – 这应该导致在落入资源之前接受授权服务器:

 security.oauth2.resource.filter-order = 3 

您可以在此处找到其他问题的正确答案: https : //stackoverflow.com/questions/28537181