안녕하세요. 강사님 강의 듣고 WebFlux 방식에서도 프로그래밍 방식 또는 동적방식으로 권한을 적용해 보고자 이것저것 해보고 있는데요. WebFlux 방식에서는 DelegatingReactiveAuthorizationManager 클래스에서 private final List<ServerWebExchangeMatcherEntry<ReactiveAuthorizationManager<AuthorizationContext>>> mappings; 이 형식으로 mappings를 생성자로 넘겨주거나 생성될때 build add() 메서드로 한건식 넘겨주면 List 형식에 추가되어 요청이 들어오면 아래의 check메서드에서 해당 요청을 체크하는 것 같습니다. @Override public Mono<AuthorizationDecision> check(Mono<Authentication> authentication, ServerWebExchange exchange) { return Flux.fromIterable(this.mappings) .concatMap((mapping) -> mapping.getMatcher() .matches(exchange) .filter(MatchResult::isMatch) .map(MatchResult::getVariables) .flatMap((variables) -> { logger.debug(LogMessage.of(() -> "Checking authorization on '" + exchange.getRequest().getPath().pathWithinApplication() + "' using " + mapping.getEntry())); return mapping.getEntry().check(authentication, new AuthorizationContext(exchange, variables)); })) .next() .defaultIfEmpty(new AuthorizationDecision(false)); } 문제는 mappings 정보를 어떻게 만들어서 넘겨야 할지 감이 안옵니다. .pathMatchers(HttpMethod.GET, "/routes").permitAll() .pathMatchers(HttpMethod.POST, "/auth-server/**").permitAll() .pathMatchers(HttpMethod.POST,"/auth-service/auth/token").permitAll() .pathMatchers(HttpMethod.GET,"/auth-service/api/v1/users").hasRole("ROLE_USER") 이 4개의 pathMatchers를 아래의 형식으로 해서 List로 넘겨야 할듯 한데 어떻게 할 수 있을까요? ServerWebExchangeMatcherEntry<ReactiveAuthorizationManager<AuthorizationContext>>> new ServerWebExchangeMatcherEntry<ReactiveAuthorizationManager<AuthorizationContext>>( ServerWebExchangeMatchers.pathMatchers(HttpMethod.GET, "/auth-service/api/v1/users"), AuthorityReactiveAuthorizationManager.hasRole("ROLE_USER")) 위의 방법으로 객체를 하나하나 만들어서 넘겨보기도 했는데 Role이 지정된 건 적용이 됩니다. 그러나 permitAll()을 시켜줘야 하는 것들은 어떻게 적용시켜야 할지... 하루종일 방법을 찾아봤는데 내공 부족으로 인하여 못찾고 해매고 있습니다. 도움 부탁드립니다.
수업에서 배운 세션 고정 공격은 먼저 공격자가 서버에 로그인 인증을 완료한 후 세션ID를 받은 뒤에 피해자에게 몰래 심는 거잖아요. 해당 세션ID로 피해자가 서버에 접속하는 걸텐데, 서버 입장에선 공격자의 신상으로 이미 인증이 되어 있어서 피해자의 모든 요청에 허용을 하지 않을까요? 굳이 피해자가 다시 로그인을 하는 상황이 머릿속에 그려지지 않습니다. 또 피해자가 사이트에 접속했을 때 이미 인증이 되어 있기 때문에 다른 사람으로 로그인이 되어 있을테고, 그러면 오히려 공격자의 신상이 피해자에게 노출되는 꼴 아닌가요..? ㅎㅎ 그렇다고 피해자가 다시 로그인을 하기 위해서 로그아웃하는 순간 악의적인 세션ID는 더 이상 사용하지 못하게 되구요.. 궁금합니다!
안녕하세요 선생님 현재 실전 프로젝트 20 restDsl까지 적용하여 저의 개인 프로젝트를 진행 중에 있습니다 세션 방식은 문제없이 동작을 하지만 토큰으로 변경을 하고자 하니 문제가 생겼습니다 질문 1. 기존 RestAuthenticationFilter을 그대로 사용하고 RestAuthenticationSuccessHandler에서 인증이 완료가 되면 토큰을 발급하여 헤더로 보내주는 것이 가능할가요? 1 방식이 가능하다면 정상 발급된 토큰을 확인하는 필터를 RestAuthenticationFilter 앞에 추가하도록 하여 인증을 유지하고 싶습니다 또한 실제 인증 처리는 Provider 쪽에서 진행이 된다고 강의에서 배웠는데 JwtAuthenticationProvider라는 클래스를 따로 하나 만들어 또 하나의 restFilter를 생성하여 @Order로 우선순위를 주고 새로이 인증을 처리하는 방식이 맞을까요? 이상이 제가 질문 드리고 싶은 부분들 입니다. 혹시 틀린 점이나 추가해야 하는 점이 있다면 조언 부탁 드립니다..
안녕하세요. 강의 열심히 듣고 이것저것 많이 배우고 있습니다. 강사님 강의 중 동적으로 권한 정보를 읽어다 적용하는 부분을 배웠습니다. 혹시 webflux 방식에서도 동적 커스텀 권한 관리가 가능할까요? 자료를 찾아봐도 딱히 방법에 대해 자료가 많이 검색이 되지 않는데 가능 여부만이라도 확인이 가능할까 해서 여쭤봅니다.
ubuntu@ip-172-31-86-200:~/memberCertification$ ./gradlew clean build Deprecated Gradle features were used in this build, making it incompatible with Gradle 9.0. You can use '--warning-mode all' to show the individual deprecation warnings and determine if they come from your own scripts or plugins. For more on this, please refer to https://docs.gradle.org/8.7/userguide/command_line_interface.html#sec:command_line_warnings in the Gradle documentation. BUILD FAILED in 15s 8 actionable tasks: 8 executed ubuntu@ip-172-31-86-200:~/memberCertification$ ./gradlew clean build > Task :test MemberCertificationApplicationTests > contextLoads() FAILED java.lang.IllegalStateException at DefaultCacheAwareContextLoaderDelegate.java:180 Caused by: org.springframework.beans.factory.BeanCreationException at AbstractAutowireCapableBeanFactory.java:1773 Caused by: org.hibernate.service.spi.ServiceException at AbstractServiceRegistryImpl.java:276 Caused by: org.hibernate.HibernateException at DialectFactoryImpl.java:191 1 test completed, 1 failed > Task :test FAILED FAILURE: Build failed with an exception. * What went wrong: Execution failed for task ':test'. > There were failing tests. See the report at: file:///home/ubuntu/memberCertification/build/reports/tests/test/index.html * Try: > Run with --scan to get full insights. Deprecated Gradle features were used in this build, making it incompatible with Gradle 9.0. You can use '--warning-mode all' to show the individual deprecation warnings and determine if they come from your own scripts or plugins. For more on this, please refer to https://docs.gradle.org/8.7/userguide/command_line_interface.html#sec:command_line_warnings in the Gradle documentation. BUILD FAILED in 15s 8 actionable tasks: 8 executed ubuntu@ip-172-31-86-200:~/memberCertification$ ./gradlew clean build > Task :test MemberCertificationApplicationTests > contextLoads() FAILED java.lang.IllegalStateException at DefaultCacheAwareContextLoaderDelegate.java:180 Caused by: org.springframework.beans.factory.BeanCreationException at AbstractAutowireCapableBeanFactory.java:1773 Caused by: org.hibernate.service.spi.ServiceException at AbstractServiceRegistryImpl.java:276 Caused by: org.hibernate.HibernateException at DialectFactoryImpl.java:191 1 test completed, 1 failed > Task :test FAILED FAILURE: Build failed with an exception. * What went wrong: Execution failed for task ':test'. > There were failing tests. See the report at: file:///home/ubuntu/memberCertification/build/reports/tests/test/index.html * Try: > Run with --scan to get full insights. Deprecated Gradle features were used in this build, making it incompatible with Gradle 9.0. You can use '--warning-mode all' to show the individual deprecation warnings and determine if they come from your own scripts or plugins. For more on this, please refer to https://docs.gradle.org/8.7/userguide/command_line_interface.html#sec:command_line_warnings in the Gradle documentation. BUILD FAILED in 14s 8 actionable tasks: 8 executed 구글에 검색해본 결과, java: error: invalid flag: --warning-mode=all을 하면 된다는 글을 보고 Preferences > Compiler > java Compiler에 --warning-mode all --stacktrace 입력을 하고 실행을 해봤습니다. java: error: invalid flag: --warning-mode=all가 발생하며 실행이 되지 않습니다. 어떻게 해야 에러를 고칠 수 있을까요 ?
Description: Parameter 0 of constructor in com.example.membercertification.security.config.SecurityConfig required a single bean, but 2 were found: - authenticationProvider: defined in file [/Users/jjeong/Desktop/study/memberCertification/out/production/classes/com/example/membercertification/security/provider/FormAuthenticationProvider.class] - restAuthenticationProvider: defined in file [/Users/jjeong/Desktop/study/memberCertification/out/production/classes/com/example/membercertification/security/provider/RestAuthenticationProvider.class] This may be due to missing parameter name information Action: Consider marking one of the beans as @Primary, updating the consumer to accept multiple beans, or using @Qualifier to identify the bean that should be consumed Ensure that your compiler is configured to use the '-parameters' flag. You may need to update both your build tool settings as well as your IDE. (See https://github.com/spring-projects/spring-framework/wiki/Upgrading-to-Spring-Framework-6.x#parameter-name-retention) 해당 에러에서 적힌 provider 2개를 @Qualifier와 @Primary로 설정하면 /api에서 로그인 할 경우, 로그인 영속성이 안 되는데 어떻게 해결해야 하나요 ?
SecurityConfig 클래스에서 @Bean 으로 등록한 UserDetailsService 클래스는 http.userDetailsService(userDetailsService) 이런식으로 설정하지 않는데, 그 이유를 알 수 있을까요 ?? 커스텀하게 만든 UserDetailsService 즉, FormUserDetailsService 를 사용하기 위해서는 http.userDetailsService(userDetailsService) 이런식으로 설정을 해야된다고 강의에 설명되어 있었습니다. 근데, SecurityConfig 클래스에서 @Bean 으로 등록한 UserDetailsService 클래스도 걀국 우리가 직접 커스텀하게 만든것이지 않나요..? 그러면 이클래스도 http.userDetailsService(userDetailsService) 이런식으로 설정을 해야할거 같은데 안해도 정상적으로 작동하는 이유가 궁금합니다 !!
안녕하세요. 강사님. 강의 외적인 내용이지만, 질문 좀 드리겠습니다. JWT로 로그인하는 스프링 서버를 만들었는데요. 클라우드에 올린 서버가 포스트맨의 POST 형식의 로그인 요청을 수행한 뒤, 동일한 url의 GET 요청으로 Redirect 되는 현상을 발견했습니다. 스프링 서버를 로컬에서 띄우는 경우에는 발생하지 않습니다. 강의를 전부 듣지는 않았지만, FormLogin, HttpBasic를 모두 비활성화해도 로그인 이후에 Redirect가 발생하나요? Redirect를 안하고 싶은 경우는, 어떻게 설정하면 될까요? JwtFilter의 doFilter 로직에 AuthenticationSuccessHandler 구현체를 만들어서 처리하면 되는 것까지 확인했습니다.
섹션 5의 세션 고정 보호 강의 실습 부분을 보면, 루트경로(/) 로 요청했을때도 응답에 세션아이디가 저장된 쿠기가 날라왔습니다. 즉, 세션 생성 정책이 디폴트( ifRequired ) 인데 서버에 세션이 생성된 것인데, 혹시 세션이 어느부분에서 생성되었는지 알수 있을까요..?? ++ 추가)) 섹션 5의 SessionManagementFilter / ConcurrentSessionFilter - 2 강의를 보니 .maximumSessions() 설정을 해야만 세션관련 작업을 하는 필터들이 정상적으로 등록된다고 설명돼있는데 위의 실습은 이 설정을 하지 않아서 필터들이 등록되지 않은 걸까요..?? 근데 세션 고정 보호 적용은 어떻게 적용된건지 모르겠네요..ㅠㅠ
안녕하세요, 좋은 강의에 항상 감사드리고 있습니다. 다름이 아니고 수업자료 내 FilterChain 그림에 보면, 그냥 Filter와 DelegatingFilterProxy 가 연결되어 있으며, DelegatingFilterProxy 가 FilterChainProxy에 보안처리를 위임하고 있습니다. 한편, 코드 내에서 디버깅을 하면서 확인할 수 있는 필터는 모두 FilterChainProxy 안에 있는 필터들(강의영상에서는 16개)만 확인이 되고, DelegatingFilterProxy가 아닌 보통 서블릿 필터는 확인이 되지 않는 것 같습니다. DelegatingFilterProxy가 Spring에서 Filter을 사용할 수 있도록 하는 역할을 한다고 말씀하신 것으로 보아 다른 Filter 들은 Spring 코드 내에서 어떤 역할(Authentication인지 등..)을 하는 지 확인할 수 없는 것인지요? 또한 코드 내에서 확인이 안된다면 Tomcat 등 WAS 자체의 스펙 내에서 확인이 되는 건가요? 감사합니다.
안녕하세요. 아직 강의를 듣는 초반입니다. 미리 기능의 가능 여부가 궁금하여 여쭤봅니다. 클라이언트의 요청을 필터의 설정에 따라 인증/인가 등을 판단하는데요. 필터에 설정하는 값들을 DB 또는 파일 등에 넣어 놓고 실시간으로 동적으로 요청이 올때의 값을 읽어와서 필터링 하는것도 혹시 가능할지 궁금하여 여쭤봅니다. 설정이 초기에만 로드되어 계속 사용 되는 것인지 아니면 매 요청시에 설정을 확인하여 적용하는 것인지 매 요청시에 설정을 확인하면 해당 요청시에 값을 동적으로 읽어 와서 적용시킬 수 있지 않을까 싶은 생각에서 가능한지 궁금합니다.
안녕하세요 선생님, 제가 읽은 spring security 문서와 제공해주신 ppt 의 내용에 약간 다른 점이 있어서 질문드립니다. [인증 관리자 - AuthenticationManager - 1] 강의 20:54 에 나오는 ppt 에는 CustomAuthenticationFilter 를 @Bean 으로 등록하라고 나옵니다. 그런데 제가 읽은 spring security 문서에서는 spring security 전용 Filter 는 단순히 @Bean 으로만 등록하면 servlet container 에 의해서 자동으로 Filter 로 등록되버리기 때문에 FilterRegistrationBean 까지 사용해서 이를 우회하라는 글을 본적이 있습니다. 참고: Architecture :: Spring Security 혹시 ppt 오타일까요?
안녕하세요 강의 잘 보고 있습니다. 저는 지금 Rest API서버를 생성하고 인증을 하는 방식은 session으로 하고 session 저장소를 Redis로 옮겨 구현하고자 합니다. 그러나 강의와는 다르게 @EnableRedisHttpSession 어노테이션을 추가해도 Redis에 저장이 되지 않는 오류가 있는데 이를 어떻게 해결해야할지 모르겠어 질문을 드립니다. Redis가 아닌 Memory에 저장을 하였을때는 정상 동작하였으며 디버깅을 통해 문제의 원인을 파악해본 결과 SecurityContextImpl 객체에 대한 직렬화를 수행해주는 클래스가 존재하지 않아 오류가 발생하는 듯 합니다. 혹시 이 문제에 대해 도움을 받을 수 있을까요? 문제상황을 작성해놓은 포스팅과 프로젝트의 압축파일을 첨부해드리도록 하겠습니다. 추가로 프로젝트 환경은 로컬에서 진행하였으며 H2 DB와 Redis를 사용하였습니다. https://goto-pangyo.tistory.com/286 https://drive.google.com/file/d/1DccNwJWmUPBpe3KwsqxPp_VpYIAQRRaR/view?usp=sharing
@Controller의 url들을 통해 원하는 화면들을 전환하는 방식으로 일을 진행 중 입니다. Security를 적용하려 보니 강의에는 @RestController뿐인데 @RestController는 페이지 전환에 적합하지 않다고 알고 있습니다. 그렇다면 @Controller에 Security를 적용할 수 없는겁니까? 그리고 java version 17을 사용하셨는데 '왜 17을 사용하셨는지'와 '최신 버전인 22를 사용하면 어떠한 문제가 발생하는지'궁금합니다.
@Bean public AuthenticationManager authenticationManager(AuthenticationConfiguration configuration) throws Exception { return configuration.getAuthenticationManager(); } 위 처럼 Bean 으로 등록하게되면 내부 메서드에서 Bean으로 등록된 Builder를 통해 등록하는거 까지는 이해했는데요. 근데 여기서 setShareObject와 같은게 없는데 return http.build(); 빌드하게되면 HttpSecurity 메서드의 @Override protected void beforeConfigure() throws Exception { if (this.authenticationManager != null) { setSharedObject(AuthenticationManager.class, this.authenticationManager); } else { ObservationRegistry registry = getObservationRegistry(); AuthenticationManager manager = getAuthenticationRegistry().build(); if (!registry.isNoop() && manager != null) { setSharedObject(AuthenticationManager.class, new ObservationAuthenticationManager(registry, manager)); } else { setSharedObject(AuthenticationManager.class, manager); } } } 가 호출되어 여기서 else 조건을 타 getSharedObject 로 AuthenticationManagerBuilder 빌더 클래스를 다시 꺼내와서 빌드를 하는데 이렇게 되면 http.build 과정의 인증관리자와 스프링컨테이너에 있는 인증관리자는 서로 다른건가요? 같다면 우리가 등록한 Bean이 build 과정에서 나올것같은데 못찾겠습니다 ㅠㅠ..
안녕하세요, 24:00 에 말씀해주시는 SecurityContextHolderStrategy 사용하기부분에 기본방식과 변경방식 설명해주시는 부분에서 이해가 안되는 부분이 생겨 질문드립니다. 기존방식과 변경방식의 구현된 소스코드를 보니 내부에서(SecurityContextHolder.crateEmptyContext() 내부) 도 결론적으로는 strategy.createEmptyContext() 를 delegate 하는 방식으로 호출 되는것을 보았습니다. 6.x, 5.x, 4.x 모두 동일한듯합니다. /** * Allows retrieval of the context strategy. See SEC-1188. * @return the configured strategy for storing the security context. */ public static SecurityContextHolderStrategy getContextHolderStrategy() { return strategy; } /** * Delegates the creation of a new, empty context to the configured strategy. */ public static SecurityContext createEmptyContext() { return strategy.createEmptyContext(); } AbstractAuthenticationProcessingFilter 쪽에서 successfulAuthentication 쪽에 로직dl 6.x, 5.7 이하 버전 대가 다른단것은 확인했는데 /** * Puts the <code>Authentication</code> instance returned by the authentication * manager into the secure context. */ protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, Authentication authResult) throws IOException, ServletException { this.logger.debug(LogMessage.format("Authentication success: %s", authResult)); SecurityContext context = this.securityContextHolderStrategy.createEmptyContext(); context.setAuthentication(authResult); this.securityContextHolderStrategy.setContext(context); this.securityContextRepository.saveContext(context, request, response); if (this.eventPublisher != null) { this.eventPublisher.publishEvent(new InteractiveAuthenticationSuccessEvent(authResult, this.getClass())); } if (this.authenticationSuccessHandler != null) { this.authenticationSuccessHandler.onAuthenticationSuccess(request, response, authResult); } } /** * Puts the <code>Authentication</code> instance returned by the authentication * manager into the secure context. */ protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, Authentication authResult) throws IOException, ServletException { if (logger.isDebugEnabled()) { logger.debug("Authentication success: " + authResult); } SecurityContextHolder.getContext().setAuthentication(authResult); // Fire event if (this.eventPublisher != null) { eventPublisher.publishEvent(new InteractiveAuthenticationSuccessEvent( authResult, this.getClass())); } if (authenticationSuccessHandler != null) { authenticationSuccessHandler.onAuthenticationSuccess(request, response, authResult); } } 추측건데 strategy 쪽을 세팅할수있는 부분이 추가됨에따라 달라진 부분이라 생각이 되어 이부분도 말씀하신 의도와는 다를듯하여 /** * Sets the {@link SecurityContextHolderStrategy} to use. The default action is to use * the {@link SecurityContextHolderStrategy} stored in {@link SecurityContextHolder}. * * @since 5.8 */ public void setSecurityContextHolderStrategy(SecurityContextHolderStrategy securityContextHolderStrategy) { Assert.notNull(securityContextHolderStrategy, "securityContextHolderStrategy cannot be null"); this.securityContextHolderStrategy = securityContextHolderStrategy; } 경쟁조건 때문이라고 설명하신 부분에서 말씀하시는 의도를 다시 한번 알수있을까요.