SpringBoot + Thymeleaf + JWT + Redis 사용중 깃허브 로그인 API serializationfailedexception 처리

박찬규·2023년 6월 15일
0

GoodJobProject

목록 보기
4/9

SpringBoot + Thymeleaf + JWT + Redis를 사용하여 깃허브 로그인을 구현하던 중 문제가 발생했다.


오류를 읽어보니 serialize를 못 한다는 것이었다.

어떤식으로 메시지를 받아오는지 직접 봐야겠다 싶어 hgetall 'key값' 명령어로 레디스에서 값을 열어봤다.

스프링부트에서 Redis의 DefaultSerializer가 JdkSerializerationRedisSerializer 이기 때문에, 깃허브에서 제공한 리소스를 레디스에 저장 후 자바 Object 객체로 역직렬화 하지 못해서 발생한 오류였다.

이 오류는 JdkSerializerationRedisSerializer 대신 Reids의 key, value를 String으로 설정해주는 StringRedisSerializer를 사용하게 설정해주면서 해결했다.

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
public class RedisRepositoryConfig {

   @Value("${spring.data.redis.host}")
   private String host;

   @Value("${spring.data.redis.port}")
   private int port;

   // lettuce
   @Bean
   public RedisConnectionFactory redisConnectionFactory() {
       return new LettuceConnectionFactory(host, port);
   }

   @Bean
   public RedisTemplate<String, Object> redisTemplate() {
       RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
       redisTemplate.setConnectionFactory(redisConnectionFactory());
       redisTemplate.setEnableTransactionSupport(true);

       redisTemplate.setKeySerializer(new StringRedisSerializer());
       redisTemplate.setValueSerializer(new StringRedisSerializer());
       redisTemplate.setHashKeySerializer(new StringRedisSerializer());
       redisTemplate.setHashValueSerializer(new StringRedisSerializer());

       return redisTemplate;
   }
}

프로젝트를 하면서 jwt 인증만 사용했음에도 불구하고 왜 세션이 레디스에 저장되나 의문이 생겨 build.gradle을 찾아보니

spring-session-data-redis 라이브러리를 사용했기 때문임을 알게되었다. 이전에 쿠버네티스를 이용한 분산 환경에서 사용했던 옵션을 아무 생각없이 복붙해버려 생긴 일이었다..

해당 라이브러리는 제외해주고 혹시모를 추가 문제 방지를 위해 Security 설정에서 세션을 꺼줬다.

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http.csrf(AbstractHttpConfigurer::disable)
                .sessionManagement(sessionManagement -> sessionManagement
                        .sessionCreationPolicy(STATELESS)
                )

원숭이처럼 그대로 갖다 쓰니까 쓴 맛을 봤다.. 최소한의 공부는 하고 써야 삽질을 방지할 수 있다는 걸 또 한번 느꼈다..
그래도 똥인지 된장인지 먹어봤으니 다음에는 잘 구분할 수 있을 것 같다!

0개의 댓글