inflearn logo
강의

강의

N
챌린지

챌린지

멘토링

멘토링

N
클립

클립

로드맵

로드맵

지식공유

묻고 답해요

173만명의 커뮤니티!! 함께 토론해봐요.

마지막 강의 질문드립니다.

미해결

스프링부트 시큐리티 & JWT 강의

여기서 super.doFilterInternal(request, response, chain); 위 문장을 지워주셨는데 해당 줄을 지우면 회원가입 로직이 컨트롤러를 타지 않습니다. 회원가입은 /join으로 매핑되어 있는데 JwtAuthorizationFilter의 doFilterInternal() 메소드를 타고 jwtHeader 값이 없기 때문에 return을 만나 컨트롤러를 타지 않는 것 같습니다. 반대로 super.doFilterInternal(request, response, chain); 주석 해제하면 회원가입 로직은 진행됩니다만 마지막 강의에서 인증이 되지 않는 문제가 계속 일어나고 있습니다! SecurityConfig 클래스 코드입니다! 부족한 지식으로 제 생각이 다를 수 있지만 문제를 해결하지 못하고 있어 질문 드립니다ㅠㅠ

  • spring
  • spring-security
  • jwt
유영훈 댓글 2 좋아요 0 조회수 313

세션 클러스터링을 한 이후 동시로그인 제한이 안되는데요

미해결

스프링 시큐리티

안녕하십니까 강사님 강의를 듣고 여기 커뮤니티에 나름 최신 소스 받아서 시큐리티 구현중인데요 이중화 환경에서 톰캣을 통해 세션을 공유하는것까지는 되었는데요 동시 로그인제한이 안되는데 추가적인 설정을 무엇을 해야할지 모르겠는데 도움좀 받을수 있을까요? 스프링 2.7.10 스프링 시큐리티 5.7.7 // 시큐리티 설정부분 @Slf4j @RequiredArgsConstructor @EnableWebSecurity @Configuration public class WebSecurityConfig { private final MemberRepository memberRepository; @Bean public SecurityFilterChain defaultSecurityFilterChain(HttpSecurity http) throws Exception { // 경로 설정 http. authorizeRequests() .antMatchers().permitAll() .anyRequest().authenticated() ; // 동시 로그인 제한을 설정 http .sessionManagement() .maximumSessions(1) .expiredUrl("/error/expired") .and().sessionCreationPolicy(SessionCreationPolicy.ALWAYS) ; http.logout() .logoutRequestMatcher(new AntPathRequestMatcher("/logout")) .invalidateHttpSession(true) .clearAuthentication(true) .deleteCookies("JSESSIONID") ; // 로그인... 인증 권한 체크... // 로그인 return http.build(); } /** * 여기에 Authentication 을 설정하도록 */ @Bean AuthenticationManager authenticationManager(AuthenticationConfiguration authConfiguration) throws Exception { return authConfiguration.getAuthenticationManager(); } @Bean public static PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } } // 톰캣 클러스터링 부분 ( https://happy-jjang-a.tistory.com/155를 참조했습니다.) @Configuration public class TomcatClusterConfig implements WebServerFactoryCustomizer<TomcatServletWebServerFactory> { @Override public void customize(final TomcatServletWebServerFactory factory) { factory.addContextCustomizers(new TomcatClusterContextCustomizer()); } } class TomcatClusterContextCustomizer implements TomcatContextCustomizer { @Override public void customize(final Context context) { context.setDistributable(true); DeltaManager manager = new DeltaManager(); manager.setExpireSessionsOnShutdown(false); manager.setNotifyListenersOnReplication(true); context.setManager(manager); configureCluster((Engine) context.getParent().getParent()); } private void configureCluster(Engine engine) { //cluster SimpleTcpCluster cluster = new SimpleTcpCluster(); cluster.setChannelSendOptions(6); //channel GroupChannel channel = new GroupChannel(); //membership setting McastService mcastService = new McastService(); mcastService.setAddress("228.0.0.4"); mcastService.setPort(45564); // TCP&UDP port 오픈 필요 mcastService.setFrequency(500); mcastService.setDropTime(3000); channel.setMembershipService(mcastService); //receiver NioReceiver receiver = new NioReceiver(); receiver.setAddress("auto"); receiver.setMaxThreads(6); receiver.setPort(5000); // TCP port 오픈 필요 channel.setChannelReceiver(receiver); //sender ReplicationTransmitter sender = new ReplicationTransmitter(); sender.setTransport(new PooledParallelSender()); channel.setChannelSender(sender); //interceptor channel.addInterceptor(new TcpPingInterceptor()); channel.addInterceptor(new TcpFailureDetector()); channel.addInterceptor(new MessageDispatchInterceptor()); cluster.addValve(new ReplicationValve()); cluster.addValve(new JvmRouteBinderValve()); cluster.setChannel(channel); cluster.addClusterListener(new ClusterSessionListener()); engine.setCluster(cluster); } }

  • java
  • spring-boot
  • spring-security
znznwkdrns 댓글 1 좋아요 0 조회수 1292

Count 쿼리 발생에 대해 궁금합니다.

미해결

호돌맨의 요절복통 개발쇼 (SpringBoot, Vue.JS, AWS)

안녕하세요 호돌맨님 ! 질문이 있습니다 !! Pageable 을 사용해서 페이징 구현 시 Full Scan 을 하기 위해 Count 쿼리가 발생하는걸 확인했는데, Pageable 에서는 페이징 처리를 위해 총 데이터의 개수를 파악해야 하기 때문이니까 Count 쿼리가 필요한거고 Querydsl 은 직접 limit 값, offset 값을 지정하기 때문에 Full Scan 할 필요가 없으니 Count 쿼리가 필요없는게 맞을까요 ?

  • vue.js
  • aws
  • spring-boot
  • jpa
  • spring-security
전병준 댓글 2 좋아요 0 조회수 568

AOP가 적용되지않습니다.

미해결

스프링 입문 - 코드로 배우는 스프링 부트, 웹 MVC, DB 접근 기술

학습하는 분들께 도움이 되고, 더 좋은 답변을 드릴 수 있도록 질문전에 다음을 꼭 확인해주세요. 1. 강의 내용과 관련된 질문을 남겨주세요. 2. 인프런의 질문 게시판과 자주 하는 질문(링크)을 먼저 확인해주세요. (자주 하는 질문 링크: https://bit.ly/3fX6ygx) 3. 질문 잘하기 메뉴얼(링크)을 먼저 읽어주세요. (질문 잘하기 메뉴얼 링크: https://bit.ly/2UfeqCG) 질문 시에는 위 내용은 삭제하고 다음 내용을 남겨주세요. ========================================= [질문 템플릿] 1. 강의 내용과 관련된 질문인가요? (예/아니오) 2. 인프런의 질문 게시판과 자주 하는 질문에 없는 내용인가요? (예/아니오) 3. 질문 잘하기 메뉴얼을 읽어보셨나요? (예/아니오) [질문 내용] "package hello.hellospring.aop; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.springframework.stereotype.Component; @Component @Aspect public class TimeTraceAop { @Around("execution(* hello.helloSpring..*(..))") public Object execute(ProceedingJoinPoint joinPoint) throws Throwable { long start = System. currentTimeMillis (); System. out .println("START : " + joinPoint.toString()); try { return joinPoint.proceed(); } finally { long finish = System. currentTimeMillis (); long timeMs = finish - start; System. out .println("END : " + joinPoint.toString()+ " " + timeMs + "ms"); } } }" TimeTraceAop 클래스를 작성한 이후에 실행을 시켜보아도 수업처럼 START END 부분이실행되지 않습니다. 단순 스프링 실행화면만 보이는데 어디가 문제일까요?

  • java
  • spring
  • mvc
  • spring-boot
digeuthi 댓글 3 좋아요 0 조회수 2231

@Deprecated

해결됨

실전! Querydsl

안녕하세요 queryDsl의 기본 문법에 대해서 듣고 있는데요. 현재 기준, fetchResults(), fetchCount() 가 deprecated 되었네요.(자바11, springboot 2.7 버전에 맞는 queryDsl) 강의 끝부분에서 말씀하신, 복잡한 페이징 & 쿼리 부분에서는 coun와 select 쿼리가 다르니까 따로 작성해서 해야된다는 말씀 것과 연관되어서 그런 것 맞을까요? 그러면 @Deprecated 된 현재는 fetchResults(), fetchCount() 는 사용을 지양하고 별개의 쿼리로 각각의 값들을 얻어 조합해서 response 해주는 것이 맞죠?

  • java
  • jpa
highjune 댓글 1 좋아요 3 조회수 1573

[5강] admin, manager로 로그인시 403에러

미해결

스프링부트 시큐리티 & JWT 강의

안녕하세요! 강의 잘 듣고 있습니다. 다름이 아니라 5강을 진행하던 중, DB에서 ROLE_ADMIN, ROLE_MANAGER로 바꾸어 주었는데도 403에러가 떠서 질문드립니다. <SecurityConfig> package com.example.SpringSecurity.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security .config.annotation.method.configuration.EnableMethodSecurity; import org.springframework.security.config.annotation.web.builders .HttpSecurity; import org.springframework.security .config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security .config.annotation.web.configurers.AbstractHttpConfigurer; import org.springframework.security .crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security .web.SecurityFilterChain; @Configuration @EnableWebSecurity // 스프링 시큐리티 필터가 스프링 필터체인에 등록이 됨. @EnableMethodSecurity(securedEnabled = true) public class SecurityConfig { @Bean public BCryptPasswordEncoder encodePwd(){ return new BCryptPasswordEncoder(); } @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { return http .csrf(AbstractHttpConfigurer::disable) // 사이트 위변조 요청 방지 .authorizeHttpRequests((authorizeRequests) -> { // 특정 URL에 대한 권한 설정. authorizeRequests.requestMatchers("/user/**").authenticated(); authorizeRequests.requestMatchers("/manager/**") .hasAnyRole("ADMIN", "MANAGER"); // ROLE_은 붙이면 안 된다. hasAnyRole()을 사용할 때 자동으로 ROLE_이 붙기 때문이다. authorizeRequests.requestMatchers("/admin/**") .hasRole("ADMIN"); // ROLE_은 붙이면 안 된다. hasRole()을 사용할 때 자동으로 ROLE_이 붙기 때문이다. authorizeRequests.anyRequest().permitAll(); }) .formLogin((formLogin) -> { formLogin .loginPage("/loginForm") // 권한이 필요한 요청은 해당 url로 리다이렉트 .loginProcessingUrl("/login") // login 주소가 호출되면 시큐리티가 낚아채서 대신 로그인을 해준다. .defaultSuccessUrl("/"); //로그인 성공시 /주소로 이동 }) .build(); } } <IndexController> package com.example.SpringSecurity.controller; import com.example.SpringSecurity.model.User; import com.example.SpringSecurity.repository.UserRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security .crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.ResponseBody; @Controller public class IndexController { @Autowired private UserRepository userRepository; @Autowired private BCryptPasswordEncoder bCryptPasswordEncoder; @GetMapping({"/",""}) public String index(){ return "index"; } @GetMapping("/user") public @ResponseBody String user(){ return "user"; } @GetMapping("/admin") public @ResponseBody String admin(){ return "admin"; } @GetMapping("/manager") public @ResponseBody String manager(){ return "manager"; } @GetMapping("/loginForm") public String loginForm(){ return "loginForm"; } @GetMapping("/joinForm") public String joinForm(){ return "joinForm"; } @PostMapping("/join") public String join(User user){ System. out .println(user); user.setRole("ROLE_USER"); String rawPassword = user.getPassword(); String encPassword = bCryptPasswordEncoder.encode(rawPassword); user.setPassword(encPassword); userRepository.save (user); // 패스워드가 암호화가 안되어있으면, 회원가입은 잘되나 Security를 이용해 로그인 할 수 없다. return "redirect:/loginForm"; } @GetMapping("/info") public @ResponseBody String info(){ return "개인정보"; } } 코드는 이러합니다. SecurityConfig는 v6이어서 수정하였습니다. 에러 해결에 도움 부탁드려요,, 항상 좋은 강의 감사합니다!

  • spring
  • spring-security
서영선 댓글 2 좋아요 0 조회수 937

Controller Test 시 @WebMvcTest 사용 관련 질문입니다.

미해결

호돌맨의 요절복통 개발쇼 (SpringBoot, Vue.JS, AWS)

안녕하세요 호돌맨님 :) 좋은 강의 늘 감사드립니다. Controller Test 할 때 질문이 있습니다. 강의에서 호돌맨님께서는 @SpringBootTest 사용하셨는데 저는 한 번 @WebMvcTest를 사용해보고 있습니다. 그러다보니 문제가 하나 발생을 하더라구요. 우선 PostController 쪽 코드를 보여드리겠습니다. @GetMapping("/posts") public ApiResponse<List<PostResponse>> getAll(@ModelAttribute PostSearch postSearch) { List<PostResponse> posts = postService.getAllPost(postSearch); return ApiResponse.ok(posts); } 보시면 게시글을 전체 조회하는 이 메서드의 경우에는 인증이 따로 필요없이 바로 조회가 되게 했는데요. Insomnia 라는 프로그램을 통해서 테스트했을 때 따로 인증하지 않아도 전체 조회 요청이 성공하는 것을 확인했습니다. 그런데 테스트코드를 작성할 때 인증 처리를 해주지 않으면 계속해서 401 에러가 발생을 하더라구요. @DisplayName("게시글을 전체 조회한다.") @CustomMockUser //todo 실제로는 인증이 필요없는데도 테스트 통과를 위해서 인증 처리를 해줘야 하는 것인가? @Test void getAllPosts() throws Exception { // given List<Post> posts = IntStream .range(1, 5) .mapToObj(i -> Post.of(FREE, i + "번 제목입니다.", i + "번 내용입니다.")) .toList(); List<PostResponse> response = changePostListToPostResponseList(posts); // when when(postService.getAllPost(any())).thenReturn(response); //then mockMvc.perform( MockMvcRequestBuilders.get("/api/posts") ) .andDo(MockMvcResultHandlers.print()) .andExpect(MockMvcResultMatchers.jsonPath("$.code").value(200)) .andExpect(MockMvcResultMatchers.jsonPath("$.message").value("OK")) .andExpect(MockMvcResultMatchers.jsonPath("$.status").value("OK")) .andExpect(MockMvcResultMatchers.jsonPath("$.data").isArray()) .andExpect(MockMvcResultMatchers.status().isOk()); } @CustomMockUser 어노테이션을 붙여줘야 테스트 통과가 되는 상황입니다. 실제 원하는 기능은 인증없이 전체 조회 되게 하는 것이 목표인데 테스트 통과를 위해서 @CustomMockUser 어노테이션을 붙여주는 것이 올바른 테스트인지 궁금합니다! 혹시 이게 @WebMvcTest와 관련없는 다른 문제라면 알려주시면 한 번 제가 더 찾아보겠습니다..!

  • vue.js
  • aws
  • spring-boot
  • jpa
  • spring-security
비가싫어요 댓글 2 좋아요 0 조회수 1088

강의 ppt 그림 질문입니다.

미해결

스프링 시큐리티

강의안 ppt를 보면서 진행중인데 그림이 상이해서 헷갈려 질문드립니다. 67번 슬라이드에서 인증 결과를 저정하는 그림에서는 ThreadLocal > SecurityContextHolder > SecurityContext 처럼 표기되어있는데 74번 슬라이드에서는 SecurityContextHolder > ThreadLocal > SecurityContext 처럼 표기되어있어서 혼란이오는데 어느 슬라이드의 그림이 맞는건가요?

  • java
  • spring-boot
  • spring-security
정동인 댓글 1 좋아요 0 조회수 358

Ajax Custom DSLs - customConfigurerAjax(HttpSecurity http) 에서 loginProcessingUrl(/api/login) 처리할 때 null

해결됨

스프링 시큐리티

customConfigurerAjax(HttpSecurity http) 에서 loginProcessingUrl("/api/login") 처리할 때 private void customConfigurerAjax(HttpSecurity http) throws Exception { http .apply(new AjaxLoginConfigurer<>()) .successHandlerAjax(ajaxAuthenticationSuccessHandler()) .failureHandlerAjax(ajaxAuthenticationFailureHandler()) .setAuthenticationManager(authenticationManager(authenticationConfiguration)) .loginProcessingUrl("/api/login") ; } AbstractAuthenticationFilerConfigurer 클래스의 loginProcessingUrl을 호출하던데 여기서 authFilter 가 null 이어서 예외가 발생하는데 public T loginProcessingUrl(String loginProcessingUrl) { this.loginProcessingUrl = loginProcessingUrl; this.authFilter.setRequiresAuthenticationRequestMatcher(createLoginProcessingUrlMatcher(loginProcessingUrl)); return getSelf(); } 어떻게 해결해야할지 모르겠습니다. ㅠㅠ https://github.com/pdh9311/core-spring-security 추가로 ajax security 시작한 이후로 localhost:8080 으로 접속하니까 화면이 안나오고 401 에러가 발생하는데 어디가 문제인지 모르겠습니다. ㅠㅠ

  • java
  • spring-boot
  • spring-security
cozyrust 댓글 2 좋아요 0 조회수 493

Cannot snapshot 오류가 뜹니다.

해결됨

스프링 입문 - 코드로 배우는 스프링 부트, 웹 MVC, DB 접근 기술

학습하는 분들께 도움이 되고, 더 좋은 답변을 드릴 수 있도록 질문전에 다음을 꼭 확인해주세요. 1. 강의 내용과 관련된 질문을 남겨주세요. 2. 인프런의 질문 게시판과 자주 하는 질문(링크)을 먼저 확인해주세요. (자주 하는 질문 링크: https://bit.ly/3fX6ygx) 3. 질문 잘하기 메뉴얼(링크)을 먼저 읽어주세요. (질문 잘하기 메뉴얼 링크: https://bit.ly/2UfeqCG) 질문 시에는 위 내용은 삭제하고 다음 내용을 남겨주세요. ========================================= [질문 템플릿] 1. 강의 내용과 관련된 질문인가요? (예/아니오) 2. 인프런의 질문 게시판과 자주 하는 질문에 없는 내용인가요? (예/아니오) 3. 질문 잘하기 메뉴얼을 읽어보셨나요? (예/아니오) [질문 내용] 여기에 질문 내용을 남겨주세요. 코드를 모두 정상적으로 작성하였는데 Cannot snapshot C:\Users\이름\OneDrive\바탕 화면\App\Programming\study\inflearn\Spring\forBeginner\hello-spring\build\test-results\test\binary\output.bin: not a regular file 이런 오류가 뜹니다.

  • java
  • spring
  • mvc
  • spring-boot
재밌는코딩 댓글 1 좋아요 0 조회수 1628

세션 삭제

미해결

스프링 시큐리티

안녕하세요 시큐리티 이번에 처음 공부하게 되었는데 강의가 너무 좋네요 질문은 임의로 세션을 삭제하면 다시 인증을 받아야 하는데 SecurityContext에는 인증 정보가 들어있지 않나요 ?

  • java
  • spring-boot
  • spring-security
H K 댓글 2 좋아요 0 조회수 448

영속성 컨텍스트에 대해 질문이 있습니다.

미해결

자바 ORM 표준 JPA 프로그래밍 - 기본편

https://www.inflearn.com/questions/789381/%EC%97%94%ED%8B%B0%ED%8B%B0-%EB%A7%A4%EB%8B%88%EC%A0%80-%EB%8F%99%EC%8B%9C%EC%84%B1 위에 질문과 답변을 봤을때는 엔티티매니저가 달라도 트랜잭션이 같으면 같은 영속성컨텍스트를 사용한다고 되어있습니다. 하지만 이 부분이 실제로 어떻게 이뤄질 수 있는것인지 이해되지 않습니다. 코드로 어떻게 되어져 있는지 찾아볼 수 있을까요? 제가 찾아본 내용으로는 SessionImpl이라는 엔티티매니저 구현체에 아래 처럼 엔티티매니저를 넣어서 영속성컨텍스트를 생성하는 코드를 볼 수 있었습니다. 그럼 영속성 컨텍스트는 따로 만들어지는게 아닌가? 라는 생각도 하게되었습니다. protected StatefulPersistenceContext createPersistenceContext() { return new StatefulPersistenceContext( this ); } 트랜잭션에 따라 영속성 컨텍스트가 공유되고 스레드마다 영속성 컨텍스트가 어떻게 나눠질 수 있는지 궁금합니다. 그리고 영속성컨텍스트는 프록시라도 Bean으로 등록되는데 실제 동작을 하는건 원본객체일테고 그럼 그 객체이 있는 영속성컨텍스트를 공유하게 되는것은 아닌가? 의문이 들었습니다. 질문을 정리하겠습니다. 트랜잭션에 따라 영속성 컨텍스트가 어떻게 공유될 수 있나요?(확인할 수 있는코드나 기술이 있다면 말씀해주시면 감사하겠습니다.) Bean으로 등록된 엔티티매니저가 다른 상태를 유지할 수 있는 방법이 무엇인가요? 프록시라해도 원본객체를 통해 동작하는게 아닌가요? 영속성컨텍스트는 프록시라도 Bean으로 등록되는데 실제 동작을 하는건 원본객체일테고 그럼 그 객체이 있는 영속성컨텍스트를 공유하게 되는것은 아닌가요? 바보같은 질문일 수 있지만 답변해주시면 너무 감사하겠습니다.

  • java
  • jpa
YOGURT 댓글 2 좋아요 0 조회수 878

엔티티매니저의 대해 질문이 있습니다!

미해결

자바 ORM 표준 JPA 프로그래밍 - 기본편

EntityManager는 빈 스코프가 프록시로 설정된다고 알고있습니다. 하지만 결국은 원본 엔티티매니저를 사용하는것이라고 이해했습니다. 그러면 요청이 들어오면 엔티티매니저를 사용하는데 엔티티매니저 내에 영속성 컨텍스트가 있고 싱글톤으로 유지된다면 영속성컨텍스트가 다른 요청이랑 공유되는게 아닌가요? 싱글톤으로 등록되어 있는데 영속성컨텍스트가 공유되지 않는 이유가 궁금합니다. 엔티티매니저가 빈인데 어떻게 요청마다 생성되는것인지 궁금합니다.

  • java
  • jpa
YOGURT 댓글 1 좋아요 1 조회수 430

4-2 강의에서 소스 확인 부탁드립니다.

해결됨

스프링 시큐리티

- 학습 관련 질문을 남겨주세요. 상세히 작성하면 더 좋아요! - 먼저 유사한 질문이 있었는지 검색해보세요. - 서로 예의를 지키며 존중하는 문화를 만들어가요. - 잠깐! 인프런 서비스 운영 관련 문의는 1:1 문의하기를 이용해주세요. 4-2 강의를 보고 있는데 해당 이전 강의에서는 authenticationEntryPoint, LoginUrlAuthenticationEntryPoint, FormAccessDeniedHandler 에 대한 설명 없었는데 4-2 강의에서는 소스에 해당 내용으로 바뀌어 있습니다. 누락된 것인지 아니면 제가 못 찾는 것인지 확인 부탁드립니다.

  • java
  • spring-boot
  • spring-security
파이프라인 댓글 1 좋아요 0 조회수 354

Object 클래스의 clone() 메서드 질문

미해결

자바(Java) 알고리즘 문제풀이 입문: 코딩테스트 대비

Object 클래스의 clone() 메서드는 깊은 복사가 아니라 얕은 복사로 알고 있습니다. 강의에서의 선생님의 말씀대로 clone() 메서드는 깊은 복사가 맞나요?

  • java
  • 코딩-테스트
재영 댓글 2 좋아요 0 조회수 364

스프2탄 PPT파일은 없나요?

미해결

스프링 프레임워크는 내 손에 [스프2탄]

강의 설명해주시는거 PPT파일 확인하면서 보려고하는데 PPT파일은 없는거같아서요

  • spring
  • jquery
  • mvc
  • jpa
  • spring-security
최현제 댓글 1 좋아요 0 조회수 546

MySql Lock을 사용하지 않는 이유

미해결

실습으로 배우는 선착순 이벤트 시스템

강의에서 설명해주시기로는 쿠폰 개수를 가져오는 것부터 쿠폰 생성까지 lock을 걸어야 한다고 설명 주셨는데 이전 강의인 재고 관리 이슈와는 다르게 row가 아닌 table에 lock을 걸기 때문에 성능 이슈가 발생한다고 보면 될까요?

  • java
  • docker
  • spring-boot
  • kafka
  • redis
데자와아 댓글 2 좋아요 0 조회수 1236

스프링 시큐리티 멀티 로그인 관련 질문드립니다.

미해결

스프링 시큐리티

@Configuration @EnableWebSecurity public class SecurityConfig { @Bean public SecurityFilterChain adminfilterChain(HttpSecurity http) throws Exception { http.authorizeRequests() .requestMatchers("/admin/**").hasRole("ADMIN") .anyRequest().authenticated() .and() .httpBasic() ; return http.build(); } @Bean static final public InMemoryUserDetailsManager kk() { //DB연동을 안할 경우, 테스트 용으로 하는 것이다. UserDetails user = User.withDefaultPasswordEncoder() .username("user") .password("1111") .roles("USER") .build(); UserDetails admin = User.withDefaultPasswordEncoder() .username("admin") .password("1111") .roles("ADMIN") .build(); return new InMemoryUserDetailsManager(user, admin); } } @Configuration class config2 { @Bean public SecurityFilterChain userfilterChain(HttpSecurity http) throws Exception { http.authorizeRequests() .requestMatchers("/user/**").hasRole("USER") .anyRequest().authenticated() .and() .formLogin() ; return http.build(); } } 스프링 시큐리티가 최근부터 Bean으로 설정을 해야하며, 강의에서 나온 antmatchers()와 같은 함수명이 바뀌어 구글링을 하며 만들어보고자 도전해보고 있습니다. 해당 강의 중 "다중 보안 설정"에 대한 내용과 유사하게 구현해보고자 하였으나, 마음처럼 되지 않아 질문을 남김니다. 제가 구현하고 싶은 형태는 localhost:8080/user >> formLogin() 페이지로 이동하게 되고, 이와 다르게 localhost:8080/admin >> httpBasic () 페이지로 이동하도록 구현하고자 합니다. 하지만, 생각과는 다르게 admin 경로가 처리가 안되는 것을 확인하였습니다. 이에 대해 조언을 구하고자 합니다.

  • java
  • spring-boot
  • spring-security
김상욱 댓글 1 좋아요 0 조회수 1286

[Google oauth2 관련] The dependencies of some of the beans in the application context form a cycle

미해결

스프링부트 시큐리티 & JWT 강의

에러 메시지는 아래와 같습니다. *************************** APPLICATION FAILED TO START *************************** Description: The dependencies of some of the beans in the application context form a cycle: ┌─────┐ | oauth2UserService defined in file [D:\GooGoo\out\production\classes\eunhye\GooGoo\config\oauth\Oauth2UserService.class] ↑ ↓ | securityConfig defined in file [D:\GooGoo\out\production\classes\eunhye\GooGoo\config\security\SecurityConfig.class] └─────┘ Action: Relying upon circular references is discouraged and they are prohibited by default. Update your application to remove the dependency cycle between beans. As a last resort, it may be possible to break the cycle automatically by setting spring.main.allow-circular-references to true. Process finished with exit code 1 oauth2UserService와 securityConfig가 cycle을 이루고 있다. 뭔가 구조가 잘못됐다는 것을 알 수 있었습니다만... 전 강의 잘 듣고 잘 코드 쳤다고 생각이 되거든요ㅠ 스스로를 의심하며 아무리 코드를 쳐다봐도 잘못된 점을 모르겠어서 질문 올립니다. 다음은 관련된 코드들입니다. Oauth2UserService.java package eunhye.GooGoo.config.oauth; import eunhye.GooGoo.config.security.SecurityDetails; import eunhye.GooGoo.dto.UserDTO; import eunhye.GooGoo.entity.UserEntity; import eunhye.GooGoo.entity.UserRole; import eunhye.GooGoo.repository.UserRepository; import lombok.RequiredArgsConstructor; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.oauth2.client.userinfo.DefaultOAuth2UserService; import org.springframework.security.oauth2.client.userinfo.OAuth2UserRequest; import org.springframework.security.oauth2.core.OAuth2AuthenticationException; import org.springframework.security.oauth2.core.user.OAuth2User; import org.springframework.stereotype.Service; @Service @RequiredArgsConstructor public class Oauth2UserService extends DefaultOAuth2UserService { private final UserRepository userRepository; private final PasswordEncoder passwordEncoder; // 구글로부터 받은 userRequest 데이터에 대해 후처리하는 함수 @Override public OAuth2User loadUser(OAuth2UserRequest userRequest) throws OAuth2AuthenticationException{ OAuth2User oauth2User = super.loadUser(userRequest); // 회원가입 강제 진행 String provider = userRequest.getClientRegistration().getClientId(); String providerId = oauth2User.getAttribute("sub"); String userNickname = provider+"_"+providerId; String userEmail = oauth2User.getAttribute("email"); String userPassword = passwordEncoder.encode("겟인데어"); UserRole authority = UserRole.USER; UserEntity userEntity = userRepository.findByUserEmail(userEmail); if(userEntity == null){ userEntity = UserEntity.builder() .userNickname(userNickname) .userEmail(userEmail) .userPassword(userPassword) .authority(authority) .provider(provider) .providerId(providerId) .build(); userRepository.save(userEntity); } return new SecurityDetails(userEntity, oauth2User.getAttributes()); } } SecurityConfig.java package eunhye.GooGoo.config.security; import eunhye.GooGoo.config.oauth.Oauth2UserService; import lombok.RequiredArgsConstructor; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; 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.authentication.AuthenticationFailureHandler; import org.springframework.security.web.util.matcher.AntPathRequestMatcher; @Configuration @EnableWebSecurity @RequiredArgsConstructor public class SecurityConfig{ private final AuthenticationFailureHandler customFailureHandler; private final Oauth2UserService oauth2UserService; @Bean public BCryptPasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http .csrf().disable() .authorizeRequests() .antMatchers("/user/**").authenticated() .antMatchers("/admin/**").access("hasRole('ADMIN')") .anyRequest().permitAll() .and() .formLogin() .loginPage("/login") .loginProcessingUrl("/login") .defaultSuccessUrl("/home") .usernameParameter("userEmail").passwordParameter("userPassword") .failureHandler(customFailureHandler) .and() .logout() .logoutRequestMatcher(new AntPathRequestMatcher("/logout")) .logoutSuccessUrl("/login") .and().oauth2Login() .loginPage("/login").defaultSuccessUrl("/home") .userInfoEndpoint().userService(oauth2UserService); return http.build(); } } SecurityDetails.java package eunhye.GooGoo.config.security; import eunhye.GooGoo.entity.UserEntity; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import lombok.RequiredArgsConstructor; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.oauth2.core.user.OAuth2User; import java.util.ArrayList; import java.util.Collection; import java.util.Map; @Data public class SecurityDetails implements UserDetails, OAuth2User { // 일반 로그인 private final UserEntity userEntity; // OAuth 로그인 (Google) private Map<String, Object> attributes; public SecurityDetails(UserEntity userEntity){ this.userEntity = userEntity; } public SecurityDetails(UserEntity userEntity, Map<String, Object> attributes){ this.userEntity = userEntity; this.attributes = attributes; } @Override public Map<String, Object> getAttributes() { return attributes; } @Override public String getName() { return userEntity.getId()+""; } @Override public Collection<? extends GrantedAuthority> getAuthorities() { Collection<GrantedAuthority> authorities = new ArrayList<>(); authorities.add(new GrantedAuthority() { @Override public String getAuthority() { return userEntity.getAuthority().toString(); } }); return authorities; } @Override public String getPassword() { return userEntity.getUserPassword(); } @Override public String getUsername() { return userEntity.getUserEmail(); } @Override public boolean isAccountNonExpired() { return true; } @Override public boolean isAccountNonLocked() { return true; } @Override public boolean isCredentialsNonExpired() { return true; } @Override public boolean isEnabled() { return true; } } 추가적인 코드가 필요하다면 아래 깃헙 링크 참고해주세요 https://github.com/you-eun-hye/GooGoo

  • spring
  • spring-security
  • google
  • oauth2
유은혜 댓글 1 좋아요 0 조회수 922

[이진 탐색 실전 문제] 원하는 정수 찾기 편 질문

미해결

Do it! 알고리즘 코딩테스트 with JAVA

안녕하세요? 강의를 듣다가 궁금한 것이 생겨 질문 드립니다. 자바의 정렬 기본 알고리즘 시간 복잡도와 이진 탐색 시간 복잡도가 nlogn인 건 이해했는데, 코드부를 보면 이중 반복문이 나오고 있습니다. 앞 서 강의에서 반복문을 기준으로 이중 반복문이면 n의2승이라고 말씀하셨는데, 이 중 반복문을 썼는데도 nlogn이 되는 건 반복문이 진행되는 동안 절반씩 찾기 때문인가요?? 만약 이중 반복문으로 시간 복잡도가 올라간다면 이중 반복문을 쓰지 않고, 해결하는 방법을 알려주실 수 있으실까요?

  • java
  • 코딩-테스트
  • 알고리즘
댓글 1 좋아요 0 조회수 520

인기 태그

인프런 TOP Writers

주간 인기글