묻고 답해요
130만명의 커뮤니티!! 함께 토론해봐요.
인프런 TOP Writers
-
해결됨스프링 프레임워크는 내 손에 [스프1탄]
회원테이블과 권한테이블 간 관계
선생님 안녕하세요. 회원테이블과 권한테이블 간 관계 질문드립니다.회원 1명이 사용자, 매니저, 관리자 중 여러 권한을 가질 수 있으니, 회원테이블과 권한테이블 간 관계는 '1대다'의 관계인가요?
-
미해결호돌맨의 요절복통 개발쇼 (SpringBoot, Vue.JS, AWS)
예외처리2 validation Map
Validation 클래스를 만들어서 Validation 클래스를 List로 담아서 내보냈습니다.이렇게 하면 테스트가 정상적으로 동작을 하는데 Map을 사용했을 때 성능적으로나 효율성이 뭐가 더 나은지 알고 싶습니다.그리고 json 을 어떤 방식으로 넘겨야 좋은지 알고싶습니다.
-
미해결스프링 시큐리티
브레이크 포인트를 거는 이유
브레이크 포인트를 거는 이유가 뭔가요 ??
-
미해결스프링 프레임워크는 내 손에 [스프2탄]
스프링 시큐리티 질문
package kr.bit.config; import org.springframework.beans.factory.annotation.Autowired; 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.factory.PasswordEncoderFactories; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.web.SecurityFilterChain; @Configuration //스프링 컨테이너 설정파일이라고 메모리에 올림 @EnableWebSecurity public class SecurityConfiguration { @Autowired private UserDetailsServiceImpl userDetailsService; //패스워드 인코딩 객체를 스프링 컨테이너에 등록 @Bean public PasswordEncoder PasswordEncoder() { return PasswordEncoderFactories.createDelegatingPasswordEncoder(); } @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http.csrf(csrfConfig -> csrfConfig.disable() ) .authorizeHttpRequests(authorizeRequests -> authorizeRequests .anyRequest().permitAll() ) .formLogin(login -> login .loginPage("/member/login") .defaultSuccessUrl("/board/list") ) .logout(logout -> logout .logoutUrl("/member/logout") .logoutSuccessUrl("/") ) .userDetailsService(userDetailsService); return http.build(); } } 모든 접근에 대해 permitAll()을 하면 http://localhost:8080/m15/http://localhost:8080/m15/member/login둘다 잘 접속 되지만package kr.bit.config; import org.springframework.beans.factory.annotation.Autowired; 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.factory.PasswordEncoderFactories; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.web.SecurityFilterChain; @Configuration //스프링 컨테이너 설정파일이라고 메모리에 올림 @EnableWebSecurity public class SecurityConfiguration { @Autowired private UserDetailsServiceImpl userDetailsService; //패스워드 인코딩 객체를 스프링 컨테이너에 등록 @Bean public PasswordEncoder PasswordEncoder() { return PasswordEncoderFactories.createDelegatingPasswordEncoder(); } @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http.csrf(csrfConfig -> csrfConfig.disable() ) .authorizeHttpRequests(authorizeRequests -> authorizeRequests .requestMatchers("/", "/member/**").permitAll() .requestMatchers("/board/**").authenticated() ) .formLogin(login -> login .loginPage("/member/login") .defaultSuccessUrl("/board/list") ) .logout(logout -> logout .logoutUrl("/member/logout") .logoutSuccessUrl("/") ) .userDetailsService(userDetailsService); return http.build(); } } requestMatchers 로 permitAll()하면http://localhost:8080/m15/로 접속하면http://localhost:8080/m15/member/login로 이동하면서 에러가 발생합니다. 스프링 부트 버전은 3.2.1입니다.
-
미해결호돌맨의 요절복통 개발쇼 (SpringBoot, Vue.JS, AWS)
로그인을 Controller가 아닌 filter에서 처리하는 것의 이점
스프링 시큐리티에서 기본적으로 제공하는 formlogin 방식이 아닌 방식(예를 들면 json 요청)으로 로그인을 구현할 때, 기존의 방식 처럼 컨트롤러에서 처리하는 것과 커스텀 필터를 등록하여 처리하는 것에 차이가 무엇인지 궁금합니다. 아무래도 필터는 Dispatcher Servlet을 거치지 않고 먼저 처리할 수 있다는 장점이 있을 것 같은데 컨트롤로 단에서 처리하는 것 보다 어떤점이 유리할까요? 또 다른 이점이 있는지도 궁금합니다!
-
미해결스프링 시큐리티
csrf 문의
헤더에 토큰 값 주고 브레이크 포인트 잡았는데요..actualToken이 null 입니다ㅜㅜ 왜 그러는 걸까요?
-
미해결스프링부트 시큐리티 & JWT 강의
JWT - 24강 authenticationManager() 문제
jwt버전 문제로 안되는 것같아요..
-
미해결스프링부트 시큐리티 & JWT 강의
authenticaiotnMaanger()안됨
버전차이로 오류가 뜬것같습니다!..
-
미해결스프링 시큐리티
AjaxAuthenticationProvider에서 authenticate 함수 재정의 할 때 @Transactional 관련 질의입니다.
안녕하세요. 강의 잘 듣고 있습니다.제가 수강하는 시점엔 SpringBoot 3.x.x, security6를 써야 하지만, security5과 아키텍처는 대동소이할 거 같아 수업과 동일한 환경에서 강의 듣고 있습니다.강사님 영상에서 10:45 보시면 authenticate()에 @Transactional이 들어가있는데요. 제가 실습 환경에서는, 이 애노테이션 때문인 것 같은데, AjaxAuthenticationProvider 프록시 객체 생성에서 에러가 발생합니다.대체 @Transactional이랑 무슨 상관인지는 파악하지 못했지만 설마..하고 해당 애노테이션을 지우고 나니 AjaxAuthentication 프록시 객체가 잘 생성되고 정상 동작을 하더라고요.이유가 정말 궁금합니다.좋은 강의 감사합니다.
-
해결됨스프링부트 시큐리티 & JWT 강의
3강에서 로그인폼 작성후 실행하면 작성한 입력폼이 안 뜹니다.
안녕하세요 강의 듣고 있는 수강생입니다.좋은 강의 가르쳐주셔서 감사합니다.제가 따라 가다가 막힌 부분이 있어서 질문 남깁니다.3강에서 login - > loginForm 으로 리턴해주고 loginForm을 작성한 후 테스트 할 때loginForm에 작성한 로그인 입력폼이 뜨지 않고loginForm 문자 그 자체만을 반환하고 있습니다.오류도 뜨지 않아서 maven 업데이트나 프로젝트 클린 후 실행해봐도 똑같은데 무엇때문인지 알 수 있을까요 ??
-
해결됨스프링 프레임워크는 내 손에 [스프1탄]
MVC02에서 List 화면이 나오지 않습니다
안녕하세요, 강의 실습을 따라서 진행하는 중에 화면이 잘 안나오는 문제가 있어서 질문 드립니다.지난번에 MVC01에서 화면이 로드되지 않는 문제에 대해 maven clean, install을 알려주셔서 이후에는 화면 부분을 생성할 때마다 maven clean, install을 진행했습니다ㅜㅜ하지만 이번에는 maven clean,install을 실행하거나 프로그램을 껐다가 다시 해봐도 List가 나오지 않습니다.브라우저의 결과는 아래와 같습니다.List 출력 전 json 알림까지도 잘 나왔고 http://localhost:8080/controller/boardList.do에서도 아래 이미지처럼 나왔습니다.main.jsp 파일입니다. 제가 보기에는 오타 없는 것 같아요. 32번줄 table부분은 var listHtml="<table class='table table-boardered'>";로도 바꿔봤는데 결과는 같습니다.controller 부분입니다.또한 pom.xml dependency도 추가했습니다.서버도 문제 없이 작동되고 있습니다.어디가 문제일까요... 강의를 너무 잘 듣고 있는데 환경 설정 때문인지 자꾸 실행되지 않는 부분이 생겨서 질문 남깁니다ㅜㅜegov 4.0으로 초기 셋팅은 강사님과 동일합니다.
-
미해결스프링 프레임워크는 내 손에 [스프1탄]
시큐리티 프로젝트..
부트말고 스프링프레임워크에서 시큐리티 기능을 이용한 회원별 권한 부여된 게시판 기능을 만들려고 하는데 SPRING MVC02와 03, 04 를 한 프로젝트 안에 다 작업해도될까요??필요한 기능이 관리자 - 글쓰기(사진 멀티업로드) 이용자 - 조회, 찜기능 비회원- 조회이런것들입니다.시큐리티 기능을 활용해서 사이트를 만들어보려고 하는데 어떤 챕터를 활용하면 좋을지 의견 부탁드립니다..!기존 세팅은 되어 있어서 MVC01 은 제외하고 작업하면 될 것 같은데이렇게 되면 MVC02부터 실행해도 괜찮은지도 말씀 부탁드립니다..!감사합니다.
-
미해결스프링 프레임워크는 내 손에 [스프1탄]
org.springframework.beans.factory.UnsatisfiedDependencyException
MVC06 소스 톰캣 실행 시 아래 오류가 발생합니다. ERROR: org.springframework.web.servlet.DispatcherServlet - Context initialization failedorg.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'memberController': Unsatisfied dependency expressed through field 'memberUserDetailsService'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'kr.ody.apps.security.MemberUserDetailsService' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)} at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:586) at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:91) at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:372) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1344) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:582) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:502) 구글링으로 파악이 안되네요.원인이 무엇일까요?
-
미해결스프링 시큐리티
LogoutFilter MockMVC 테스트 질문
안녕하세요 양질의 강의 감사합니다 ㅎㅎ개인 프로젝트에 LogoutFilter를 적용하고 테스트해보려는데, 404 에러가 발생합니다. 아마 mockMvc에 필터가 적용이 안된 것 같은데, 지금 생각으로는 수동으로 LogoutFilter 객체를 생성해서 mockmvc에 추가해주는 것밖에 방법이 떠오르지 않습니다. 혹시 아래와 같이 테스트하는 방법 말고 더 적절한 방법이 있을지 궁금합니다. 감사합니다 ^^ @BeforeEach void setUp( WebApplicationContext webApplicationContext, RestDocumentationContextProvider restDocumentation) { this.mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext) .apply(documentationConfiguration(restDocumentation)) .build(); } @Test void signout() throws Exception { mockMvc.perform(RestDocumentationRequestBuilders.post("/v1/logout") .cookie(new Cookie(Constants.ACCESS_TOKEN_KEY, accessToken)) .cookie(new Cookie(Constants.REFRESH_TOKEN_KEY, refreshTokenString))) .andExpect(status().isOk()) .andExpect( result -> { Cookie accessTokenCookie = result.getResponse().getCookie("X-Access-Token"); assertThat(accessTokenCookie.getMaxAge()).isZero(); assertEquals("", accessTokenCookie.getValue()); }); }
-
미해결
스프링 시큐리티 HttpSeurity.apply() derpeciated 도움 부탁드려요!
안녕하세요! 최근 스프링 시큐리티가 패치되면서, 기존 메서드 체이닝 방식이 아닌 람다식을 통해 함수형으로 설정하도록 바뀌었는데요. 다른 설정 부분은 새롭게 바뀐 방식을 찾았으나.... 아래 사진의 마지막 apply() 는 도저히 찾을 수가 없더라고요...ㅠ 혹시 아시는 분계실까요?('apply(C)' is deprecated since version 6.2 and marked for removal )
-
해결됨스프링 시큐리티
RoleHierarchy 강의 내용에서 계층 권한 설정에 대해 몇 가지 질문드립니다.
안녕하세요, 우선 좋은 내용의 강의 감사드립니다. 이어 Spring Security 계층 권한 설정 방법에 대해 아래와 같이 몇 가지 질문을 드리고자합니다. [질문 항목]DB를 사용해서 계층 권한 테이블을 선언하고 부모, 자식 관계의 권한 데이터(row)를 등록해 놓은 상황에서 프로그램을 실행시키게 되면 현재 이 계층 권한 테이블에 있는 데이터에 한해서만 Security 권할 설정이 이루어지는 것인가요? 만약, 추후 DB에 직접 새로운 계층 권한 정보가 등록된다면 해당 프로그램이 재시작되어야만 변경된 계층 권한 정보가 동기화되는 것인가요?1번 항목과 비슷한 맥락으로 한 회원이 서비스 이용중 자신의 권한이 사이트 관리자에 의해 변경되었다면 변경된 권한이 적용되는 시점에 대해서도 궁금합니다.Spring Security 기본 정책(?)상 계층 권한을 나타낼 때에는 문자열 형태로 권한 관계를 > 를 사용하여 표기하는 것을 볼 수 있었는데요. 이렇게 문자열 형태가 아닌 다른 형태(예를 들어 Map 등)로도 표기가 가능한가요? 만약, 이런 설정 방법이 존재한다면 가이드를 제공해주실 수 있을까요?아직 강의를 완강한 것이 아니기에 질문 내용이 부족한점 양해드리며, 미리 답변 감사드립니다.
-
미해결호돌맨의 요절복통 개발쇼 (SpringBoot, Vue.JS, AWS)
배포 준비 과정에서 막혀 질문 드립니다.
호돌맨의 요절복통 개발쇼시즌2 배포 준비(빌드) 강의를 듣고 있는데, 계속 오류가 생겨 질문 올립니다. 우선 ./gradlew clean으로 삭제한 뒤./gradlew build를 실행하면 이런 식으로 한글이 깨졌다는 에러가 나옵니다. 해결하고자 했던 방안세팅 바꾸기파일 인코딩 바꾸기Help - EditCustom Vm Options이런 방법을 써 봤으나 다 되지 않았고 이 코드를 build.gradle에 넣는 방식으로 해결했더니build 후 libs 폴더가 생기지 않습니다. 그래서 이 부분을 true로 바꿔주면 plain snapshot만 생깁니다. 어떻게 해결해야 하나요? 밑 코드는 build.gradle 파일입니다.plugins { id 'java' id 'org.springframework.boot' version '2.5.9' id 'io.spring.dependency-management' version '1.0.11.RELEASE' id "org.asciidoctor.jvm.convert" version "3.3.2" } group = 'com.reheat' version = '0.0.1-SNAPSHOT' java { sourceCompatibility = '11' } configurations { compileOnly { extendsFrom annotationProcessor } asciidoctorExt } repositories { mavenCentral() } ext { asciidocVersion = "2.0.6.RELEASE" snippetsDir = file('build/generated-snippets') } dependencies { implementation 'org.springframework.boot:spring-boot-starter-data-jpa' implementation 'org.springframework.boot:spring-boot-starter-web' implementation 'org.springframework.boot:spring-boot-starter-validation' testImplementation 'org.junit.jupiter:junit-jupiter:5.8.1' testImplementation 'junit:junit:4.13.1' compileOnly 'org.projectlombok:lombok' runtimeOnly 'com.h2database:h2' annotationProcessor 'org.projectlombok:lombok' testImplementation 'org.springframework.boot:spring-boot-starter-test' //REST Docs asciidoctorExt "org.springframework.restdocs:spring-restdocs-asciidoctor:${asciidocVersion}" testImplementation "org.springframework.restdocs:spring-restdocs-mockmvc:${asciidocVersion}" } tasks.named('test') { useJUnitPlatform() } test { outputs.dir snippetsDir } asciidoctor { inputs.dir snippetsDir configurations 'asciidoctorExt' dependsOn test } bootJar { enabled = true dependsOn asciidoctor copy { from asciidoctor.outputDir into "src/main/resources/static/docs" } } jar{ enabled = true } tasks.withType(JavaCompile){ options.encoding = "UTF-8" }
-
미해결스프링부트 시큐리티 & JWT 강의
authenticationManager 관련 질문입니다.
안녕하세요 늘 좋은 강의 올려주셔서 감사합니다.authenticationManager 파라미터 전달 부분에서 문제가 있어 이렇게 게시글 남깁니다!새로 올려주신 소스코드를 보며 새로 업데이트된 시큐리티에서 사용하기위해 authenticationManager 를 파라미터로 전달하는 부분을 적용하였습니다 그런데Authentication authentication = authenticationManager.authenticate(authenticationToken);부분에서 loadbyUsername() 함수를 호출하지 못하고 있습니다... JwtAuthenticationFilter// 유저네임 패스워드 토큰 생성 UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken( loginUser.getUsername(), loginUser.getPassword() ); System.out.println("JwtAuthenticationToken : 토큰생성완료"); // authenticate() 함수가 호출 되면 인증 프로바이더가 유저 디테일 서비스의 // loadUserByUsername(토큰의 첫번째 파라메터) 를 호출하고 // UserDetails를 리턴받아서 토큰의 두번째 파라메터(credential)과 // UserDetails(DB값)의 getPassword()함수로 비교해서 동일하면 // Authentication 객체를 만들어서 필터체인으로 리턴해준다. // Tip: 인증 프로바이더의 디폴트 서비스는 UserDetailsService 타입 // Tip: 인증 프로바이더의 디폴트 암호화 방식은 BCryptPasswordEncoder // 결론은 인증 프로바이더에게 알려줄 필요가 없음. Authentication authentication = authenticationManager.authenticate(authenticationToken); System.out.println("authentication : authentication 생성 완료"); PrincipalDetails principalDetails = (PrincipalDetails) authentication.getPrincipal(); System.out.println("Authentication : " + principalDetails.getUser().getUsername()); return authentication;SecurityConfig@Configuration @EnableWebSecurity @RequiredArgsConstructor public class SecurityConfig { private final CosConfig cosConfig; @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { AuthenticationManager authenticationManager = http.getSharedObject(AuthenticationManager.class); http.csrf(csrf -> csrf.disable()); http.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS)); http.addFilter(cosConfig.corsFilter()); // cors 허용 설정 http.addFilterBefore(new MyFilter3(), SecurityContextPersistenceFilter.class); http.formLogin(login -> login.disable()); http.httpBasic(basic -> basic.disable()); http.addFilter(new JwtAuthenticationFilter(authenticationManager)); http.authorizeHttpRequests(request -> request.requestMatchers("/api/v1/user/**") .hasAnyRole("USER", "MANAGER", "ADMIN") .requestMatchers("/api/v1/manager/**") .hasAnyRole("MANAGER", "ADMIN") .requestMatchers("/api/v1/admin/**") .hasRole("ADMIN") .anyRequest().permitAll() ); return http.getOrBuild(); } 와 같이 SecurityConfig를 업데이트된 Spring Security 독스를 보고 선생님께서 강의해주신 내용대로 만들어보았습니다.터미널에서는JwtAuthentication Filter : 로그인 시도중 JwtAuthenticationFilter : UserEntity(id=0, email=null, password=qwer1234, username=ssar, role=null, createDate=null) JwtAuthenticationToken : 토큰생성완료와 같이 JwtAuthenticationToken : 토큰생성완료 까지는 정상적으로 되는걸 확인하였습니다.이후 loadByUsername() 부분에 따로 출력을 찍어 확인한결과 호출이 안되는걸 확인했습니다.@Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { UserEntity userEntity = this.userDao.findByUsername(username); System.out.println("================ loadUserByUsername ================"); System.out.println(userEntity); System.out.println("---------------- loadUserByUsername -----------------"); return new PrincipalDetails(userEntity); } 어떤 부분이 잘못되어서 그런건지 찾지 못하여 게시글 남깁니다! 늘 좋은강의 감사합니다! 개인적으로 문제점이 된다고 생각한 부분AuthenticationManager authenticationManager = http.getSharedObject(AuthenticationManager.class);에서 authenticationManager를 받는 부분이 제대로 안되는것 같습니다... 추가로 SecurityConfig 에서 authenticationManager 부분을 로그로 찍어본 결과 null 출력되는걸 확인했습니다... authenticationManager부분이 생성이 안되는걸까요?
-
해결됨스프링 프레임워크는 내 손에 [스프1탄]
강의내용대로 실행중인데 boardForm.do가 안나옵니다.
어디가 잘못된건지 못 찾겠습니다. 일단 boardList.jsp 에 boardForm.do를 작성했는데 저는 계속해서 404에러와 아래 문구가 콘솔창에 찍힙니다. 도와주세요. 제 눈에는 잘못된 부분이 보이지 않습니다.... 현재 화면을 캡처해서 올립니다.servlet-context.xmlBoardControllerboardList.jspboardForm.jsproot-context.xml결과창 : boardList는 잘 나옵니다.
-
미해결스프링부트 시큐리티 & JWT 강의
Consider defining a bean of type 'org.springframework.security.crypto.password.PasswordEncoder' in your configuration.
@Configuration public class BCryptConfig { @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } } 위와 같이 Config class에 PasswordEncoder 빈을 생성했는데도 Description:Parameter 1 of constructor in domain.Member.service.MemberService required a bean of type 'org.springframework.security.crypto.password.PasswordEncoder' that could not be found.Action:Consider defining a bean of type 'org.springframework.security.crypto.password.PasswordEncoder' in your configuration.Process finished with exit code 1 와 같이 에러가 발생하면 어떻게 해야할까요?