티스토리 뷰

☠️ Java

Filter

James Wetzel 2024. 11. 26. 15:53
728x90
반응형

OncePerRequestFilter

HTTP 요청당 한 번만 실행되는 필터를 작성할 수 있도록 도와줍니다. 

import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class JwtAuthenticationFilter extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain filterChain) throws ServletException, IOException {
        String token = request.getHeader("Authorization");

        if (token != null && token.startsWith("Bearer ")) {
            String jwt = token.substring(7);

            // JWT 검증 및 사용자 정보 가져오기 로직
            String username = validateAndExtractUsername(jwt);

            if (username != null) {
                // SecurityContextHolder에 인증 정보 저장
                SecurityContextHolder.getContext().setAuthentication(
                        new UsernamePasswordAuthenticationToken(username, null, List.of()));
            }
        }

        filterChain.doFilter(request, response);
    }

    private String validateAndExtractUsername(String jwt) {
        // JWT 검증 로직 (간단히 예제로 처리)
        return jwt.equals("valid-jwt") ? "user" : null;
    }
}





import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
public class SecurityConfig {

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        return http
                .authorizeHttpRequests(auth -> auth
                        .anyRequest().authenticated()
                )
                .addFilterBefore(new JwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class) // 사용자 정의 필터 등록
                .build();
    }
}

 

 

728x90
반응형