인프런 커뮤니티 질문&답변

흑후추님의 프로필 이미지

작성한 질문수

Spring Cloud로 개발하는 마이크로서비스 애플리케이션(MSA)

Users Microservice - AuthenticationFilter 추가

스프링 시큐리티 최신버전 코드 있을까요?

23.12.01 10:52 작성

·

1.7K

0

제일 최근에 질문한 글 참고해도 적용이 안되네요...

혹시 현재 버전에서 적용 가능한 코드가 있을까요?

아니면 참고할 수 있는 자료라도 있을까요?

 

https://start.spring.io/ 에서 gradle로 생성해서 사용중입니다. 스프링 3.2버전 사용하고있어요.

답변 7

2

unfineapp005님의 프로필 이미지

2024. 07. 20. 18:30

지금은 github 소스를 참고해도 안되네요.

springboot 3.3.0, security-core 6.3.0

제가 설정한 방법 공유합니다.

혹시나 도움이 될까 싶어 올려요.

(2024-07-21) AuthenticationFilter 추가 시 userService 관련하여 순환참조 오류를 해결한 소스입니다.

@Slf4j
@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
public class WebSecurity {

    private final Environment env;

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http,
                                           AuthenticationManager authenticationManager,
                                           UserService userService) throws Exception {

        http.csrf(AbstractHttpConfigurer::disable)
                .authorizeHttpRequests(authorize ->
                        authorize.requestMatchers("/users/**").permitAll()
                                .requestMatchers("/actuator/**").permitAll()
                                .requestMatchers("/health-check/**").permitAll()
                                .requestMatchers("/error/**").permitAll()
                                .requestMatchers("/**").access((authentication, request) -> {
                                    String clientIp = request.getRequest().getRemoteAddr();
                                    log.debug("client ip is = {}", clientIp);

                                    // 허용된 IP 리스트
                                    String[] allowedIps = {"192.168.35.194", "192.168.35.195", "192.168.35.196"};

                                    // IP가 허용된 리스트에 포함되어 있는지 확인
                                    boolean isAllowed = Arrays.asList(allowedIps).contains(clientIp);

                                    return new AuthorizationDecision(isAllowed);
                                })
                )
                .authenticationManager(authenticationManager)
                // 사용자 세션 저장하지 않음
                .sessionManagement(configurer -> configurer.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
                // 응답 헤더에 X-Frame-Options 추가 - 클릭재킹 공격 방어 - 동일 출처만 <iframe> 로드 가능.
                .headers(headers -> headers.frameOptions(HeadersConfigurer.FrameOptionsConfig::sameOrigin))
                .addFilter(customAuthenticationFilter(authenticationManager, userService));

        return http.build();
    }

    /**
     * authenticationManager bean 생성
     * @param http HttpSecurity
     * @return authenticationManager bean
     */
    @Bean
    public AuthenticationManager authenticationManager(HttpSecurity http,
                                                       UserService userService,
                                                       BCryptPasswordEncoder passwordEncoder) throws Exception {
        AuthenticationManagerBuilder authenticationManagerBuilder = http.getSharedObject(AuthenticationManagerBuilder.class);
        authenticationManagerBuilder.userDetailsService(userService).passwordEncoder(passwordEncoder);

        return authenticationManagerBuilder.build();
    }

    /**
     * customAuthenticationFilter bean 생성
     * @return customAuthenticationFilter bean
     */
    @Bean
    public CustomAuthenticationFilter customAuthenticationFilter(AuthenticationManager authenticationManager,
                                                                 UserService userService) {
        return new CustomAuthenticationFilter(authenticationManager, userService, env);
    }

    /**
     * 비밀번호 암호화 모듈
     * @return 암호화 bean
     */
    @Bean
    public BCryptPasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}

1

Dowon Lee님의 프로필 이미지
Dowon Lee
지식공유자

2024. 02. 02. 23:33

안녕하세요, 이도원입니다.

강좌에서 사용된 샘플 코드를 최신 버전으로 업데이트 하였습니다.

아래 github 에서 확인해 보실 수 있습니다.

https://github.com/joneconsulting/toy-msa

감사합니다.

1

정호연님의 프로필 이미지

2023. 12. 05. 06:43

이게 답변이 될 수 있을지 모르겠는데요.. 저도 공부하면서 뭔가 틀려서 여러 삽질을 통해서 코드 변경해가면서 하고 있어서


@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
public class WebSecurity {

    private final UserService userService;
    private final BCryptPasswordEncoder bCryptPasswordEncoder;
    private final Environment env;
    private final AuthenticationConfiguration authenticationConfiguration;

    @Bean
    public WebSecurityCustomizer webSecurityCustomizer() {
        return (web) -> web.ignoring().requestMatchers(PathRequest.toStaticResources().atCommonLocations());
    }

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http.csrf().disable()
                .authorizeRequests()
                .antMatchers("/actuator/**").permitAll();

        http.csrf().disable()
                .authorizeRequests().antMatchers("/**")
                .hasIpAddress("192.168.0.7")
                .and()
                .addFilter(getAuthenticationFilter(authenticationConfiguration))
                .headers().frameOptions().disable();
        return http.build();
    }

    private AuthenticationFilter getAuthenticationFilter(AuthenticationConfiguration authenticationConfiguration) throws Exception {
        AuthenticationFilter authenticationFilter = new AuthenticationFilter(authenticationManager(authenticationConfiguration), userService, env);
        return authenticationFilter;
    }

    @Bean
    AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration) throws Exception {
        return authenticationConfiguration.getAuthenticationManager();
    }


}
흑후추님의 프로필 이미지
흑후추
질문자

2023. 12. 06. 14:27

혹시 스프링이랑 시큐리티 버전이 어떻게되나요?

0

Dowon Lee님의 프로필 이미지
Dowon Lee
지식공유자

2024. 07. 21. 09:50

안녕하세요, 이도원입니다.

현재 Spring Boot 3.2 + Spring Cloud 2023.0.0 버전으로 된 실습 코드를 공유해 드리고 있습니다. 관련 실습 코드에 대한 강의 콘텐츠도 업로드 되었습니다. 혹시 아래 코드로 실행하실 때에도 오류가 발생하는 건지 확인해 주실 수 있을끼요? 오류가 발생 되셨다면 관련 부분은 한번 더 공유해 주시면 감사드리겠습니다.

새로운 소스 코드는 아래 Github에 공유 되어 있고, Branch는 main이 아니라 springboot3.2 Branch를 사용하시기 바랍니다.

https://github.com/joneconsulting/toy-msa/tree/springboot3.2

감사합니다.

Dowon Lee님의 프로필 이미지
Dowon Lee
지식공유자

2024. 07. 21. 09:52

추가로, use-service에 대한 새로운 강의 콘텐츠는 아래에 업로드되어 있습니다. 참고 부탁드립니다.

https://www.inflearn.com/course/lecture?courseSlug=%EC%8A%A4%ED%94%84%EB%A7%81-%ED%81%B4%EB%9D%BC%EC%9A%B0%EB%93%9C-%EB%A7%88%EC%9D%B4%ED%81%AC%EB%A1%9C%EC%84%9C%EB%B9%84%EC%8A%A4&unitId=231751

0

흑후추님의 프로필 이미지
흑후추
질문자

2024. 01. 05. 09:59

섹션 4. Users Microservice ➀ Spring Security 코드 입니다.

@Configuration
@EnableWebSecurity
public class WebSecurity {
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http.csrf(csrf->csrf.disable());
        http.authorizeHttpRequests(request->{
            request.requestMatchers(antMatcher("/users/**")).permitAll();
            request.requestMatchers(antMatcher("/h2-console/**")).permitAll();
        });
        http.headers(headers->headers.frameOptions(frameOptions->frameOptions.disable()));
        return http.build();
    }
}

0

흑후추님의 프로필 이미지
흑후추
질문자

2023. 12. 08. 11:07

https://www.inflearn.com/questions/1020758/springboot-3%EC%A0%90%EB%8C%80-%EB%B2%84%EC%A0%84-spring-security-%EC%84%A4%EC%A0%95

여기 코드 참고해서 작성했습니다.

섹션6 기준으로 나머지 코드는 변수명 정도만 수정했고, WebSecurity코드는 이렇게 바꿔서 사용했어요.

@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
public class WebSecurity {

    private final UserService userService;
    private final Environment environment;
    private final AuthenticationConfiguration authenticationConfiguration;
    private final AuthenticationManager authenticationManager;

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http.csrf(AbstractHttpConfigurer::disable)
                .authorizeHttpRequests(request ->{
                    request.requestMatchers(antMatcher("/**")).permitAll();
                })
                .addFilter(getAuthenticationFilter(authenticationConfiguration));
        http.headers().frameOptions().disable(); //H2 Console 설정

        return http.build();
    }

    private AuthenticationFilter getAuthenticationFilter(AuthenticationConfiguration authenticationConfiguration) throws Exception {
        AuthenticationFilter authenticationFilter = new AuthenticationFilter(authenticationManager, userService, environment);
        return authenticationFilter;
    }

}

0

인프런 AI 인턴님의 프로필 이미지

2023. 12. 03. 10:56

안녕하세요, 인프런 AI 인턴입니다.

스프링 시큐리티를 사용하는 데 문제가 있으시군요.
스프링 부트 참조 문서의 “18. “How-to” Guides > 18.14. Security” 섹션을 참고하시면 현재 버전의 스프링 부트에 적용 가능한 스프링 시큐리티 관련 정보를 얻으실 수 있습니다.

자세한 내용과 가이드는 스프링 시큐리티 프로젝트 페이지에서 확인하실 수 있습니다.

또한, 스프링 부트에 관련된 다양한 상황의 질문과 답변이 필요하다면 Stack Overflow의 spring-boot 태그가 붙은 글을 참조하시거나, 새 질문을 하실 수도 있습니다.

현재 문서는 스프링 부트 3.1.5 버전을 기준으로 하고 있지만, 스프링 부트 3.2 버전에서도 동일하게 적용될 수 있는 내용이 많으니 참고하시면 도움이 될 것입니다.

참고 문서 URL: Spring Boot Reference Documentation - Security

오류가 지속되거나 구체적인 코드를 찾기 어려우시면, 추가적으로 문의 주시면 답변 드리도록 하겠습니다. 흑후추님, 문제 해결을 위한 참고 자료가 도움이 되길 바랍니다.