본문 바로가기
반응형
Spring/Security

Spring Security에서 세션값 변경

by brightGarden02 2022. 12. 3.

서비스에서 update를 통해서 수정을 해도

DB에는 수정이 되지만 세션 변경을 하지 않았기 때문에

브라우저에는 수정 전의 정보가 여전히 남는 문제가 생긴다.

 

새로 로그인을 해야 수정된 정보로 나타나게 되는데

그러한 번거러움 없이 세션값을 변경하면 수정 후 정보가 바로 반영된다.

 

 

 

세션값 변경을 적용하기에 앞서 SecurityConfig 클래스 내부에 메소드를 생성한다. 

@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
public class SecurityConfig {

    @Bean
    public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration) throws Exception {
        return authenticationConfiguration.getAuthenticationManager();
    }

 

 

 

그리고 수정하는 메소드 안에 아래 코드를 적는다.

필자는 MemerController 클래스에 update 메소드 안에 적용하였다.

Authentication authentication = authenticationManager.authenticate
        (new UsernamePasswordAuthenticationToken(principal.getName(), memberUpdateForm.getPassword1()));

SecurityContextHolder.getContext().setAuthentication(authentication);

 

 

 

Spring Security에서의 세션값 변경 과정은 다음과 같다.

 

1. 사용자가 로그인 정보, 인증을 요청하면

2. AuthenticationFilter를 통해 UsernamePasswordAuthentication Token을 만든다.

3. ProviderManger에게 Token을 전달한다.

4. AuthenticationManger는 등록된 AuthenticationProvider에게 인증을 요구한다.

5. UserDetailsService에 사용자 정보를 전달한다.

6. User 객체를 만든다.

7. AthenticationProvider는 User를 전달받고 사용자 정보를 비교한다.

8. 인증이 완료되면 Authentication 객체를 반환한다.

9. AuthenticationFilter에 Authentication 객체가 반환된다.

10. Authenticaton 객체를 SecurityContext에 저장한다.

SecurityContextHolder.getContext().setAuthentication(authentication);

 

 

세션 영역에는 SecurityContext가 있다.

SecurityContext안에 Authentication 객체를 저장함으로써 

세션값이 변경된다.

 

 

참고로 비밀번호를 쿠키가 아닌 세션에 저장하는 이유는

세션이 보안상으로 더 좋기 때문이다.

세션은 서버에서 연결 정보로 관리한다.

 

 

 

 

참고 블로그

https://dev-coco.tistory.com/174

 

Spring Security의 구조(Architecture) 및 처리 과정 알아보기

시작하기 앞서 스프링 시큐리티에서 어플리케이션 보안을 구성하는 두 가지 영역에 대해 간단히 알아보자. 인증(Authentication)과 인가(Authorization) 대부분의 시스템에서는 회원을 관리하고 있고,

dev-coco.tistory.com

 

'Spring > Security' 카테고리의 다른 글

[Security] 보안 취약점 CSRF 해결  (0) 2024.09.06
Spring Security 로그인 문제  (0) 2022.11.20

댓글


반응형
반응형