Я использую безопасность oauth2 при весенней загрузке с версией 2.1.5.Когда я отправляю запрос на выдачу токена, я получаю только тот же токен, что и раньше.Я не могу получить токен, пока токен не истек.После этого я могу получить новый токен, но опять та же ситуация.
Я попытался изменить хранилище токенов с JdbcTokenStore на InMemoryTOkenStore.Кроме того, я изменил механизм аутентификации AuthenticationProvider на UserDetailsService. Но ничего не произошло.
@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;
}
});
}
}
}