요청 기반 권한 부여 - HttpSecurity.securityMatch 강의 (14분 25초) 를 듣고 코드를 똑같이 따라 치고 실행해보니 에러가 뜨면서 동작을 안 하더군요. spring boot 버전은 3.4.1 + spring security 6.4.2 로 테스트를 해봤습니다. 조사를 해보니 에러를 뱉는 건 스프링 시큐리티의 WebSecurity 클래스였고, 아래 빨간 박스 친 부분에서 에러를 뱉습니다. 이 코드는 securityMatcher 를 설정 안 한 SecurityFilterChain, 즉 anyRequestFilterChain 이 모든 FilterChain 들 보다 항상 뒤편에 있어야 되는 것을 보장하기 위한 유효성 검사를 위한 것입니다. 선생님이 강의를 찍던 당시와 달라진 내용이 아닐까 싶습니다. 아무튼 이를 우회해서 테스트를 할 수 있는데, 선생님이 작성하신 코드에서 딱 한줄만 추가해주면 됩니다. @Bean @Order(1) public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { // !!!!!!!!!!!!!!! 아래 한 줄 추가 !!!!!!!!!!!!!!! http.securityMatchers(matcher -> matcher.requestMatchers("/**")); http.authorizeHttpRequests(auth -> { auth.anyRequest().authenticated(); }) .formLogin(Customizer.withDefaults()); return http.build(); } @Bean public SecurityFilterChain securityFilterChain2(HttpSecurity http) throws Exception { http.securityMatchers(matchers -> matchers.requestMatchers("/api/**", "/oauth/**")); http.authorizeHttpRequests(auth -> { auth.anyRequest().permitAll(); }); return http.build(); } 이상으로 내용 공유를 마칩니다.
안녕하세요 선생님, 현재 프로젝트에서 프로덕션에서 사용하는 SecurityConfig클래스와 테스트에서 사용하는 SecurityConfig를 다르게 가져가려 합니다. 이유는 프로덕션 환경에서는 jwt필터 같이 커스텀 필터들을 적용해야하고, 테스트 환경에서는 해당 필터들을 거치지 않도록 해서 테스트를 더 편하게 하기 위함입니다. @Configuration @EnableWebSecurity public class SecurityConfig { @Bean("prodSecurityFilterChain") public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {...} ... http.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class); ... } @TestConfiguration @EnableWebSecurity public class TestSecurityConfig { @Bean("testSecurityFilterChain") public SecurityFilterChain testSecurityFilterChain(HttpSecurity http) throws Exception {...} //필터 없음 } 위 처럼 작성하였습니다. 컨트롤러 테스트 시 @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) @ActiveProfiles("test") public class InterfaceTest { @LocalServerPort private int port; @BeforeEach void setUp() { RestAssured.port = port; } } 위의 클래스를 상속받아서 테스트를 구현합니다. 제 의도는 테스트 시에는 @TestConfiguration이 주어진 SecurityConfig를 기반으로 설정이 될거고 TestSecurityConfig에는 jwt필터가 없으니, 테스트 코드에서는 필터를 거치지 않고 잘 수행이 될거다 였으나, 실제 Security 디버그를 보면 2024-12-11 10:17:32 [Test worker] DEBUG org.springframework.security.web.DefaultSecurityFilterChain - Will secure any request with filters: DisableEncodeUrlFilter, WebAsyncManagerIntegrationFilter, SecurityContextHolderFilter, HeaderWriterFilter, CorsFilter, LogoutFilter, BlackListCheckFilter, JwtAuthenticationFilter, RequestCacheAwareFilter, SecurityContextHolderAwareRequestFilter, AnonymousAuthenticationFilter, SessionManagementFilter, ExceptionTranslationFilter, AuthorizationFilter 로 JwtAuthenticationFilter가 있으며, 인증처리가 안되었다는 401에러를 뱉고있습니다. 질문 드립니다. 1. 프로덕션 환경과 테스트 환경 Config구분시 별도의 설정이 더 필요할까요? 자료들을 더 찾아보아도 다른 방법이 없어서 질문드립니다. 2. 혹시 Config를 구분하는것이 아예 불가능한것일까요?? 아니라면, 실무에서도 위와 같은 구조가 자주 사용되는지 등 궁금합니다.
@EnableWebSecurity @Configuration public class SecurityConfig { @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http, HandlerMappingIntrospector introspector) throws Exception{ http .addFilterAt(authorizationFilter(introspector), AuthorizationFilter.class) .formLogin(Customizer.withDefaults()) .csrf(AbstractHttpConfigurer::disable); return http.build(); } @Bean public AuthorizationFilter authorizationFilter(HandlerMappingIntrospector introspector){ List<RequestMatcherEntry<AuthorizationManager<RequestAuthorizationContext>>> mappings = new ArrayList<>(); RequestMatcherEntry<AuthorizationManager<RequestAuthorizationContext>> requestMatcherEntry1 = new RequestMatcherEntry<>( new MvcRequestMatcher(introspector, "/user"), AuthorityAuthorizationManager.hasAuthority("ROLE_USER")); RequestMatcherEntry<AuthorizationManager<RequestAuthorizationContext>> requestMatcherEntry2 = new RequestMatcherEntry<>( new MvcRequestMatcher(introspector, "/db"), AuthorityAuthorizationManager.hasAuthority("ROLE_DB")); RequestMatcherEntry<AuthorizationManager<RequestAuthorizationContext>> requestMatcherEntry3 = new RequestMatcherEntry<>( new MvcRequestMatcher(introspector, "/admin"), AuthorityAuthorizationManager.hasAuthority("ROLE_ADMIN")); RequestMatcherEntry<AuthorizationManager<RequestAuthorizationContext>> requestMatcherEntry4 = new RequestMatcherEntry<>( AnyRequestMatcher.INSTANCE, // default strategy = AuthenticatedAuthorizationStrategy new AuthenticatedAuthorizationManager<>()); mappings.add(requestMatcherEntry1); mappings.add(requestMatcherEntry2); mappings.add(requestMatcherEntry3); mappings.add(requestMatcherEntry4); RequestMatcherDelegatingAuthorizationManager manager = RequestMatcherDelegatingAuthorizationManager.builder() .mappings(maps -> maps.addAll(mappings)).build(); return new AuthorizationFilter(manager); } @Bean public UserDetailsService userDetailsService(){ UserDetails user = User.withUsername("user").password("{noop}1111").roles("USER").build(); UserDetails db = User.withUsername("db").password("{noop}1111").authorities("ROLE_DB").build(); UserDetails admin = User.withUsername("admin").password("{noop}1111").roles("ADMIN","SECURE").build(); return new InMemoryUserDetailsManager(user, db, admin); } } 필터에 직접 RequestMatcherDelegatingAuthorizationManager를 넣는 방식으로 개선해 봤습니다 처음에는 RequestMatcherDelegatingAuthorizationManager -> RequestMatcherDelegatingAuthorizationManager 구조로 바꾸려고 했는데 access()에는 AuthorizationManager<RequestAuthorizationContext>만 가능해서 AuthorizationManager<HttpServletRequest>인 RequestMatcherDelegatingAuthorizationManager를 바로 못 넣더라구요 그래서 필터를 생성하고 필터 생성자로 RequestMatcherDelegatingAuthorizationManager를 넣는 방식을 사용했습니다
해당 필터는 단순히 Supplier로 감싸진 CsrfToken 을 getToken ()을 통해서 초기화를 진행하고 있습니다 GET 방식이면 어차피 CsrfFilte r에서 바로 다음 필터로 넘어가고 POST면 CsrfFilter 에서 토큰 비교를 하기 위해서 초기화를 CsrfFilter 에서 하는데 CsrfCookieFilter 는 왜 필요할까요? 여러 가지 케이스로 디버깅하면서 좀 더 살펴봤는데 특정 페이지에서 POST 요청을 하는 버튼이 있으면 먼저 CSRF 토큰을 발급해서 클라이언트에 저장이 되어있어야 POST 요청에서 토큰을 쿠키에 꺼내어 검증할 수 있기 때문에 GET 요청에도 getToken()을 통해서 초기화가 진행되고 해당 초기화 과정에 saveCookie 로직이 있기 때문에 클라이언트 쿠키에 토큰이 저장되는 걸로 추측했습니다
CSRF 통합 강의에서 17분쯤에 user 1111 계정이 아니라 ddd로 입력을 하시는데 UserDetails로 설정 하지 않으신 것 같은데 어떻게 로그인이 되는 건지 궁금합니다. 로그인 후 Whitelabel Error가 뜨는 경우는 어떤 부분을 수정하면 될까요? 이 강의를 수강하면서 해당 오류가 많았습니다. 로그인이 된 경우도 있고 안 된 경우도 있었습니다.
현재 지금 프론트와 백엔드로 나누어져 웹 개발을 하고 있습니다 여기서 궁금한점은 선생님 코드를 다 따라 적었는데 프론트에서 로그인 요청을 해서 로그인한 이후 프론트에서 메인 페이지로 보내는데 거기서 다음 기능을 쓰려고 하면 서버 500에러가 뜨고 어나니머스필터가 요청을 받는거 같습니다 저도 정확하게 알 수 없어서 그런데 혹시 CSRF기능을 안써서 어나니머스필터로 가는 것인지 아니면 뭐가 잘못 된건지 알 수 없습니다 좀 알려주시면 감사하겠습니다
안녕하세요. 선생님 시큐리티 강의를 재밌게 듣고있는 한 학생으로서 명품강의를 만들어주셔서 감사드립니다. 강의를 들으면서 SameOrigin과 쿠키(SameSite)의 차이를 구별할 수 있게 됐고 더 나아가 Samesite간의 SingleSignOn(sso)이라는 기술도 관심을 갖게 됐습니다. sso관련하여 추천하실만한 도서나 기술블로그가 있으신지 궁금합니다~!
로그인의 경우 앞선강의에서 /login 엔드포인트로 post요청을 보낼텐데, 지금 예제를 보면 모든 엔드포인트에 대하여 HttpMethod.POST는 ROLE_WRITE권한을 가져야한다라고 명시되어져 있습니다. MANAGER권한을 갖은 UserDetails 계정으로 로그인을하면 post요청을 보내니 로그인이 실패되지 않을까 고민이 되었는데, 성공하는 것을 강의에서 확인하였습니다. 이것이 왜 가능한 것인지 궁금합니다.
인증제공자 2에서 커스텀한 필터 적용하고 마지막으로 서버 가동후에 테스트 하는데 해당 화면이 뜹니다. 주소창에 localhost:8080 입력후 접근하면 제대로 뜨는 것을 보면 리다이렉트 문제라고 생각되는데 쿼리스트링으로 인증 후에 다시 루트로 리다이렉트를 어떻게 해야 하나요? 다 옮겨 적은 거 같은데 혹시 제가 놓친 설명이나 코드가 있다면 죄송합니다.
AuthenticationManager가 부모 AuthenticationManager를 가지는 이유를 모르겠습니다. 매니저는 프로바이더를 여러 개 가질 수 있는데, 굳이 부모 매니저를 추가로 가질 수 있도록 해서 부모의 프로바이더를 사용해야할 이유가 있을까요? 그리고 그렇게 사용하는 적절한 예시가 있을까요?