import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClient;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClientService;
import org.springframework.stereotype.Service;
@Service
public class RedisOAuth2AuthorizedClientServiceImpl implements OAuth2AuthorizedClientService {
private final static String REDIS_KEY_PATTERN = "my-oauth2authorizedclient:%S:%S";
private final RedisTemplate<String, OAuth2AuthorizedClient> redisTemplate;
public RedisOAuth2AuthorizedClientServiceImpl(RedisConnectionFactory redisConnectionFactory) {
this.redisTemplate = new RedisTemplate();
this.redisTemplate.setConnectionFactory(redisConnectionFactory);
this.redisTemplate.setKeySerializer(new StringRedisSerializer());
this.redisTemplate.setValueSerializer(new JdkSerializationRedisSerializer());
this.redisTemplate.afterPropertiesSet();
}
@Override
public OAuth2AuthorizedClient loadAuthorizedClient(String clientRegistrationId, String principalName) {
ValueOperations<String, OAuth2AuthorizedClient> valueOperations = redisTemplate.opsForValue();
return (OAuth2AuthorizedClient) valueOperations.get(String.format(REDIS_KEY_PATTERN, clientRegistrationId, principalName));
}
@Override
public void saveAuthorizedClient(OAuth2AuthorizedClient authorizedClient, Authentication principal) {
ValueOperations<String, OAuth2AuthorizedClient> valueOperations = redisTemplate.opsForValue();
valueOperations.set(
String.format(REDIS_KEY_PATTERN, authorizedClient.getClientRegistration().getRegistrationId(), principal.getName()),
authorizedClient
);
}
@Override
public void removeAuthorizedClient(String clientRegistrationId, String principalName) {
redisTemplate.delete(String.format(REDIS_KEY_PATTERN, clientRegistrationId, principalName));
}
}