1

I am using oauth2 security in spring boot with 2.1.5 version. When I send a request to issue token, I am receiving an only the same token that got before. I cannot get a token until the token is expired. After that, I can get a new token, but again the same situation.

I tried to change the token store from JdbcTokenStore to InMemoryTOkenStore. Besides that, I changed the authentication mechanism AuthenticationProvider to UserDetailsService.But nothing happened.

 @Configuration
 public class OAuth2SecurityConfiguration {

@Configuration
@EnableResourceServer
public static class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {

    private final TokenStore tokenStore;

    public ResourceServerConfiguration(TokenStore tokenStore) {
        this.tokenStore = tokenStore;
    }

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) {
        resources.tokenStore(tokenStore).resourceId(Constants.SERVER_RESOURCE_ID);
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers(Constants.API_BASE_PATH + "/**").authenticated()
                .and().csrf().disable();
    }
}

@Configuration
@EnableAuthorizationServer
public static class OAuth2AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {

    private final AuthenticationManager authenticationManager;
    private final DataSource dataSource;
    private final PasswordEncoder passwordEncoder;

    @Value("${jwt.key.password:my_pay_jwt_password}")
    private String keyStorePassword;

    public OAuth2AuthorizationServerConfiguration(AuthenticationManager authenticationManager, DataSource dataSource, PasswordEncoder passwordEncoder) {
        this.authenticationManager = authenticationManager;
        this.dataSource = dataSource;
        this.passwordEncoder = passwordEncoder;
    }

    @Bean
    public TokenStore tokenStore() {

    return new InMemoryTokenStore();
    }

    @Bean
    public JwtAccessTokenConverter tokenEnhancer() {
        // For getting user information in getPrincipal()
        DefaultUserAuthenticationConverter duac = new DefaultUserAuthenticationConverter();
        DefaultAccessTokenConverter datc = new DefaultAccessTokenConverter();
        datc.setUserTokenConverter(duac);
        JwtAccessTokenConverter converter = new CustomAccessTokenConverter();
        converter.setAccessTokenConverter(datc); // IMPORTANT

        KeyStoreKeyFactory keyStoreKeyFactory = new KeyStoreKeyFactory(new ClassPathResource("static/jwt.jks"), keyStorePassword.toCharArray());
        converter.setKeyPair(keyStoreKeyFactory.getKeyPair("jwt"));
        PublicKey publicKey = keyStoreKeyFactory.getKeyPair("jwt").getPublic();
        String publicKeyString = Base64.encodeBase64String(publicKey
                .getEncoded());
        converter.setVerifierKey(publicKeyString);

        return converter;
    }

    @Bean
    @Primary
    public AuthorizationServerTokenServices defaultAuthorizationServerTokenServices() {
        DefaultTokenServices tokenServices = new LockingTokenServices();
        tokenServices.setAuthenticationManager(this.authenticationManager);
        tokenServices.setTokenStore(tokenStore());
        tokenServices.setTokenEnhancer(tokenEnhancer());
        tokenServices.setSupportRefreshToken(true);
        tokenServices.setReuseRefreshToken(false);

        return tokenServices;
    }

    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) {
        security
                .checkTokenAccess("permitAll()")
                .tokenKeyAccess("isAuthenticated()")
                .allowFormAuthenticationForClients()
                .passwordEncoder(NoOpPasswordEncoder.getInstance());
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.jdbc(dataSource)
                .passwordEncoder(passwordEncoder);
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
        endpoints
                .reuseRefreshTokens(false)
                .accessTokenConverter(tokenEnhancer())
                .authenticationManager(authenticationManager)
                .tokenStore(tokenStore()).approvalStoreDisabled();
        endpoints.exceptionTranslator(exception -> {
            if (exception instanceof OAuth2Exception) {
                OAuth2Exception oAuth2Exception = (OAuth2Exception) exception;
                if (OAuth2Exception.INVALID_GRANT.equals(oAuth2Exception.getOAuth2ErrorCode())) {
                    oAuth2Exception.addAdditionalInformation("error_description", "Invalid username or password");
                }
                return ResponseEntity
                        .status(oAuth2Exception.getHttpErrorCode())
                        .body(oAuth2Exception);
            } else {
                throw exception;
            }
        });
    }
}

}

  • 1
    why new token for every request? Can't you have the same token for a session and then invalidate it? – karthick Jun 12 '19 at 17:55
  • I think If I send a request and get a token, then I log out it from a device. If I have multiple accounts, all accounts will be logged out. This is the problem. – Nasibulloh Yandashev Jun 12 '19 at 18:13
  • Can you add more notes in the question of what problem you are facing now. At this point the question is a bit ambiguous – karthick Jun 12 '19 at 18:45
  • 1
    I am sending a request in order to get an access_token and I am getting it. But If I send the next request, I am getting the previous token. I don't need the previous token, I need a new one. If I don't change the mechanism, then, If I log out the system, all my session which using this token will be invalid. I don't want to do that. That's why I want to get a new token for every request – Nasibulloh Yandashev Jun 12 '19 at 19:03

0 Answers0