2017-07-09 10 views
1

私はoauth2認証を提供するために私のスプリングブートアプリケーションを構成しました。今OAuth2-SpringBoot - リフレッシュトークン

 @Configuration 
    public class OAuth2Configuration { 

     @Configuration 
     @EnableResourceServer 
     protected static class ResourceServerConfiguration extends ResourceServerConfigurerAdapter { 

      @Autowired 
      private CustomAuthenticationEntryPoint customAuthenticationEntryPoint; 

      @Autowired 
      private CustomLogoutSuccessHandler customLogoutSuccessHandler; 

      @Override 
      public void configure(HttpSecurity http) throws Exception { 

       http 
         .exceptionHandling() 
         .authenticationEntryPoint(customAuthenticationEntryPoint) 
         .and() 
         .logout() 
         .logoutUrl("/oauth/logout") 
         .logoutSuccessHandler(customLogoutSuccessHandler) 
         .and() 
         .csrf() 
         .disable() 
         .headers() 
         .frameOptions().disable() 
         .exceptionHandling().and() 
         .sessionManagement() 
         .sessionCreationPolicy(SessionCreationPolicy.STATELESS) 
         .and() 
         .authorizeRequests() 
         .antMatchers(HttpMethod.OPTIONS, "/**").permitAll() 
         .antMatchers("/api/v1/login/**").permitAll() 
         .antMatchers("/api/v1/admin/**").permitAll() 
         .antMatchers("/api/v1/test/**").permitAll() 
         .antMatchers("/oauth/token").permitAll() 
         .antMatchers("/api/**").authenticated(); 
      } 

     } 

     @Configuration 
     @EnableAuthorizationServer 
     protected static class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter implements EnvironmentAware { 

      private static final String ENV_OAUTH = "authentication.oauth."; 
      private static final String PROP_CLIENTID = "clientid"; 
      private static final String PROP_SECRET = "secret"; 
      private static final String PROP_TOKEN_VALIDITY_SECONDS = "tokenValidityInSeconds"; 

      private RelaxedPropertyResolver propertyResolver; 

      @Autowired 
      private DataSource dataSource; 

      @Bean 
      public TokenStore tokenStore() { 
       return new JdbcTokenStore(dataSource); 
      } 

      @Autowired 
      @Qualifier("authenticationManagerBean") 
      private AuthenticationManager authenticationManager; 

      @Override 
      public void configure(AuthorizationServerEndpointsConfigurer endpoints) 
        throws Exception { 
       endpoints 
         .tokenStore(tokenStore()) 
         .authenticationManager(authenticationManager); 
      } 

      @Override 
      public void configure(ClientDetailsServiceConfigurer clients) throws Exception { 
       clients 
         .inMemory() 
         .withClient(propertyResolver.getProperty(PROP_CLIENTID)) 
         .scopes("read", "write") 
         .authorities(Authorities.ROLE_USER.name()) 
         .authorizedGrantTypes("password", "refresh_token", "authorization_code", "implicit") 
         .secret(propertyResolver.getProperty(PROP_SECRET)) 
         .accessTokenValiditySeconds(
           propertyResolver.getProperty(PROP_TOKEN_VALIDITY_SECONDS, Integer.class, 1800)) 
         .refreshTokenValiditySeconds(100000); 
      } 

      @Override 
      public void setEnvironment(Environment environment) { 
       this.propertyResolver = new RelaxedPropertyResolver(environment, ENV_OAUTH); 
      } 

     } 

    } 


     @Configuration 
    @EnableWebSecurity 
    public class SecurityConfiguration extends WebSecurityConfigurerAdapter { 

     @Autowired 
     private UserDetailsService userDetailsService; 

     @Bean 
     public CustomPasswordEncoder passwordEncoder() { 
      return new CustomPasswordEncoder(); 
     } 

     @Autowired 
     public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { 

      auth 
        .userDetailsService(userDetailsService) 
        .passwordEncoder(passwordEncoder()); 

     } 

     @Override 
     public void configure(WebSecurity web) throws Exception { 

      web 
        .ignoring() 
        .antMatchers(HttpMethod.OPTIONS, "/**").antMatchers("/api/login/**"); 
     } 

     @Override 
     public void configure(HttpSecurity http) throws Exception { 
      http.httpBasic().realmName("WebServices").and().sessionManagement() 
        .sessionCreationPolicy(SessionCreationPolicy.STATELESS).and().requestMatchers() 
        .antMatchers("/oauth/authorize").and().authorizeRequests().antMatchers("/oauth/authorize") 
        .authenticated(); 
     } 

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

     @EnableGlobalMethodSecurity(prePostEnabled = true, jsr250Enabled = true) 
     private static class GlobalSecurityConfiguration extends GlobalMethodSecurityConfiguration { 
      @Override 
      protected MethodSecurityExpressionHandler createExpressionHandler() { 
       return new OAuth2MethodSecurityExpressionHandler(); 
      } 

     } 

    } 


    public class UserDetailsServiceImpl implements UserDetailsService { 

    @Inject 
    private AccountDao accountDao; 

    @Override 
    @Transactional 
    public UserDetails loadUserByUsername(final String login) { 
     Account userFromDatabase = null; 
     String lowercaseLogin = login.toLowerCase(); 
     if (lowercaseLogin.contains("@")) { 
      userFromDatabase = accountDao.getByEmailId(lowercaseLogin); 
     } else { 
      userFromDatabase = accountDao.getByPhoneNumber(lowercaseLogin); 
     } 

     if (userFromDatabase != null) { 
      if (!userFromDatabase.getActivated()) { 
       throw new UserNotActivatedException("User " + lowercaseLogin + " was not activated"); 
      } 
      List<GrantedAuthority> grantedAuthorities = userFromDatabase.getRoles().stream() 
        .map(authority -> new SimpleGrantedAuthority(authority.getRoleName())).collect(Collectors.toList()); 
      return new org.springframework.security.core.userdetails.User(userFromDatabase.getAccountName(), 
        userFromDatabase.getAccountPassword(), grantedAuthorities); 
     } else { 
      throw new UsernameNotFoundException("User " + lowercaseLogin + " was not found in the " + "database"); 
     } 
    } 

} 

私はアクセストークンの有効期限が切れた後にリフレッシュトークンを取得しようとするたびとして列電話番号12345678とアカウント名とDB内の行がありますが、私はいつも

2017-07-10 00:57:40.797 INFO 68115 --- [nio-9090-exec-4] o.s.s.o.provider.endpoint.TokenEndpoint : Handling error: NoSuchClientException, No client with requested id: 12345678

を取得https://myTestWebServices/oauth/token?grant_type=refresh_token&refresh_token=f4cc8213-3f2b-4a30-965b-6feca898479e

I認証に設定ヘッダがあります。基本XXX xxxは私が使用するのと同じです私はそれがうまく動作すると仮定しているので、access_tokenを取得します。

しかし、出力は私がパスワードgrant_typeのために、のclientIdとclientSecretが必要とされていると考え、常にこの

{ "error": "unauthorized", "error_description": "User 12345678 was not found in the database" }

+0

完全なスタックトレースを送信してください。リフレッシュトークンをどのように取得しているのかOAuth2の流れを説明してください。 –

+0

@AbhijitSarkar今すぐチェックしてください –

+0

私が提案したものを試しましたか? –

答えて

0

です。 AuthorizationヘッダーにAccessトークンの代わりにBase64でエンコードされたclientIdとclientSecretを渡します。これと同じように:loadUserByUsernameにブレークポイントを置く、

また
curl --data "grant_type=password&username=user&password=pass&client_id=my_client" http://localhost:8080/oauth/token" 

とチェック:

curl -H "Authorization: Bearer [base64encode(clientId:clientSecret)]" "https://yourdomain.com/oauth/token?grant_type=refresh_token&refresh_token=[yourRefreshToken]" 

私はあなたが最初に(私は尋ねていても言いませんでした)このようなトークンを取得と仮定していますリフレッシュに失敗した場合に呼び出されます。

関連する問題