Spring Security와 인증 방식
Spring Security 개요
- Spring Security는 애플리케이션의 인증 및 권한 관리를 담당하는 프레임워크.
비유
- Spring Security → 은행의 보안 시스템 (가드)
- CustomUserDetailService → 방문자 명부를 관리하는 직원
- CustomAuthenticationFilter → 특정 VIP 고객만 입장할 수 있도록 하는 직원
CustomUserDetailService
Spring Security가 제공하는 UserDetailsService 인터페이스를 구현하여, 사용자 정보를 데이터베이스에서 가져오는 역할 수행.
역할
- 사용자 이름(username)을 기반으로 데이터베이스에서 사용자 정보를 조회.
- 조회한 정보를 Spring Security가 이해할 수 있는 UserDetails 객체로 변환하여 반환.
코드 예제
@Service
@RequiredArgsConstructor
public class CustomUserDetailService implements UserDetailsService {
private final MemberRepository memberRepository;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
Member member = memberRepository.findByUsername(username)
.orElseThrow(() -> new UsernameNotFoundException("사용자를 찾을 수 없습니다."));
return new User(member.getUsername(), member.getPassword(), List.of());
}
}
CustomAuthenticationFilter
Security의 기본 인증 과정과 다르게 사용자 지정 로직을 추가할 수 있도록 함.
역할
- 기존 Security의 인증 프로세스를 다른 방식으로 처리하거나, 추가적인 보안 로직을 적용.
- 필터 체인 내에서 실행되며, 원하는 작업 수행 후 다음 필터로 요청 전달.
코드 예제
@Component
public class CustomAuthenticationFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
System.out.println("Custom Authentication Filter Activated");
filterChain.doFilter(request, response);
}
}
인증 방식
1. ID/PW 방식
- 아이디와 비밀번호를 전송하여 인증.
- 문제점: 개인정보 노출 위험.
2. API Key 방식
- 무작위 API Key를 사용하여 인증.
- 문제점:
- API Key를 기반으로 사용자 조회 → DB 부하 증가.
- 캐시(Cache) 방식을 도입하여 DB 사용 감소 가능.
- 하지만 여전히 서버 부담이 큼.
3. JWT(Json Web Token) 방식
- 인증된 사용자가 받은 토큰을 활용하여 추가 인증 없이 요청 가능.
- 문제점:
- 유효기간이 무제한이면 보안 위험 증가 (도난, 탈취 가능성).
- 해결책: 유효기간이 있는 토큰을 발급.
- 변조 방지: 시크릿 키(Secret Key)로 서명.
JWT 직렬화/역직렬화 예제
JWT 직렬화
public static String createToken(Key secretKey, int expireSeconds, Map<String, Object> claims) {
Date issuedAt = new Date();
Date expiration = new Date(issuedAt.getTime() + 1000L * expireSeconds);
return Jwts.builder()
.claims(claims)
.issuedAt(issuedAt)
.expiration(expiration)
.signWith(secretKey)
.compact();
}
JWT 역직렬화
Jwts.parser()
.verifyWith(secretKey)
.build()
.parse(jwtStr);
'TIL' 카테고리의 다른 글
250212 수 TIL (0) | 2025.02.12 |
---|---|
250210 월 TIL (0) | 2025.02.10 |
250206 수 TIL (0) | 2025.02.06 |
250205 수 TIL (0) | 2025.02.05 |
250204 화 TIL (0) | 2025.02.04 |