2017-02-18 74 views
4

我想爲我的REST spring引導項目使用OAuth2。用一些例子,我創建配置的OAuth2:OAuth2與Spring Boot REST應用程序 - 不能使用令牌訪問資源

@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返回

/API代碼200和字符串 「從授權免費」/安全返回{ 「時間戳」:1487451065106, 「狀態」:403, 「錯誤」: 「禁止」, 「消息」:「訪問否認「,」路徑「:」/ 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, 「範圍」:」讀寫「}

然後我試圖發送一個請求(與我得到的令牌),其要求認證爲資源:

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

這裏是響應:

{ 「時間戳」:1487451630224, 「狀態」:403, 「錯誤」: 「禁止」, 「消息」: 「拒絕訪問」, 「路徑」: 「/ API /固定」}

我不明白爲什麼訪問被拒絕。我不確定在配置中,它似乎是不正確的。此外,我還沒有清醒地認識方法的關係配置(HttpSecurity HTTP)在一個延伸WebSecurityConfigurerAdapter類和另一個延伸ResourceServerConfigurerAdapter。 謝謝你的幫助!

+0

當您發送令牌作爲標題'Authorization:Bearer [TOKEN]'時會發生什麼? – dav1d

+0

@ dav1d我試過但訪問仍然被拒絕 – Alex

回答

19

如果您使用的是1.5.1或最近更新的彈簧引導,請注意他們更改了spring security oauth2(Spring Boot 1.5 Release Notes)的過濾順序。

根據發行說明,嘗試將以下屬性添加到應用程序。性能/ YML,這樣做的資源服務器過濾器將其他篩選器作爲備用後使用後 - 這應該引起授權墜落到資源服務器之前被接受:

security.oauth2.resource.filter-order = 3 

你可以找到一個很好的答案爲您的其他問題在這裏:https://stackoverflow.com/questions/28537181

+0

非常感謝您的回答。我添加了這個屬性並刪除了@Order註解。現在我可以獲取訪問令牌,然後使用它獲取/ api/secured資源。但現在我無法獲得/ api/free。我認爲它可以通過更改配置方法來解決。 – Alex

+0

很高興幫助。如果它解決了您的問題,您可以將此答案標記爲已接受。 – Tom

+0

是的,當然,它幫助了很多。 – Alex

相關問題