|
| 1 | +package com.ajou.hertz.common.auth; |
| 2 | + |
| 3 | +import java.io.IOException; |
| 4 | + |
| 5 | +import org.springframework.http.HttpHeaders; |
| 6 | +import org.springframework.security.core.Authentication; |
| 7 | +import org.springframework.security.core.context.SecurityContextHolder; |
| 8 | +import org.springframework.stereotype.Component; |
| 9 | +import org.springframework.util.StringUtils; |
| 10 | +import org.springframework.web.filter.OncePerRequestFilter; |
| 11 | + |
| 12 | +import jakarta.servlet.FilterChain; |
| 13 | +import jakarta.servlet.ServletException; |
| 14 | +import jakarta.servlet.http.HttpServletRequest; |
| 15 | +import jakarta.servlet.http.HttpServletResponse; |
| 16 | +import lombok.RequiredArgsConstructor; |
| 17 | + |
| 18 | +@RequiredArgsConstructor |
| 19 | +@Component |
| 20 | +public class JwtAuthenticationFilter extends OncePerRequestFilter { |
| 21 | + |
| 22 | + private static final String TOKEN_TYPE_BEARER_PREFIX = "Bearer "; |
| 23 | + |
| 24 | + private final JwtTokenProvider jwtTokenProvider; |
| 25 | + |
| 26 | + /** |
| 27 | + * 모든 요청마다 작동하여, jwt access token을 확인한다. |
| 28 | + * 유효한 token이 있는 경우 token을 parsing해서 사용자 정보를 읽고 SecurityContext에 사용자 정보를 저장한다. |
| 29 | + * |
| 30 | + * @param request request 객체 |
| 31 | + * @param response response 객체 |
| 32 | + * @param filterChain FilterChain 객체 |
| 33 | + */ |
| 34 | + @Override |
| 35 | + protected void doFilterInternal( |
| 36 | + HttpServletRequest request, |
| 37 | + HttpServletResponse response, |
| 38 | + FilterChain filterChain |
| 39 | + ) throws ServletException, IOException { |
| 40 | + String accessToken = getAccessToken(request); |
| 41 | + |
| 42 | + if (StringUtils.hasText(accessToken)) { |
| 43 | + try { |
| 44 | + jwtTokenProvider.validateToken(accessToken); |
| 45 | + Authentication authentication = jwtTokenProvider.getAuthentication(accessToken); |
| 46 | + SecurityContextHolder.getContext().setAuthentication(authentication); |
| 47 | + } catch (Exception ignored) { |
| 48 | + // 인증 권한 설정 중 에러가 발생하면 권한을 부여하지 않고 다음 단계로 진행 |
| 49 | + } |
| 50 | + } |
| 51 | + filterChain.doFilter(request, response); |
| 52 | + } |
| 53 | + |
| 54 | + /** |
| 55 | + * Request의 header에서 token을 읽어온다. |
| 56 | + * |
| 57 | + * @param request Request 객체 |
| 58 | + * @return Header에서 추출한 token |
| 59 | + */ |
| 60 | + public String getAccessToken(HttpServletRequest request) { |
| 61 | + String authorizationHeader = request.getHeader(HttpHeaders.AUTHORIZATION); |
| 62 | + if (authorizationHeader == null || !authorizationHeader.startsWith(TOKEN_TYPE_BEARER_PREFIX)) { |
| 63 | + return null; |
| 64 | + } |
| 65 | + return authorizationHeader.substring(TOKEN_TYPE_BEARER_PREFIX.length()); |
| 66 | + } |
| 67 | +} |
0 commit comments