Spring 코드
LoginCustomAuthenticationFilter 작성
•로그인 인증 필터를 위해 LoginCustomAuthenticationFilter 작성
(WebSecurityConfig 쪽에서 로그인 필터 내용 제거해도 됨)
package com.kosta.config;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.kosta.domain.LoginRequest;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import java.io.IOException;
@Slf4j
public class LoginCustomAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
private static final AntPathRequestMatcher LOGIN_PATH = new AntPathRequestMatcher("/api/auth/login", "POST");
protected LoginCustomAuthenticationFilter(AuthenticationManager authenticationManager) {
super(LOGIN_PATH);
setAuthenticationManager(authenticationManager);
}
@Override
public Authentication attemptAuthentication(
HttpServletRequest request, HttpServletResponse response) throws AuthenticationException,
IOException, ServletException {
// POST, /api/auth/login 에 요청이 들어오면 진행되는 곳
LoginRequest loginRequest = null;
// 1. Body에 있는 로그인 정보 ("email": "~~", password: "~~")
try {
log.info("[attemptAuthentication] 로그인 정보 가져오기");
ObjectMapper objectMapper = new ObjectMapper();
loginRequest = objectMapper.readValue(request.getInputStream(), LoginRequest.class);
} catch (IOException e) {
throw new RuntimeException("로그인 요청 파라미터 이름 확인 필요 (로그인 불가)");
}
// 2. email과 password를 기반으로 AuthenticationToken 생성!
log.info("[attemptAuthentication] AuthenticationToken 생성");
UsernamePasswordAuthenticationToken uPAT = new UsernamePasswordAuthenticationToken(
loginRequest.getEmail(), loginRequest.getPassword());
// 3. 인증 시작 (AuthenticationManager의 authenticate 메소드가 동작할 때 -> loadUserByUsername 동작)
log.info("[attemptAuthentication] 인증 시작");
Authentication authenticate = getAuthenticationManager().authenticate(uPAT);
return authenticate;
}
@Override
protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response,
FilterChain chain, Authentication authResult)
throws IOException, ServletException {
log.info("로그인 정상적으로 성공함");
super.successfulAuthentication(request, response, chain, authResult);
}
}