프로그래밍/spring

세션 교체 방법과 회원 정보 수정

승민아 2024. 7. 26. 16:57

현제 해더에 프로필 이미지 미리보기는 다음과 같은 html 태그를 갖는다.

<img id="profileImgHeaderPreview" class="rounded-circle w-100 h-100"
     th:src="${#authentication.getPrincipal().profileImgPath}">

타임리프를 이용해 세션에 담긴 사용자 정보를 가지고 프로필 이미지를 출력하고 있다.

 

여기서 발생한 문제는 다음과 같다.

 

사용자가 프로필 변경 페이지에서 프로필 이미지를 변경한다.

기존 프로필 이미지

 

프로필 이미지를 변경하고 저장을 눌러 저장한다.

프로필 이미지 선택 후 저장

 

그러나 문제가 여기서 발생한다.

헤더의 프로필 이미지는 세션 정보를 통하기에 변경되지 않음.

변경 완료시 헤더 부분의 프로필 이미지 미리보기가 바뀌지 않는다.

 

재 로그인시 세션 교체로 이미지 변경 됨

프로필 이미지는 세션 정보를 통해 가져오므로 재 로그인시 세션을 새로 저장하며 변경이 적용 된다.

 

세션 값을 변경하여 저장해보자.

 

그럼 프로필 변경 로직에 세션 변경 로직도 포함해서 문제를 해결할 수 있다.

@Transactional
public void updateMemberProfile(...) {

Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
CustomUserDetails principal = (CustomUserDetails) authentication.getPrincipal();
CustomUserDetails userDetails = new CustomUserDetails(...);
SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(userDetails, "", null));

}
  • SecurityContextHolder에서 Authentication을 꺼내온다.
    • Authentication은 SpringSecurity에서 인증 정보를 나타내는 인터페이스이다.
  • authentication에서 getPrincipal로 인증된 정보 객체를 꺼내온다.
    • CustomUserDetails는 현재 내 프로젝트에서 구현한 UserDetails 클래스이다.
  • new CustomUserDetails : SecurityContext과 세션에 새로 저장할 클래스를 생성한다.
    • 이때 변경된 정보(프로필 이미지 경로 등등..)를 생각하여 변경하여 생성한다.
  • setAuthentication : SecurityContext의 Authentication을 새로 설정한다.

 

 

이제 프로필 변경 메소드를 다시 실행 시켜보자.

프로필 이미지 변경시

프로필 변경을 완료했다.

 

세션 교체로 프로필 이미지 변경 완료

프로필 변경 완료시 세션 정보도 새로 변경 저장하므로 헤더의 프로필 이미지 미리보기 또한 변경된다.!