AI딥러닝/SporingBoot

Spring Security를 활용한 로그인 및 로그아웃 구현

Ystory96 2026. 1. 6. 12:15

[Spring Boot] Spring Security 로그인/로그아웃 가이드

 

1. 세팅하기 https://spring.io/

 

Spring | Home

Cloud Your code, any cloud—we’ve got you covered. Connect and scale your services, whatever your platform.

spring.io

 

 

2. 프로젝트 설정(build.gradle)

보안 라이브러리와 타임리프 시큐리티 확장팩 추가

Gradle
dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-security'
    implementation 'org.thymeleaf.extras:thymeleaf-extras-springsecurity6'
}

 

 

3. 핵심 로직 구현하기(Backend)

① SecurityConfig: 보안 정책 설정

어떤 페이지를 허용할지, 로그인/로그아웃 경로는 어디인지 정의합니다.

  • 암호화 빈(Bean) 등록: BCryptPasswordEncoder를 사용하여 비밀번호를 해시화합니다.
  • CSRF 비활성화: 테스트를 위해 POST 요청 차단을 해제합니다.
  • 로그인 파라미터: id와 pw라는 사용자 정의 파라미터를 사용하도록 설정합니다.

② MemberUserDetailsService: 사용자 조회

사용자가 입력한 아이디를 DB(mem0105 테이블)에서 찾아 시큐리티 전용 객체로 변환합니다.

  • loadUserByUsername: 아이디를 통해 사용자를 찾고, 'USER' 권한을 부여합니다.

③ MemberServiceImp: 비밀번호 암호화 저장

회원가입 시 입력받은 평문 비밀번호를 반드시 암호화하여 DB에 저장해야 합니다.

Java
 
// 비밀번호 암호화 로직 예시
memberDTO.setPw(bCryptPasswordEncoder.encode(memberDTO.getPw())); // 암호화
memberRepository.save(memberDTO.toEntity()); // DB 저장

 

 

4. 화면 구현 (Frontend)

① 로그인 폼 (login.html)

시큐리티 설정과 action, name 속성을 정확히 일치시켜야 합니다.

  • th:action="@{/loginProcess}"
  • name="id", name="pw"

② 메뉴 상태 제어 (top.html)

sec:authorize 속성을 사용하여 로그인 상태에 따라 메뉴를 동적으로 보여줍니다.

  • isAnonymous(): 로그인 전 메뉴 노출
  • isAuthenticated(): 로그인 후 사용자 이름(name) 및 로그아웃 버튼 노출

 

5. 정리

 

  • 세팅: build.gradle 의존성 추가
  • 설계: MemberEntity와 MemberDTO 만들기
  • 저장: MemberRepository와 MemberServiceImp(비밀번호 암호화)
  • 인증: 시큐리티의 심장 MemberUserDetailsService
  • 보안 설정: SecurityConfiguration 클래스
  • 화면 연결: MemberController와 Thymeleaf 파일들

끝.