묻고 답해요
164만명의 커뮤니티!! 함께 토론해봐요.
인프런 TOP Writers
-
미해결스프링 시큐리티
섹션4 7번 강의 문제가 있는거 같네요.
섹션4 6번강의까지 잘 따라왔습니다. 혹시 제가 잘못 본게 있을까 해서 3번 강의를 들었지만 안되네요. 강의 내용 그대로 코딩했습니다. 머가 문제일까요? 500에러면 문법에러인건데요. html내 meta위치가 문제인가여? 강의중에 특정파일 내 html meta가 중첩된것도 보입니다. _csrf값이 undefined나 null일 경우도 에러가 생기는것도 같네요. 강사님 답변좀 부탁드립니다.
-
미해결스프링 프레임워크는 내 손에 [스프2탄]
spring Legacy Project에서 MVC 프로젝트가 없습니다. 어떻게 해야하나요?
안녕하세요. 24.03.24일 날 스프2탄을 구매하였습니다. 시작부터 문제가 발생되어서 글 남깁니다. 강사님의 영상을 따라 eGovFrame-4.0.0을 다운로드 하였고 1. 프로젝트를 생성하기위해 Spring Legacy Project 클릭 ---문제 발생 ---- 2.Simple Projects만 보이고 MVC프로젝트가 보이질 않습니다. 구글링을 해보고 시도 하였지만 해결되지 못했습니다. 초보의 입장에서 난감해하고 있습니다. 해결방법과 그따른 영상을 업데이트를 해주실수 있을까요?
-
미해결스프링 시큐리티
파일이 수시로 이름이 바껴있네요 ㄷㄷ
CustomAuthenticationProvider 로 폼인증방식 강의 진행하셨는데요. Ajax인증방식에서는 FormAuthenticationProvider로 파일명이 Custom에서 바껴있는데 중간에 이름만 바꾸신건가여?? 강의를 듣다보면 파일이름이 달라져서 헷갈립니다. ㄷㄷ강의진행시에 바로직전까지 했던 소스의 버전관리가 필요해보입니다. 다음강의 들으면 파일명이 혹은 실제코드가 달라져있는게 초짜인 수강생들에겐 좀 힘듭니다.
-
미해결스프링 시큐리티
HttpSessionSecurityContextRepository를 사용안하는 문제
선생님 안녕하세요.스프링 시큐리티 업데이트 버전만 손꼽아 기다리는 중입니다ㅠㅠ우선 저는 프로젝트에서 기존 버전이 아니라 최신 버전으로 Security를 적용하고 session 저장소로 @EnableRedisHttpSession를 사용해 Redis를 사용하는 중입니다.Redis에 sessionId가 저장되는것까지 확인했습니다.선생님 강의보면서 참고하면서 잘 따라왔다고 생각했는데, 아래처럼 에러가 뜹니다. HttpSessionSecurityContextRepository에서 SPRING_SECURITY_CONTEXT Key를 이용해서 찾은게 SecurityContext가 아닌 Authentication 인증객체라는 내용 같은데요.Authentication < SecurityContext < SecurityContextHolder가 아니라 Authentication < SecurityContextHolder가 된것 같습니다.20240322 21:08:43.930 [http-nio-8080-exec-2] WARN o.s.s.w.c.HttpSessionSecurityContextRepository - SPRING_SECURITY_CONTEXT did not contain a SecurityContext but contained: '{authentication={authorities=[{authority=ROLE_ADMIN}], details={remoteAddress=0:0:0:0:0:0:0:1, sessionId=null}, authenticated=true, principal={password=null, username=sejinpark@email.com, authorities=[{authority=ROLE_ADMIN}], accountNonExpired=true, accountNonLocked=true, credentialsNonExpired=true, enabled=true}, credentials=null, name=sejinpark@email.com}}'; are you improperly modifying the HttpSession directly (you should always use SecurityContextHolder) or using the HttpSession attribute reserved for this class?그래서 로그인한 상태에서 아래 내용을 출력해도 AnonymousUser가 뜨는데요.SecurityContextHolder.getContext().getAuthentication() 인증 저장소 필터 챕터에서 SecurityContextPersistenceFilter를 deprecated되서 SecurityContextHolderFilter를 디버깅해봤더니, SecurityContextRepository 구현체 2개 (HttpSessionSecurityContextRepository, DelegatingSecurityContextRepository) 중에서 DelegatingSecurityContextRepository로만 가서 문제인것 같습니다. 아예 HttpSessionSecurityContextRepository로 들어가질 않더라구요. 이게 문제인것 같은데, 어느부분을 확인해아할지, 혹은 어떤 필터를 커스텀해야할지 여쭙고싶습니답참고로 securityContext를 아래처럼 설정했습니다 .securityContext((securityContext) -> securityContext .securityContextRepository(new DelegatingSecurityContextRepository( new HttpSessionSecurityContextRepository() ))
-
미해결스프링 시큐리티
error , exception 이 잘 안됩니다.
강사님 소스와 똑같이 했는데도 안되는데요 ....로그인 실패해도 에러 문구가 안뜹니다. 디버깅하면 Controller 값이 null 로 들어오는데 왜그런걸까요 ?? security 설정에 /login?* 설정도 해줬습니다. @Controllerpublic class LoginController { // 에러가 있을때만 선택적으로 받는다.@RequestMapping(value={"/login"})public String login(@RequestParam(value = "error", required = false) String error,@RequestParam(value = "exception", required = false) String exception, Model model){model.addAttribute("error",error);model.addAttribute("exception",exception);return "login";} @GetMapping("/logout")public String logout(HttpServletRequest request, HttpServletResponse response) { Authentication authentiation = SecurityContextHolder.getContext().getAuthentication(); if (authentiation != null) {new SecurityContextLogoutHandler().logout(request, response, authentiation);} return "redirect:/login"; }} package com.eazybytes.springsecsection3.security.handler; import java.io.IOException; import org.springframework.security.authentication.BadCredentialsException;import org.springframework.security.authentication.InsufficientAuthenticationException;import org.springframework.security.core.AuthenticationException;import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;import org.springframework.stereotype.Component; import jakarta.servlet.ServletException;import jakarta.servlet.http.HttpServletRequest;import jakarta.servlet.http.HttpServletResponse; // 인증 검증시 실패할때 인증 예외 발생@Componentpublic class CustomAuthenticationFailureHandle extends SimpleUrlAuthenticationFailureHandler { @Overridepublic void onAuthenticationFailure(final HttpServletRequest request, final HttpServletResponse response, final AuthenticationException exception) throws IOException, ServletException { String errorMessage = "Invalid Username or Password"; if(exception instanceof BadCredentialsException) {errorMessage = "Invalid Username or Password"; }else if(exception instanceof InsufficientAuthenticationException) {errorMessage = "Invalid Secret";} setDefaultFailureUrl("/login?error=true&exception=" + errorMessage); super.onAuthenticationFailure(request, response, exception); }}package com.eazybytes.springsecsection3.security.config;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.autoconfigure.security.servlet.PathRequest;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.security.authentication.AuthenticationDetailsSource;import org.springframework.security.authentication.AuthenticationProvider;import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;import org.springframework.security.config.annotation.web.builders.HttpSecurity;import org.springframework.security.config.annotation.web.configuration.WebSecurityCustomizer;import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;import org.springframework.security.crypto.password.PasswordEncoder;import org.springframework.security.web.SecurityFilterChain;import org.springframework.security.web.authentication.AuthenticationFailureHandler;import org.springframework.security.web.authentication.AuthenticationSuccessHandler;import com.eazybytes.springsecsection3.security.provider.CustomAuthenticationProvider;import com.eazybytes.springsecsection3.security.service.CustomUserDetailsService;import jakarta.servlet.DispatcherType;@Configurationpublic class SecurityConfig { @Autowiredprivate AuthenticationSuccessHandler customerauthenticationSuccessHandler; // 인증 성공후 핸들링 처리 @Autowiredprivate AuthenticationFailureHandler authenticationFailureHandlerl; // 인증 실패후 핸들링 처리 @Autowiredprivate AuthenticationDetailsSource authenticationDetailsSource; // FormWebAuthenticationDetails 을 security 가 사용할 수 있도록 등록 @Autowiredprivate CustomUserDetailsService userDetailsService; // 개발자가 만든 userDetailsService 를 사용 protected void configure (AuthenticationManagerBuilder auth) throws Exception{ // CustomAuthenticationProvider 를 seruciry 가 사용할 수 있도록 등록auth.authenticationProvider(authenticationProvider());} @Beanpublic AuthenticationProvider authenticationProvider() {return new CustomAuthenticationProvider();} @BeanSecurityFilterChain defaultSecurityFilterChain(HttpSecurity http) throws Exception {http.csrf(AbstractHttpConfigurer::disable); http.authorizeHttpRequests((auth) ->auth.dispatcherTypeMatchers(DispatcherType.FORWARD).permitAll().requestMatchers("/","/users","/users/login/**, /login*").permitAll() /* /login* /login?error=true&exception 접근 허용 */.requestMatchers("/mypage").hasRole("USER").requestMatchers("/message").hasRole("MANAGER").requestMatchers("/config").hasRole("ADMIN").anyRequest().authenticated()); http.formLogin((form) ->form.loginPage("/login").loginProcessingUrl("/login_proc").defaultSuccessUrl("/").authenticationDetailsSource(authenticationDetailsSource).successHandler(customerauthenticationSuccessHandler ) // 인증이 성공한 후 핸들링 처리.failureHandler(authenticationFailureHandlerl) // 인증이 실패후 후 핸들링 처리.permitAll());return http.build();} @Beanpublic PasswordEncoder passwordEncoder() {return new BCryptPasswordEncoder();} @Beanpublic WebSecurityCustomizer webSecurityCustomizer() {// 정적 리소스 spring security 대상에서 제외return (web) ->web.ignoring().requestMatchers(PathRequest.toStaticResources().atCommonLocations());}} --------------------- <!DOCTYPE html><html xmlns:th="http://www.thymeleaf.org"><head th:replace="layout/header::userHead"></head><body><div th:replace="layout/top::header"></div><div class="container text-center"><div class="login-form d-flex justify-content-center"><div class="col-sm-5" style="margin-top: 30px;"><div class="panel"><p>아이디와 비밀번호를 입력해주세요</p></div><div th:if="${param.error}" class="form-group"><span th:text="${exception}" class="alert alert-danger">잘못된 아이디나 암호입니다</span></div><form th:action="@{/login_proc}" class="form-signin" method="post"><input type="hidden" th:value="secret" name="secret_key" /><div class="form-group"><input type="text" class="form-control" name="username" placeholder="아이디" required="required" autofocus="autofocus"></div><div class="form-group"><input type="password" class="form-control" name="password" placeholder="비밀번호" required="required"></div><button type="submit" class="btn btn-lg btn-primary btn-block">로그인</button></form></div></div></div></body></html>
-
미해결스프링 시큐리티
thymeleaf tag 질문합니다.
- 학습 관련 질문을 남겨주세요. 상세히 작성하면 더 좋아요! - 먼저 유사한 질문이 있었는지 검색해보세요. - 서로 예의를 지키며 존중하는 문화를 만들어가요. - 잠깐! 인프런 서비스 운영 관련 문의는 1:1 문의하기를 이용해주세요. 로그인 하지 않을 때 isAnonymous() 는 동작하는데 로그인 하고 isAuthenticated() 는 동작 하지 않아서 top 메뉴에 로그아웃이 보이지 않네요 로그인 처리가 잘 안돼서 그런건가요 ??
-
미해결호돌맨의 요절복통 개발쇼 (SpringBoot, Vue.JS, AWS)
ExceptionHandler가 AccessDeniedHandler(Http403Handler)를 먹어버리는 현상
안녕하세요 호돌맨님 강의 항상 잘보고있습니다. 다름이 아니라 실습 중 의도치 않게 동작하는 부분이 있어 질문드립니다. 상황회원 가입 후 로그인이 때 유저의 Role 은 ADMIN메소드 시큐리티로 아래와 같이 자원의 권한 제한@RestController class HomeController { @GetMapping("/user") @PreAuthorize("hasRole('ROLE_USER')") fun user(): String { return "user 접근 가능👁" } @GetMapping("/admin") @PreAuthorize("hasRole('ROLE_ADMIN')") fun admin(): String { return "admin 접근 가능 👨💼" } }이 때ExceptionHandler로 Runtime예외를 캐치해 응답을 주고 있습니다.동시에 커스텀한 403핸들러를 HttpSecurity에 끼워 넣어주었습니다.// ControllerAdvice @ExceptionHandler(Exception::class) fun handleRuntimeException(ex: Exception): ResponseEntity<ErrorResult> { logger.error("ex", ex) return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) .body( ErrorResult( code = "500", message = ex.message, ) ) } // SecurityConfig @Bean fun securityFilterChain(http: HttpSecurity): SecurityFilterChain { return http // .. other config.. .exceptionHandling { e -> e.accessDeniedHandler(Http403Handler(objectMapper)) e.authenticationEntryPoint(Http401Handler(objectMapper)) } .build() } 기대하는 동작ADMIN으로 로그인한 유저가 USER 자원에 접근하면 아래와 같이 응답{ "code": "403", "message": "접근할 수 없습니다.", "validation": null }실제 동작{ "code": "500", "message": "Access Denied", "validation": null } ControllerAdvice에서 Runtime예외를 처리하지 않는다면 의도대로 403이 응답되는데, ControllerAdvice에서 예외를 포괄적으로 처리하게 되면 403이 응답되지 않습니다. 혹시 이런경우를 겪으신적이 있는지? 따로 해결방법이 있을지 궁금해 여쭙습니다.감사합니다.
-
미해결스프링 프레임워크는 내 손에 [스프1탄]
git 연결할때 오류
06. 개발환경구축_Git 연결하기 할때에 21초 즈음에 해야하는 finish가 눌리지 않고, Target location for project SpringStart already exists, cannot move project이러한 오류가 발생합니다
-
미해결호돌맨의 요절복통 개발쇼 (SpringBoot, Vue.JS, AWS)
섹션10 언제 나오나요?
대략적인 일정이라도 궁금합니다
-
미해결스프링 시큐리티
버전업하면서 deprecated된 것들이 너무많아요
- 학습 관련 질문을 남겨주세요. 상세히 작성하면 더 좋아요! - 먼저 유사한 질문이 있었는지 검색해보세요. - 서로 예의를 지키며 존중하는 문화를 만들어가요. - 잠깐! 인프런 서비스 운영 관련 문의는 1:1 문의하기를 이용해주세요.강의따라갈려니까 관련해서 오류가 계속 발생하고 extends가 안되는데 어떻게 해야하는지 추가글이나 방법을 알려주세요.
-
미해결스프링 프레임워크는 내 손에 [스프1탄]
프로젝트 생성시 Srping MVC Project 없음
- 학습 관련 질문을 남겨주세요. 상세히 작성하면 더 좋아요! - 먼저 유사한 질문이 있었는지 검색해보세요. - 서로 예의를 지키며 존중하는 문화를 만들어가요. - 잠깐! 인프런 서비스 운영 관련 문의는 1:1 문의하기를 이용해주세요. 다르분 질문 봣는데 해결이 안되어 질문남깁니다. sts3로 설치해서 들어가봐도 Spring MVC Project 가 안나오는데 어떡해 진행해야할까요자세하게좀 설명부탁드립니다..
-
미해결스프링부트 시큐리티 & JWT 강의
섹션 3. JWT 관련 기능 질문입니다.
안녕하세요, 강의 잘 보고 있습니다.이번에 JWT 관련 기능을 구현함에 있어 참고차 보게되었는데요. 시큐리티가 인터페이스화가 많이 되어있다보니 동일한 기능임에도 구현하는 사람마다 어느 필터에서 인증/인가를 구현하는 지가 차이가 있는 것 같습니다. 섹션 3 버전2 소스 기준으로 JwtAuthorizationFilter 의 경우 BasicAuthenticationFilter를 확장하여 사용하고 JwtAuthenticationFilter의 경우 UsernamePasswordAuthenticationFilter 를 확장하여 사용하고, 필터에 등록되어 있습니다. 위 2가지 필터는 공식 문서 참고에 의하면BasicAuthenticationFilter 는 HTTP 헤더에서 토큰을 추출하여 간단히 인증을 하는 용도로, UsernamePasswordAuthenticationFilter는 폼 기반의 로그인을 처리한다고 나와 있습니다. 만약 그렇다면, 폼 로그인 없이 JWT 토큰 만으로는 BasicAuthenticationFilter를 확장하는 JwtAuthorizationFilter만 존재해도 인증 과정 상 크게 문제는 없어보이는데요.(권한 체크는 별도로 할거라 인증 과정에 넣지 않으려고 합니다.)어떤 분은 토큰 체크하는 부분을 GenericFilterBean 또는 OncePerRequestFilter 로 구현하시는 분들도 존재하더라구요.단순히 로그인 컨트롤러에서 JWT 토큰을 발급하고 이후 요청 필터에서 토큰 체크 및 리프레시 토큰 체크 등의 인증 처리를 한다면 어떤 필터를 구현하여 등록하는 걸 추천하시는지 개인적으로 궁금합니다.감사합니다.
-
미해결스프링 시큐리티
spring security 패치 관련
@Configuration @EnableWebSecurity public class SecurityConfig { @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { //인증 http .authorizeHttpRequests((authorizeRequests) -> authorizeRequests.anyRequest().authenticated()); //인가 http .formLogin((formLogin) -> formLogin .usernameParameter("user") .passwordParameter("1234") .defaultSuccessUrl("/", true) ); return http.build(); } }
-
미해결스프링 시큐리티
모바일을 사용할때 토큰말고 세션
모바일 서비스를 하는데 인증방식을 보통 jwt 토큰으로 하자나요api 서버에서도 세션을 쓰지 않고 jwt 발급해주고 토큰으로 인증을 하는데 , 세션쿠키방식으로 모바일이 인증하기가 어려운 이유가 뭘까요 ...웹은 세션 쿠키 방식을 쓰는데 왜 모바일은 그렇게 못하는걸까요?
-
미해결스프링 시큐리티
DB 연동한 인가 부분에 대한 질문입니다!
안녕하세요.새강의 없이 혼자 좀 해오고 있는데 DB 연동하는 부분은 좀 감이 안 잡히네요. AuthorizationFilter에서 처리될 때RequestMatcherDelegatingAuthorizationManager에 위임되고 거기에 있는 this.mappings에 SecurityConfig에서 설정한 requestMatcher가 초기화되어 있더라고요.다이나믹하게 this.mappings에 제가 디비에서 가져온 데이터를 넣으면 좋은데 이 방법이 맞는지도 모르겠고 감을 못 잡겠네요ㅠ힌트라도 주실 수 있나요? 현재 강의에서 사용하는 방법의 일부처럼 새로운 필터를 넣어야 하는 걸까요..
-
미해결스프링 프레임워크는 내 손에 [스프1탄]
Oracle을 연결하고 싶은데, sql파일을 만들고나면...
Oracle을 연결하고 싶은데, sql파일을 만들고나면... 상단창에 Type을 Oracle로 지정해도 Name과 Database가 뜨지 않습니다. lib 폴더 만들어서 ojdbc6.jar 드라이버도 넣어 놨고, tnsnames.ora에 XE = (DESCRIPTION = (ADDRESS = (PROTOCOL = TCP) (HOST = 127.0.0.1) (PORT = 1521) ) (CONNECT_DATA = (SERVER = dedicated) (SERVICE_NAME = orcl) ) )도 추가해두었습니다.pom.xml에는 다음과 같이 dependency도 추가하였습니다.<!-- Servlet --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>javax.servlet.jsp-api</artifactId> <version>2.3.1</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>5.0.2.RELEASE</version> </dependency> <dependency> <groupId>com.zaxxer</groupId> <artifactId>HikariCP</artifactId> <version>3.4.1</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.6</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.3.2</version> </dependency> 뭐가 문제일까요 선생님?
-
미해결스프링부트 시큐리티 & JWT 강의
로그인 성공 이후의 경로
- 학습 관련 질문을 남겨주세요. 상세히 작성하면 더 좋아요! - 먼저 유사한 질문이 있었는지 검색해보세요. - 서로 예의를 지키며 존중하는 문화를 만들어가요. - 잠깐! 인프런 서비스 운영 관련 문의는 1:1 문의하기를 이용해주세요. 1.postman에서 /login경로로 로그인 시도를 하여 성공하였는데, 로그인 성공 이후에는 어떤 경로로 이동하게 되는건가요?만약 리액트와 협업을 하여 로그인 기능을 구현한다면 로그인 화면에서 아이디와 비밀번호를 치고 로그인을 시도해야하는데 그 경우에는 경로를@PostMapping("/login")public void login(User user) {}이런식으로 해야하는건가요?
-
미해결호돌맨의 요절복통 개발쇼 (SpringBoot, Vue.JS, AWS)
CommentService에서 Repository를 호출하지 않는데도
CommentService에서 Repository를 호출하지 않는데도 DB에 저장되는 이유가 뭔가요? @Transactional 어노테이션에 기능이 있는 것 같은데 이런 건 JPA를 좀 더 공부해야 알 수 있는 내용일까요?
-
미해결스프링 시큐리티
Ajax방식도 똑같이 Session방식을 사용하는건가요?
안녕하세요.Ajax를 사용하면 UsernamePassword방식과 같이 세션쿠키를 사용해서 인증/인가 처리를 하는건가요?
-
미해결스프링 시큐리티
Config 파일 생성 시 질문이 있습니다.
안녕하세요.기존에 form인증방식에서 만들었던 Config 파일이 있고 Ajax인증방식의 Config파일을 만들었더니 Ajax필터가 정상작동하지 않았습니다. 정확히 뭐 때문에 작동을 안하는지는 모르겠지만 form인증방식에서 만들었던 Config 파일의 빈으로 등록한 SecurityFilterChain을 주석처리하니까 Ajax필터가 작동하더라구요. 제가 잘못 작성한 걸까요? 혹시 이유를 알 수 있을까요?감사합니다.<form 인증방식><ajax 인증방식>