좋아! 😎
지금부터 Spring Boot + Spring Security로 아래 4가지 핵심 기능을 단계별로 정리해줄게:
| 기능 번호 | 구현 항목 |
|---|---|
| 1️⃣ | DB 기반 회원가입 & 로그인 |
| 2️⃣ | Redis 세션 저장 방식 적용 |
| 3️⃣ | 로그인 실패 메시지 처리 |
| 4️⃣ | 로그인 상태 확인 (세션에서 사용자 이름 가져오기) |
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
@Entity
public class User {
@Id
private String username;
private String password;
private String role;
}
public interface UserRepository extends JpaRepository<User, String> {
}
@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();
}
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@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";
}
implementation 'org.springframework.session:spring-session-data-redis'
implementation 'org.springframework.boot:spring-boot-starter-data-redis'
spring:
redis:
host: localhost
port: 6379
session:
store-type: redis
timeout: 30m
➕ Redis 서버는 따로 켜줘야 함 (
redis-server명령어 또는 Docker)
<div th:if="${param.error}">
<p style="color:red;">로그인 실패! 아이디 또는 비밀번호를 확인하세요.</p>
</div>
/login?error=true→param.error로 화면에 표시 가능
@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() |
필요하다면:
까지 가능해!
혹시 지금 진행 중인 프로젝트에 맞춰 커스터마이징해줄까? 🤗