LoginFilter 구현
public class LoginFilter extends UsernamePasswordAuthenticationFilter {
private final AuthenticationManager authenticationManager;
public LoginFilter(AuthenticationManager authenticationManager) {
this.authenticationManager = authenticationManager;
}
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
String username = obtainUsername(request);
String password = obtainPassword(request);
System.out.println(username);
UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(username, password, null);
return authenticationManager.authenticate(authToken);
}
@Override
protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authentication) {
}
@Override
protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException failed) {
}
}
LoginFilter?
- LoginFilter는 사용자 인증을 처리하는 필터
- 사용자가 아이디와 비밀번호를 입력하면 이를 검증하고, 검증이 성공하면 JWT 토큰을 발급하는 역할!
- 흐름 요약
1. 사용자가 로그인 요청을 보내면 LoginFilter가 이를 가로챈다
2. LoginFilter는 아이디와 비밀번호를 AuthenticationManager에 전달하여 인증을 시도한다.
3. 인증이 성공하면 successful 메서드에서 JWT토큰을 생성하고, 클라이언트에 반환할 수 있다.
4. 인증 실패하면 unsuccessfil 메서드에서 실패 메시지를 처리할 수 있다.
SecurityConfig에 LoginFilter 등록
http
.addFilterAt(new LoginFilter(authenticationManager(authenticationConfiguration)), UsernamePasswordAuthenticationFilter.class);