java
CHAPTER 70 / 99
읽기 약 2분
FUNCTION
Spring Security: 인증과 권한 관리
핵심 개념
SecurityFilterChain·UserDetailsService·BCrypt·권한 체계 — 로그인+권한별 접근 제어.
본문
SecurityFilterChain 설정 (Spring Security 6+)
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.csrf(csrf -> csrf.disable())
.authorizeHttpRequests(auth -> auth
.requestMatchers("/", "/login", "/signup").permitAll()
.requestMatchers("/admin/**").hasRole("ADMIN")
.anyRequest().authenticated()
)
.formLogin(form -> form
.loginPage("/login")
.defaultSuccessUrl("/dashboard")
)
.logout(logout -> logout
.logoutSuccessUrl("/")
);
return http.build();
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder(12); // strength 12
}
}UserDetailsService
@Service
@RequiredArgsConstructor
public class CustomUserDetailsService implements UserDetailsService {
private final UserRepository userRepository;
@Override
public UserDetails loadUserByUsername(String username) {
User user = userRepository.findByUsername(username)
.orElseThrow(() -> new UsernameNotFoundException(username));
return org.springframework.security.core.userdetails.User.builder()
.username(user.getUsername())
.password(user.getPassword()) // BCrypt 해시
.roles(user.getRole().name())
.build();
}
}비밀번호 인코딩
@Service
@RequiredArgsConstructor
public class UserService {
private final UserRepository userRepository;
private final PasswordEncoder passwordEncoder;
public User signup(SignupDto dto) {
// 회원가입 시 해시
User user = User.builder()
.username(dto.username())
.password(passwordEncoder.encode(dto.password()))
.role(Role.USER)
.build();
return userRepository.save(user);
}
public boolean verify(String raw, String encoded) {
return passwordEncoder.matches(raw, encoded);
}
}@PreAuthorize 어노테이션
@RestController
@RequiredArgsConstructor
public class AdminController {
@PreAuthorize("hasRole('ADMIN')")
@GetMapping("/admin/users")
public List<UserDto> getAllUsers() {
return userService.findAll();
}
@PreAuthorize("hasRole('USER') or hasRole('ADMIN')")
@GetMapping("/profile")
public UserDto getProfile(Principal principal) {
return userService.findByUsername(principal.getName());
}
@PreAuthorize("@userService.isOwner(#userId, principal.username)")
@DeleteMapping("/users/{userId}")
public void deleteUser(@PathVariable Long userId) {
userService.delete(userId);
}
}CORS 설정
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.cors(cors -> cors.configurationSource(corsConfigurationSource()))
// ...
}
@Bean
CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration config = new CorsConfiguration();
config.setAllowedOrigins(List.of("https://openhyperstep.com"));
config.setAllowedMethods(List.of("GET", "POST", "PUT", "DELETE"));
config.setAllowedHeaders(List.of("*"));
config.setAllowCredentials(true);
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", config);
return source;
}다음 챕터
CH.2 "JWT 인증" — REST API의 표준 인증.
AI 프롬프트
🤖 AI에게 잘 물어보는 법 — 모델·전략별 프롬프트
Claude
무료: Sonnet 4.6 / Pro $20/mo: Opus 4.6
내 Spring 코드의 Spring Security 부분을 분석해서 취약점·강도 보완와 개선 우선순위를 알려줘.
ChatGPT
무료: GPT-5.5 / Plus $20/mo: GPT-5.5 Pro
Spring Security vs 다른 패턴 비교를 실전 사례 5개로 보여주고 BCrypt vs Argon2 트레이드오프를 알려줘.
Gemini
무료: 2.5 Flash / Pro $19.99/mo: 3.1 Pro
내 코드베이스 전체를 분석해서 Spring Security 관련 인증 위반 위치 + CSP/CORS 누락를 보고해줘.
Grok
무료: Grok 4.1 / SuperGrok $30/mo
2026년 한국 기업의 Spring Security 채택률과 한국 핀테크 인증 패턴를 솔직히 알려줘.
⭐ 이것만 기억하세요
Spring Security: 인증과 권한 관리는 이 3가지만 확실히 잡으세요
1.Spring Security 6은 람다 DSL — SecurityFilterChain 빈으로 모든 보안 정책 정의
2.BCrypt strength 10~12 권장 — 너무 높으면 응답 지연, 낮으면 무차별 공격 취약
3.다음 챕터 CH.2에서 JWT — 세션 없는 API 인증
공유하기
진행도 70 / 99