BackEnd/SpringBoot

[Spring Security] - SpringSecurity+Jwt 로그인 과정

영지는 달리는중 2020. 10. 10. 23:37

스프링에서 제공하는 폼 로그인을 사용하는 경우 

1. 로그인 

2 UsernamePasswordAuthenticationFilter 에서 UserDetailService를 사용한 인증 후 Authentication 객체를 SpringSecurityHolder에 저장

3. 순차적으로 필터를 거친 후 마지막 필터인 FilterSecurityInterceptor에서 권한 인가 여부 결정 후 리다이렉트

 

하지만 JWT를 사용하는 경우 JWT를 가져와 인증하는 필터를 커스터마이징 하여야 한다 

1. 로그인

2. JwtAuthenticationFilter에서 토큰 추출 & 토큰 유효성 검사 & UserDetailService를 사용한 인증 후 Authentication 객체를 SpringSecurityHolder에 저장

3. 순차적으로 필터를 거친 후 마지막 필터인 FilterSecurityInterceptor에서 권한 인가 여부 결정 후 리다이렉트

 

나의 경우에는 JwtAuthenticationFilter라는 이름의 필터를 생성하여 JWT 유효성 체크 후 Authentication 객체를 SpringSecurityHolder에 저장하는 코드를 작성하였다 

@RequiredArgsConstructor
public class JwtAuthenticationFilter extends GenericFilterBean {

    private final JwtProvider jwtProvider;

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        String token = jwtProvider.resolveToken((HttpServletRequest) request);
        if(token != null && jwtProvider.validateToken(token)){
            Authentication auth = jwtProvider.getAuthentication(token);
            SecurityContextHolder.getContext().setAuthentication(auth);
        }
        chain.doFilter(request,response);
    }
}

그리고 생성한 필터를 UsernamePasswordAuthenticationFilter 앞에 설정하여 주면 끝

 

UsernamePasswordAuthenticationFilter
  • 폼 인증을 처리하는 시큐리티 필터

  • 인증된 Authentication 객체를 SecurityContextHolder에 넣어주는 필터

  • SecurityContextHolder.getContext().setAuthentication(authentication)

JwtAuthenticationFilter
  • JWT 인증을 처리하는 시큐리티 필터

  • 인증된 Authentication 객체를 SecurityContextHolder에 넣어주는 필터

  • SecurityContextHolder.getContext().setAuthentication(authentication)

 

동작흐름이 헷갈려서 정리할 겸 끄적여봤당

공부하면 할수록 어려운 싴휴리티 ,,,