카테고리 없음
                
              스프링 시큐리티
                YoshiaLee
                 2024. 8. 2. 14:12
              
                          
            
스프링 시큐리티에서 JWT를 통한 인증은 가장먼저 JwtTokenFilter에서 JWT를 추출하고 SecurityContextHolder에 현재 접속한 사용자가 누구인지 담아 놓는다. 따라서 이 필터를 통과하게 된다면 인증이 성공한것이고 추가로 CustomUserDetails를 통해 접속한 사용자에 대한 커스텀한 데이터를 바로 컨트롤러단이나 서비스단에서 사용할수 있게 되는것이다.
doFilterInternal 메서드
try{
            if(StringUtils.hasText(jwt) && tokenProvider.validateToken(jwt)){
                SecurityContext context = SecurityContextHolder.createEmptyContext();
                Claims jwtClaims = tokenProvider.parseClaims(jwt);
                String uuid = jwtClaims.getSubject();
                String authorities = jwtClaims.get("roles", String.class);
                log.info("uuid :" + uuid);
                CustomUserDetails customUserDetails = CustomUserDetails.builder()
                        .uuid(uuid)
                        .authorities(authorities)
                        .build();
                UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
                        customUserDetails,
                        jwt,
                        customUserDetails.getAuthorities()
                );
                context.setAuthentication(authentication);
                SecurityContextHolder.setContext(context);
                logger.debug("Security Context에 '{}' 인증 정보를 저장했습니다, uri: {}", customUserDetails.getUuid() ,requestURI);
            }
            else
                logger.debug("유효한 JWT 토큰이 없습니다, uri: {}",requestURI);
            // 생성한 필터 실행
            filterChain.doFilter(httpServletRequest,response);
        }catch (ExpiredJwtException e){
            //토큰의 유효기간 만료
            setErrorResponse(request, response, ErrorType.JWT_TOKEN_TIME_OUT);
        }//기타 오류는 핸들러에서 처리
        /*
        catch (JwtException | IllegalArgumentException e){
            //유효하지 않은 토큰
            setErrorResponse(response, ErrorCode.INVALID_TOKEN);
        }
         */
    }
JWT -> CustomeUserDetails 추출 과정
