Spring Boot + Spring Security로 아래 4가지 핵심 기능

moon.kick·2025년 4월 18일

좋아! 😎
지금부터 Spring Boot + Spring Security로 아래 4가지 핵심 기능을 단계별로 정리해줄게:


✅ 전체 목표 기능

기능 번호구현 항목
1️⃣DB 기반 회원가입 & 로그인
2️⃣Redis 세션 저장 방식 적용
3️⃣로그인 실패 메시지 처리
4️⃣로그인 상태 확인 (세션에서 사용자 이름 가져오기)

🔨 프로젝트 구조 예시 (Spring Boot 기반)

src/
 └── main/
     ├── java/
     │   └── com.example.securitydemo/
     │       ├── config/             ← Security 설정
     │       ├── controller/         ← 로그인/홈 컨트롤러
     │       ├── entity/             ← User 엔티티
     │       ├── repository/         ← JPA Repository
     │       ├── service/            ← UserDetailsService 구현
     │       └── SecurityDemoApplication.java
     └── resources/
         ├── templates/
         │   ├── login.html
         │   └── home.html
         └── application.yml

1️⃣ DB 기반 회원가입 & 로그인

📦 Entity

@Entity
public class User {

    @Id
    private String username;

    private String password;

    private String role;
}

🗃️ Repository

public interface UserRepository extends JpaRepository<User, String> {
}

🔐 UserDetailsService 구현

@Service
public class CustomUserDetailsService implements UserDetailsService {

    @Autowired
    private UserRepository userRepository;

    @Override
    public UserDetails loadUserByUsername(String username) {
        User user = userRepository.findById(username).orElseThrow();
        return org.springframework.security.core.userdetails.User.builder()
                .username(user.getUsername())
                .password(user.getPassword()) // 암호화 필요
                .roles(user.getRole())
                .build();
    }
}

🔧 PasswordEncoder 등록

@Bean
public PasswordEncoder passwordEncoder() {
    return new BCryptPasswordEncoder();
}

🔐 SecurityConfig

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.csrf().disable()
        .authorizeRequests()
            .antMatchers("/register", "/login").permitAll()
            .anyRequest().authenticated()
        .and()
            .formLogin()
            .loginPage("/login")
            .defaultSuccessUrl("/home", true)
            .failureUrl("/login?error=true")
        .and()
            .logout()
            .logoutSuccessUrl("/login?logout");
}

📝 회원가입 컨트롤러

@PostMapping("/register")
public String register(User user) {
    user.setPassword(passwordEncoder.encode(user.getPassword()));
    userRepository.save(user);
    return "redirect:/login";
}

2️⃣ Redis 세션 저장 방식

📦 Gradle 의존성

implementation 'org.springframework.session:spring-session-data-redis'
implementation 'org.springframework.boot:spring-boot-starter-data-redis'

⚙️ application.yml

spring:
  redis:
    host: localhost
    port: 6379

  session:
    store-type: redis
    timeout: 30m

➕ Redis 서버는 따로 켜줘야 함 (redis-server 명령어 또는 Docker)


3️⃣ 로그인 실패 메시지 처리

🔄 login.html에서 메시지 받기

<div th:if="${param.error}">
  <p style="color:red;">로그인 실패! 아이디 또는 비밀번호를 확인하세요.</p>
</div>

/login?error=trueparam.error로 화면에 표시 가능


4️⃣ 세션에서 사용자 이름 가져오기

👀 SecurityContext에서 세션 사용자 가져오기

@GetMapping("/home")
public String home(Model model, Authentication authentication) {
    String username = authentication.getName(); // 세션 유저명
    model.addAttribute("username", username);
    return "home";
}

📝 마무리 요약

기능구현 방식
✅ DB 로그인UserDetailsService + JPA
✅ 세션 저장소Redis 적용 + spring.session.store-type: redis
✅ 실패 메시지/login?error=true + Thymeleaf 조건
✅ 로그인 상태 확인Authentication.getName() 또는 Principal.getName()

필요하다면:

  • 코드 전체 ZIP 형태로 정리
  • React 프론트엔드 연동 확장 (SPA 인증 흐름)
  • Redis 블랙리스트 + JWT로 확장

까지 가능해!
혹시 지금 진행 중인 프로젝트에 맞춰 커스터마이징해줄까? 🤗

profile
@mgkick

0개의 댓글