묻고 답해요
167만명의 커뮤니티!! 함께 토론해봐요.
인프런 TOP Writers
-
해결됨스프링 시큐리티 완전 정복 [6.x 개정판]
FormAuthenticationFailureHandler -> setDefaultFailureUrl 의 Thread safety
안녕하세요 선생님, [커스텀 인증실패 핸들러 - AuthenticationFailureHandler (08:11) ] 강의를 듣다가 의문점이 생겨서 문의드립니다. 현재 AuthenticationFailureHandler 를 extend 해서 사용 중인데 FormAuthenticationFailureHandler.onAuthenticationFailure 메소드에서 아래처럼 defaultFailureUrl 을 변경하는 부분이 있습니다.@Component public class FormAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler { @Override public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException { String errorMessage = "Invalid Username or Password"; if (exception instanceof BadCredentialsException) { errorMessage = "Invalid Username or Password"; } else if (exception instanceof UsernameNotFoundException) { errorMessage = "User not exists"; } else if (exception instanceof CredentialsExpiredException) { errorMessage = "Expired password"; } else if (exception instanceof SecretException) { errorMessage = "Invalid Secret Key"; } // Thread Safe...? setDefaultFailureUrl("/login?error=true&exception=" + errorMessage); super.onAuthenticationFailure(request, response, exception); } }이 setDefaultFailureUrl 메소드를 호출해서 모든 쓰레드가 접근할 수 있는 defaultFailureUrl 필드를 변경하는 건 Thread Safe 하지 않지 않나요??
-
해결됨스프링 시큐리티 완전 정복 [6.x 개정판]
(공유) 이제는 securityMatcher 지정 안 한 FilterChain 의 순서가 맨 앞에 있으면 에러를 뱉어냅니다.
요청 기반 권한 부여 - 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(); } 이상으로 내용 공유를 마칩니다.
-
미해결스프링 시큐리티 완전 정복 [6.x 개정판]
HttpSecurity configurer
5강에서 11개의 configurer가 생성된다고 하셨는데제꺼에서는 CorsConfigurer를 제외한 10개만 생성이 됩니다.왜 이런지 알 수 있을까요?
-
미해결스프링 프레임워크는 내 손에 [스프1탄]
재생이 안되요
폰에서 영상 실행이 안되요 일부 다른 강의도 재생에 뮨제가 생겼다고 나오면서 영상이 안나와요강의 자체 문제보다는 시스템 문제 같아요다른 강의 중에 정상 실행돠는것도 있어요일부 강의만 안나와요
-
미해결스프링 시큐리티 완전 정복 [6.x 개정판]
인텔리제이 무료버전 사용중입니다. 프로젝트 생성 시
이렇게 안뜨고이렇게 떠 있는데 어떻게 프로젝트를 생성해야하는지 모르겠습니다 ㅠㅠ
-
해결됨스프링 시큐리티 완전 정복 [6.x 개정판]
프로덕션 환경과 테스트 환경 Config를 다르게 가져가는 방법
안녕하세요 선생님,현재 프로젝트에서 프로덕션에서 사용하는 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를 구분하는것이 아예 불가능한것일까요??아니라면, 실무에서도 위와 같은 구조가 자주 사용되는지 등 궁금합니다.
-
미해결스프링 시큐리티 완전 정복 [6.x 개정판]
구조 개선하기
@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를 넣는 방식을 사용했습니다
-
미해결스프링 시큐리티 완전 정복 [6.x 개정판]
섹션 9 계층적 권한 메소드 Deprecated
테스트 중 사용된 메소드가 곧 Deprecated 된다고 나오는데 혹시 다른 메소드 설정 방법 알려주실 수 있을까요?
-
미해결스프링 시큐리티 완전 정복 [6.x 개정판]
CsrfCookieFilter 역할?
해당 필터는 단순히 Supplier로 감싸진 CsrfToken을 getToken()을 통해서 초기화를 진행하고 있습니다 GET 방식이면 어차피 CsrfFilter에서 바로 다음 필터로 넘어가고 POST면 CsrfFilter에서 토큰 비교를 하기 위해서 초기화를 CsrfFilter에서 하는데 CsrfCookieFilter는 왜 필요할까요? 여러 가지 케이스로 디버깅하면서 좀 더 살펴봤는데특정 페이지에서 POST 요청을 하는 버튼이 있으면 먼저 CSRF 토큰을 발급해서 클라이언트에 저장이 되어있어야 POST 요청에서 토큰을 쿠키에 꺼내어 검증할 수 있기 때문에GET 요청에도 getToken()을 통해서 초기화가 진행되고 해당 초기화 과정에 saveCookie 로직이 있기 때문에클라이언트 쿠키에 토큰이 저장되는 걸로 추측했습니다
-
미해결스프링 시큐리티 완전 정복 [6.x 개정판]
이 강의에 세션을 사용해서
로그인한 사용자가 저의 localhost8080서버가 다시 재작동해도 로그인이 유지되게하는 강의 내용도있을가요?
-
미해결스프링 시큐리티 완전 정복 [6.x 개정판]
CSRF 통합 로그인 계정 및 로그인 후 Whitelabel Error
CSRF 통합 강의에서 17분쯤에 user 1111 계정이 아니라 ddd로 입력을 하시는데 UserDetails로 설정 하지 않으신 것 같은데 어떻게 로그인이 되는 건지 궁금합니다.로그인 후 Whitelabel Error가 뜨는 경우는 어떤 부분을 수정하면 될까요? 이 강의를 수강하면서 해당 오류가 많았습니다. 로그인이 된 경우도 있고 안 된 경우도 있었습니다.
-
미해결스프링 시큐리티 완전 정복 [6.x 개정판]
rest 로그인 방식 rememberMe 처리
RestApiDsl 에서 rememberMeService가 처리가 되는데json 방식으로 통신 시 remember-me 파라미터를 받지못합니다. AbstractRememberMeServices 를 상속받아 따로 처리해야 하는 건지 궁금합니다.
-
미해결스프링 시큐리티 완전 정복 [6.x 개정판]
시큐리티 로그인 인증 한 이후 다음 프론트 요청 어나니머스(익명사용자) 필터??
현재 지금 프론트와 백엔드로 나누어져 웹 개발을 하고 있습니다 여기서 궁금한점은 선생님 코드를 다 따라 적었는데 프론트에서 로그인 요청을 해서 로그인한 이후 프론트에서 메인 페이지로 보내는데 거기서 다음 기능을 쓰려고 하면 서버 500에러가 뜨고 어나니머스필터가 요청을 받는거 같습니다 저도 정확하게 알 수 없어서 그런데 혹시 CSRF기능을 안써서 어나니머스필터로 가는 것인지 아니면 뭐가 잘못 된건지 알 수 없습니다 좀 알려주시면 감사하겠습니다
-
미해결스프링 프레임워크는 내 손에 [스프1탄]
404 HTTP 상태 코드
선생님 안녕하세요 MVC01에서 코드를 이상 없이 작성한 거 같은데 계속해서 404 에러 코드가 발생해서 한 번만 확인해주시면 감사하겠습니다.https://github.com/normaldeve/SpringMVC
-
미해결스프링 시큐리티 완전 정복 [6.x 개정판]
Rest 로그인 후 403 오류
Rest 방식 로그인 하였을 때 유저정보를 불러오지를 못합니다.로그인 하였을 때 로그 filerChainrestFilterrestcontroller@AuthenticationPrincipal 에 담긴 정보
-
미해결코드로 배우는 스프링 웹 프로젝트 - Intermediate
로그인 처리 시 패스워드 null이 들어 가는 현상
강사님 코드 대로 로그인 처리 시 password가 null 이라 로그인 실패 합니다<security:authentication-manager> <security:authentication-provider user-service-ref="myUserDetailsService"> </security:authentication-provider> </security:authentication-manager>결국 검색을 통해 <security:authentication-manager> <security:authentication-provider user-service-ref="customUserDetailsService"> <!-- PasswordEncoder 추가 --> <security:password-encoder ref="passwordEncoder" /> </security:authentication-provider> </security:authentication-manager>안에 코드를 추가하니 정상으로 로그인 처리가 되었습니다의문점은 왜 강사님은 저 코드를 추가 하지 않아도 정상 적으로 로그인이 되는 건지 궁금합니다 제가 빠뜨린 코드가 있나 전부 체크를 해보았는데 그런 부분은 없었습니다
-
미해결스프링 시큐리티 완전 정복 [6.x 개정판]
RestAuthenticationToken의미 token의 의미
RestAuthenticaionToken 클래스를 만든 의미가 궁금하고 여기 시큐리티에서 token의 의미가 무엇인지 궁금합니다
-
해결됨이거 하나로 종결-스프링 기반 풀스택 웹 개발 무료 강의
다운로드 불가
1강 소개 자료 zip 파일이 압축 해제가 안 됩니다!
-
미해결스프링 시큐리티 완전 정복 [6.x 개정판]
다음강의는뭐에요?
동시성준비중이신다음강의는뭐에요?
-
미해결스프링 프레임워크는 내 손에 [스프1탄]
lombok api 등록 후
lombok을 임포트시키고 나서 아웃라인에 변화가 일어나지 않습니다.이런 경고메시지도 떴는데 뭐가 잘못된 걸까요..?