Spring Security와 로그인

hee·2026년 5월 18일

Spring

목록 보기
5/5

로그인의 시작

사용자가 로그인하면:

  • 일반 로그인: username + password를 검증
  • OAuth 로그인: 외부 서비스에서 받은 토큰 검증

로그인이 성공하면 Spring Security가 사용자 정보를 세션이나 JWT 등에 저장함.


Spring Security가 인증 정보를 관리하는 방식

Spring Security에는 SecurityContext라는 공간이 있음. 여기서 인증된 사용자 정보(Authentication)를 저장.

예를 들어, 로그인 후엔 다음 구조과 같은 구조가 생김.

SecurityContext
   └── Authentication
          ├── principal-> UserDetails 객체 (사용자 ID, 권한 등)
          ├── credentials-> 비밀번호 등 (보통 null)
          ├── authorities-> 권한 목록
  • principal현재 로그인한 사용자 정보
  • Spring MVC 컨트롤러에서 쉽게 가져오기 가능

컨트롤러에서 로그인 사용자 확인하기

@GetMapping("/me")public StringgetMyInfo(Authentication authentication) {UserDetailsuserDetails= (UserDetails) authentication.getPrincipal();
    System.out.println("현재 로그인한 사용자 ID: " + userDetails.getUsername());return"ok";
}

또는 더 간단하게:

@GetMapping("/me")public StringgetMyInfo(@AuthenticationPrincipal UserDetails userDetails) {
    System.out.println("현재 로그인한 사용자 ID: " + userDetails.getUsername());return"ok";
}

즉, 아이디 변경 API, 비밀번호 변경 API 등에서는 요청을 보낸 사람이 누구인지 Authentication이나 @AuthenticationPrincipal로 확인 가능.


JWT를 사용하는 경우

로그인 후 JWT를 발급하면:

  • 요청 시 HTTP Header에 Authorization: Bearer <토큰> 추가
  • Spring Security Filter가 토큰을 검증하고, 유효하면 SecurityContext에 사용자 정보 저장

결과적으로 JWT 방식이든 세션 방식이든, 컨트롤러에서는 항상 Authentication에서 로그인 사용자 정보를 꺼낼 수 있음.


아이디/비밀번호 변경 시 체크

API 예시:

@PutMapping("/user/username")public ResponseEntity<?> changeUsername(@RequestBody ChangeUsernameRequest req,@AuthenticationPrincipal UserDetails userDetails) {
    userService.changeUsername(userDetails.getUsername(), req.getNewUsername());return ResponseEntity.ok().build();
}
  • 여기서 중요한 점: 클라이언트가 전달한 사용자 ID를 사용하지 않고, SecurityContext에서 가져온 로그인 사용자 ID를 사용
  • 안 그러면 다른 사람의 ID를 바꿀 수도 있음 → 보안 취약점

정리하면:

  1. 로그인 성공 → SecurityContext에 사용자 정보 저장
  2. 요청 시 Spring Security가 SecurityContext에서 사용자 정보 확인
  3. 컨트롤러에서 Authentication 또는 @AuthenticationPrincipal로 로그인 사용자 확인
  4. 이 정보로만 아이디/비밀번호 변경 등 민감한 작업 수행

0개의 댓글