그렇지! 👍
"로그인 + 로그아웃 기능"은 어떤 인증 방식이든 기본 중의 기본,
특히 Spring Security 기반 세션 인증은 배우기 가장 좋은 첫걸음이야.
지금부터 완전 핵심 흐름이랑 코드 예시까지 쫙 보여줄게!
[1] 로그인 요청 (POST /login)
↓
[2] Spring Security가 ID/PW 인증
↓
[3] 인증 성공 시 → 세션 생성 + 인증 객체 저장
↓
[4] 이후 요청마다 → 세션 쿠키로 인증 유지
↓
[5] 로그아웃 요청 (POST /logout)
↓
[6] 세션 무효화 + 쿠키 삭제
implementation 'org.springframework.boot:spring-boot-starter-security'
implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
implementation 'org.springframework.boot:spring-boot-starter-web'
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable() // 개발단계에서만 비활성화
.authorizeRequests()
.antMatchers("/login", "/").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.defaultSuccessUrl("/home", true)
.and()
.logout()
.logoutUrl("/logout")
.logoutSuccessUrl("/login?logout")
.invalidateHttpSession(true) // 세션 무효화
.deleteCookies("JSESSIONID"); // 쿠키 삭제
}
}
@Service
public class CustomUserDetailsService implements UserDetailsService {
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
// 실제 DB에서 유저 찾기 생략
if (!username.equals("test")) {
throw new UsernameNotFoundException("User not found");
}
return User.builder()
.username("test")
.password("{noop}1234") // 비밀번호 암호화 안 함 (연습용)
.roles("USER")
.build();
}
}
@Controller
public class HomeController {
@GetMapping("/")
public String index() {
return "index"; // 로그인 페이지
}
@GetMapping("/home")
public String home() {
return "home"; // 로그인 성공 시 이동
}
@GetMapping("/login")
public String loginPage() {
return "login"; // 커스텀 로그인 폼
}
}
<form th:action="@{/login}" method="post">
<input type="text" name="username" placeholder="아이디">
<input type="password" name="password" placeholder="비밀번호">
<button type="submit">로그인</button>
</form>
<form th:action="@{/logout}" method="post">
<button type="submit">로그아웃</button>
</form>
또는 버튼 하나로 처리하고 싶다면 자바스크립트로 POST 요청을 보내면 돼.
| 기능 | 구현 방식 |
|---|---|
| ✅ 로그인 | Spring Security + formLogin |
| ✅ 인증 상태 유지 | 세션 (서버 메모리 or Redis 등) |
| ✅ 로그아웃 | POST /logout 요청 + 세션 삭제 |
👉 YES!
Spring Security 커스터마이징, DB 연동 로그인, 소셜 로그인, 토큰 인증 다 이해하기 쉬워져다음 단계로:
이런 것도 해볼 수 있어!
지금 이 코드로 실습해보고 싶어? 아니면 DB연동 버전으로 확장해볼까? 🛠️