inflearn logo
강의

Khóa học

Chia sẻ kiến thức

Ứng dụng kiến trúc microservice (MSA) phát triển với Spring Cloud

Thêm AuthenticationFilter

Spring Security 최신버전(Spring Boot 3.X.X 대)의 WebSecurity 설정 공유드립니다.

12121

potatomango

3 câu hỏi đã được viết

18

최신버전으로 진행하다보니 막혔었는데요. 구글링, ChatGPT 등을 통해서 동작하는 코드 공유드립니다.

정확한 구현은 아닐 수 있겠지만, 강의를 진행하는 데는 문제 없는 것 같습니다. 참고만 부탁드려요~

 

package com.example.userservice.security;

import com.example.userservice.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.autoconfigure.security.servlet.PathRequest;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.ObjectPostProcessor;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.util.matcher.IpAddressMatcher;

@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
public class WebSecurity {

    private final UserService userService;
    private final BCryptPasswordEncoder bCryptPasswordEncoder;
    private final ObjectPostProcessor<Object> objectPostProcessor;

    private static final String[] WHITE_LIST = {
            "/users/**",
            "/",
            "/**"
    };

    @Bean
    protected SecurityFilterChain config(HttpSecurity http) throws Exception {
        http.csrf().disable();
        http.headers().frameOptions().disable();
        http.authorizeHttpRequests(authorize -> {
                    try {
                        authorize
                                .requestMatchers(WHITE_LIST).permitAll()
                                .requestMatchers(PathRequest.toH2Console()).permitAll()
                                .requestMatchers(new IpAddressMatcher("127.0.0.1")).permitAll()
                                .and()
                                .addFilter(getAuthenticationFilter());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
        );
        return http.build();
    }

    public AuthenticationManager authenticationManager(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userService).passwordEncoder(bCryptPasswordEncoder);
        return auth.build();
    }

    private AuthenticationFilter getAuthenticationFilter() throws Exception {
        AuthenticationFilter authenticationFilter = new AuthenticationFilter();
        AuthenticationManagerBuilder builder = new AuthenticationManagerBuilder(objectPostProcessor);
        authenticationFilter.setAuthenticationManager(authenticationManager(builder));
        return authenticationFilter;
    }

}

 

이렇게 하시고 중요한 것이, Login Form을 사용하지 않기 때문에 AuthenticationFilter 클래스의 Override 메소드 중 successfulAuthentication 메소드 내부에super.successfulAuthentication(request, response, chain, authResult);

코드가 작성되어 있다면, 아래처럼 제거 또는 주석 처리를 꼭 해야 합니다! (다른 질문 글에서 발견하였습니다, 공유 감사드립니다.)

하지 않은 경우 에러가 발생하며 login 요청이 제대로 동작하지 않습니다.

 

package com.example.userservice.security;

import com.example.userservice.vo.RequestLogin;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import java.io.IOException;
import java.util.ArrayList;

public class AuthenticationFilter extends UsernamePasswordAuthenticationFilter {
    @Override
    public Authentication attemptAuthentication(HttpServletRequest request,
                                                HttpServletResponse response) throws AuthenticationException {
        try {
            RequestLogin creds = new ObjectMapper().readValue(request.getInputStream(), RequestLogin.class);
            return getAuthenticationManager().authenticate(
                    new UsernamePasswordAuthenticationToken(
                            creds.getEmail(),
                            creds.getPassword(),
                            new ArrayList<>()
                    )
            );
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    protected void successfulAuthentication(HttpServletRequest request,
                                            HttpServletResponse response,
                                            FilterChain chain,
                                            Authentication authResult) throws IOException, ServletException {
        //super.successfulAuthentication(request, response, chain, authResult);
    }
}

spring-boot spring-cloud spring-security 최신버전

Câu trả lời 5

2

JungHyo Go

도움 감사합니다 ^^

2

Dowon Lee

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

공유 감사드립니다.

강의를 시작한지 2년정도 되어 가고 있습니다. 강의 업데이트를 준비 중인데, 해당 부분도 참고하겠습니다.

감사합니다.

0

potatomango

저야말로 좋은 지식 공유해주셔서 감사드립니다.

0

KR KHS

감사합니다!

0

sec

하루종일 순환참조부터 오만 시달림 당했는데 감사합니다.. 다음부턴 맘편히 버전 맞춰야겠네요 ㅠ. 감사합니다

0

springboot1234

감사합니다!!

kafka 업데이트 강의 듣고 시포요

0

80

1

강의 교안

0

67

1

마이크로서비스간 통신 시, 인증 처리

0

75

1

api gateway 에서 인증 처리

0

62

1

섹션 19 질문드립니다

0

50

1

강의 자료 업데이트

0

80

1

부하분산 강의 섹션

0

55

1

강의자료는 어디에서?

0

68

1

강의 자료는 어디서 다운 받을 수 있나요?

0

108

1

전체 사용자 조회시 오류

0

56

1

혹시 pk 외 별도의 id 를 부여한 이유가 있을까요 ??

0

107

2

학습 방향

0

93

2

카프카 커넥터 사용 목적 문의

0

84

2

kafka 강의

0

104

2

서비스 디스커버리 종류

0

85

2

강의 자료에 대해서 궁금해요

0

111

2

GlobalFilter, LoggingFilter가 동작하지 않습니다.

0

86

2

Kafka Source Connect 버전 에러

0

81

2

소스커넥터는 사용안한 거 맞죠?

0

79

2

강의자료 업데이트 문의

0

93

2

강의에서 BCryptPasswordEncoder 에 역할(5-2)

0

55

1

강의 업데이트 계획이 궁금합니다.

0

110

2

MSA 애플리케이션에 Spring Web과 Spring Data JPA를 사용하는 것이 바람직한지 궁금합니다. (MSA 설계와 관련된 질문입니다)

0

160

2

어떤 것이 업데이트 된 건가요?

0

160

2