Skip to content

Commit 59faf83

Browse files
committed
feat: CustomAuthenticationFilter 구현
- 로그인 요청 시 호출되는 필터 - authenticationManager.authenticate()를 통해 내부적으로 인증 진행 - 인증 성공, 실패 처리 메소드 구현
1 parent 8348f7f commit 59faf83

File tree

1 file changed

+67
-0
lines changed

1 file changed

+67
-0
lines changed
Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
package dmu.dasom.api.global.auth.filter;
2+
3+
import com.fasterxml.jackson.databind.ObjectMapper;
4+
import dmu.dasom.api.domain.common.exception.ErrorCode;
5+
import dmu.dasom.api.domain.common.exception.ErrorResponse;
6+
import dmu.dasom.api.global.auth.dto.LoginRequestDto;
7+
import dmu.dasom.api.global.auth.dto.TokenBox;
8+
import dmu.dasom.api.global.auth.jwt.JwtUtil;
9+
import jakarta.servlet.FilterChain;
10+
import jakarta.servlet.http.HttpServletRequest;
11+
import jakarta.servlet.http.HttpServletResponse;
12+
import lombok.RequiredArgsConstructor;
13+
import org.springframework.http.HttpStatus;
14+
import org.springframework.http.MediaType;
15+
import org.springframework.security.authentication.AuthenticationManager;
16+
import org.springframework.security.authentication.InternalAuthenticationServiceException;
17+
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
18+
import org.springframework.security.core.Authentication;
19+
import org.springframework.security.core.AuthenticationException;
20+
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
21+
22+
import java.io.IOException;
23+
24+
@RequiredArgsConstructor
25+
public class CustomAuthenticationFilter extends UsernamePasswordAuthenticationFilter {
26+
27+
private final AuthenticationManager authenticationManager;
28+
private final JwtUtil jwtUtil;
29+
30+
@Override
31+
public Authentication attemptAuthentication(final HttpServletRequest request, final HttpServletResponse response) throws AuthenticationException {
32+
try {
33+
final ObjectMapper objectMapper = new ObjectMapper();
34+
35+
// 로그인 요청 정보를 파싱
36+
final LoginRequestDto loginRequestDto = objectMapper.readValue(request.getInputStream(), LoginRequestDto.class);
37+
38+
// 로그인 요청 정보로 인증 시도
39+
return authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(loginRequestDto.getEmail(), loginRequestDto.getPassword()));
40+
} catch (InternalAuthenticationServiceException | IOException e) { // 인증 과정에서 내부 오류 발생 시 (ex. 사용자 정보 없음)
41+
throw new AuthenticationException("Authentication Failed.", e) {};
42+
}
43+
}
44+
45+
@Override
46+
protected void successfulAuthentication(final HttpServletRequest request, final HttpServletResponse response, final FilterChain chain, final Authentication authResult) {
47+
// 기존 토큰 만료 처리
48+
jwtUtil.blacklistTokens(authResult.getName());
49+
50+
// 토큰 생성
51+
final TokenBox tokenBox = jwtUtil.generateTokenBox(authResult.getName());
52+
53+
response.setStatus(HttpStatus.OK.value());
54+
response.setHeader("Access-Token", tokenBox.getAccessToken());
55+
response.setHeader("Refresh-Token", tokenBox.getRefreshToken());
56+
}
57+
58+
@Override
59+
protected void unsuccessfulAuthentication(final HttpServletRequest request, final HttpServletResponse response, final AuthenticationException failed) throws IOException {
60+
// 로그인 실패 응답
61+
response.setStatus(HttpStatus.BAD_REQUEST.value());
62+
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
63+
response.setCharacterEncoding("UTF-8");
64+
response.getWriter().write(new ObjectMapper().writeValueAsString(new ErrorResponse(ErrorCode.LOGIN_FAILED)));
65+
}
66+
67+
}

0 commit comments

Comments
 (0)