Post

Jwt 정리

Jwt 정리

JWT 정리

JWT는 여러 곳에서 활용할 수 있다.

나는 http security와 websocket interceptor에서 활용했다.

websocket은 해당 글 에서 로직을 확인할 수 있다.

아래는 내가 작성했던 코드는 아니고 어떤식으로 작성한다 정도로 작성한 것이니 참고용으로만 확인한다.

*내가 작성한 로직은 github 확인



Filter

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
@RequiredArgsConstructor
@Slf4j
public class JwtAuthenticationFilter extends OncePerRequestFilter {
    private final JwtTokenProvider jwtTokenProvider;

    @Override // doFilter 대신 doFilterInternal 사용
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) 
            throws ServletException, IOException {
        
        // 1. 헤더에서 토큰 추출
        String token = resolveToken(request);

        // 2. 토큰이 유효한지 검사
        if (token != null && jwtTokenProvider.validateToken(token)) {
            // 3. 인증 정보 생성  등록
            Authentication authentication = jwtTokenProvider.getAuthentication(token);
            SecurityContextHolder.getContext().setAuthentication(authentication);
        }
        
        filterChain.doFilter(request, response);
    }

    private String resolveToken(HttpServletRequest request) {
        String bearerToken = request.getHeader("Authorization");
        if (StringUtils.hasText(bearerToken) && bearerToken.startsWith("Bearer ")) {
            return bearerToken.substring(7);
        }
        return null;
    }
}

한 번의 요청당 한 번만 실행




config 등록

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
@Configuration
@EnableWebSecurity
public class SecurityConfig {

    private final JwtTokenProvider jwtTokenProvider;

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http 
            .httpBasic().disable() // UI 사용X
            .csrf().disable()      // JWT를 사용하므로 CSRF 보호 불필요
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) // 세션 사용X
            .and()
            .authorizeRequests()
            .antMatchers("/api/login", "/api/signup").permitAll() // 로그인, 회원가입은 통과
            .anyRequest().authenticated() // 나머지는 무조건 토큰 있어야 
            .and()
            // UsernamePasswordAuthenticationFilter(기본 로그인필터) 전에 JWT 필터를 실행
            .addFilterBefore(new JwtAuthenticationFilter(jwtTokenProvider), UsernamePasswordAuthenticationFilter.class);

        return http.build();
    }
}




JwtTokenProvider

1
2
3
4
5
6
public Authentication getAuthentication(String token) {
    // 토큰에서 유저 정보를 꺼냄
    User user = this.getUserFromToken(token); 
    // 스프링 시큐리티 전용 인증 토큰 반환
    return new UsernamePasswordAuthenticationToken(user, "", user.getAuthorities());
}
This post is licensed under CC BY 4.0 by the author.

© haedal-uni. Some rights reserved.

Using the Chirpy theme for Jekyll.