inflearn logo
강의

강의

N
챌린지

챌린지

멘토링

멘토링

N
클립

클립

로드맵

로드맵

지식공유

묻고 답해요

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

로그인 성공 후 어떻게 진행되는지 이해가 안갑니다.

미해결

Spring Cloud로 개발하는 마이크로서비스 애플리케이션(MSA)

@Override protected void successfulAuthentication(HttpServletRequest req, HttpServletResponse res, FilterChain chain, Authentication auth) throws IOException, ServletException { String userName = ((User) auth.getPrincipal()).getUsername(); UserDto userDetails = userService.getUserDetailsByEmail(userName); byte[] secretKeyBytes = Base64.getEncoder().encode(environment.getProperty("token.secret").getBytes()); SecretKey secretKey = Keys.hmacShaKeyFor(secretKeyBytes); Instant now = Instant.now(); String token = Jwts.builder() .subject(userDetails.getUserId()) .expiration(Date.from(now.plusMillis(Long.parseLong(environment.getProperty("token.expiration_time"))))) .issuedAt(Date.from(now)) .signWith(secretKey) .compact(); res.addHeader("token", token); res.addHeader("userId", userDetails.getUserId()); } 여기서 로그인 성공 후 토큰이 발급된 뒤에 @Component @Slf4j public class AuthorizationHeaderFilter extends AbstractGatewayFilterFactory<AuthorizationHeaderFilter.Config> { Environment env; public AuthorizationHeaderFilter(Environment env) { super(Config.class); this.env = env; } public static class Config { // Put configuration properties here } @Override public GatewayFilter apply(Config config) { return (exchange, chain) -> { ServerHttpRequest request = exchange.getRequest(); if (!request.getHeaders().containsKey(HttpHeaders.AUTHORIZATION)) { return onError(exchange, "No authorization header", HttpStatus.UNAUTHORIZED); } HttpHeaders headers = request.getHeaders(); Set<String> keys = headers.keySet(); log.info(">>>"); keys.stream().forEach(v -> { log.info(v + "=" + request.getHeaders().get(v)); }); log.info("<<<"); String authorizationHeader = request.getHeaders().get(HttpHeaders.AUTHORIZATION).get(0); String jwt = authorizationHeader.replace("Bearer", ""); // Create a cookie object // ServerHttpResponse response = exchange.getResponse(); // ResponseCookie c1 = ResponseCookie.from("my_token", "test1234").maxAge(60 60 24).build(); // response.addCookie(c1); if (!isJwtValid(jwt)) { return onError(exchange, "JWT token is not valid", HttpStatus.UNAUTHORIZED); } return chain.filter(exchange); }; } private Mono<Void> onError(ServerWebExchange exchange, String err, HttpStatus httpStatus) { ServerHttpResponse response = exchange.getResponse(); response.setStatusCode(httpStatus); log.error(err); byte[] bytes = "The requested token is invalid.".getBytes(StandardCharsets.UTF_8); DataBuffer buffer = exchange.getResponse().bufferFactory().wrap(bytes); return response.writeWith(Flux.just(buffer)); // return response.setComplete(); } private boolean isJwtValid(String jwt) { byte[] secretKeyBytes = Base64.getEncoder().encode(env.getProperty("token.secret").getBytes()); SecretKey signingKey = new SecretKeySpec(secretKeyBytes, SignatureAlgorithm.HS512.getJcaName()); boolean returnValue = true; String subject = null; try { JwtParser jwtParser = Jwts.parserBuilder() .setSigningKey(signingKey) .build(); subject = jwtParser.parseClaimsJws(jwt).getBody().getSubject(); } catch (Exception ex) { returnValue = false; } if (subject == null || subject.isEmpty()) { returnValue = false; } return returnValue; } 여기로 넘어 오는 게 맞나요? 그리고 그 뒤에 어떻게 진행되는지 설명 부탁드립니다!!

  • spring-boot
  • jpa
  • 아키텍처
  • spring-cloud
  • kafka
  • msa
  • rabbitmq
댓글 2 좋아요 0 조회수 627

강의 자료 문의

해결됨

장애 없는 서비스를 만들기 위한 Resilience4j - CircuitBreaker

안녕하세요. 강의에서 사용한 ppt 자료 어디서 받을 수 있는지 궁금합니다. 감사합니다.

  • spring-boot
  • msa
  • circuit-breaker
  • resilience4j
starryeye 댓글 2 좋아요 1 조회수 339

음성 부분이 너무 깨지는데...

미해결

Microservice 구현 (with EDA,Hexagonal, DDD)

이런 부분은 빨리 보안해 주셔야 하지 않을까요? 중간 내용이 알아 들을수 없어서 너무 답답 합니다. 싼강의도 아니고... 만들어 진지 좀 된거 같은데 빠른 보안이 필요해 보입니다. 그리고 인프런은 이런부분은 한번은 검증해야 하지 않나요.

  • msa
  • ddd
GW kim 댓글 1 좋아요 0 조회수 380

왜 요청에다가 AthenticFilter를 적용할까요?

미해결

Spring Cloud로 개발하는 마이크로서비스 애플리케이션(MSA)

apigateway의 application.yml을 보면 get요청에는 authorizationHeaderFilter를 적용시키고 있습니다. authenticFilter는 그저 로그인 요청시 attempthAuthentication메소드와 successfulAthentication메소드를 통해 인증을 처리하고 response헤더에 토큰을 추가하는 역할입니다. 따라서 로그인 요청에만 적용하면 될 것 같은데, 깃허브의 최신코드 버전을 보면 거의 모든 요청에 authenticationFilter를 적용하고 있습니다. 왜 로그인요청이 아닌 다른 요청에다가 AthenticFilter를 적용할까요? apiGateway-service에서 GET요청만 AuthoriztionFilter를 적용하면 되지않나요?? http.authorizeHttpRequests((authz) -> authz .requestMatchers(new AntPathRequestMatcher("/actuator/**")).permitAll() .requestMatchers(new AntPathRequestMatcher("/h2-console/**")).permitAll() .requestMatchers(new AntPathRequestMatcher("/users", "POST")).permitAll() .requestMatchers(new AntPathRequestMatcher("/h2-console/**")).permitAll() // .requestMatchers(new AntPathRequestMatcher("/welcome/**")).permitAll() // .requestMatchers("/**").access(this::hasIpAddress) .requestMatchers("/**").access( new WebExpressionAuthorizationManager("hasIpAddress('127.0.0.1') or hasIpAddress('172.30.1.48')")) .anyRequest().authenticated() )

  • spring-boot
  • jpa
  • 아키텍처
  • spring-cloud
  • kafka
  • msa
  • rabbitmq
고은우 댓글 1 좋아요 0 조회수 309

로그인까지는 되는데 /welcome에서 403 Forbidden 에러가 뜹니다.

미해결

Spring Cloud로 개발하는 마이크로서비스 애플리케이션(MSA)

안녕하세요. 깃허브에서 spring boot 3.2 브랜치통해 코드를 작성했습니다. 그런데 회원가입, 로그인까지 해서 jwt토큰까지는 잘 받아오는데, 그 이후에 /welcome으로 헤더에 토큰으로 추가해서 요청을 보내도 403 forbidden에러가 뜹니다. 코드는 spring boot 3.2 브랜치와 동일합니다.

  • spring-boot
  • jpa
  • 아키텍처
  • spring-cloud
  • kafka
  • msa
  • rabbitmq
고은우 댓글 2 좋아요 0 조회수 1088

로그인시 No authorization header

해결됨

Spring Cloud로 개발하는 마이크로서비스 애플리케이션(MSA)

안녕하세요 로그인시에는 인증이 필요하지가 않는데 자꾸 인증 해주는 AuthorizationHeaderFilter 클래스에서 apply 메소드에서 header 값이 없다고 걸립니다. 그래서 아래와 같이 401 오류로 로그인이 안됩니다. application.yml 파일은 문제없는거 같은데 뭘 더 확인해봐야 할까요,,,? 아래는 Users application.yml 파일입니다.

  • spring-boot
  • jpa
  • 아키텍처
  • spring-cloud
  • kafka
  • msa
  • rabbitmq
dmsgp6598 댓글 1 좋아요 0 조회수 410

docker ex -it mariadb /bin/bash

미해결

Spring Cloud로 개발하는 마이크로서비스 애플리케이션(MSA)

docker ex -it mariadb /bin/bash 이후에 mysql 명령어를 치면 mysql: Command not found 에러가 나옵니다,.

  • spring-boot
  • jpa
  • 아키텍처
  • spring-cloud
  • kafka
  • msa
  • rabbitmq
김윤제 댓글 1 좋아요 0 조회수 338

강의에 사용된 소스코드는 어디서 받나요?

미해결

세 시간만에 끝내는 쿠버네티스부터 마이크로서비스, CI/CD, 서비스 메시까지

movies.json movies.py 등 강의에 사용된 소스코드는 어디서 받나요?

  • docker
  • kubernetes
  • ci/cd
  • msa
  • gitlab
  • istio
  • argocd
Kevin 댓글 1 좋아요 0 조회수 402

CQRS 질문 드립니다.

미해결

Microservice 구현 (with EDA,Hexagonal, DDD)

강사님 안녕하세요. 강의를 다 듣고 배운 내용을 개인 프로젝트를 통해 구현하는중입니다. 제가 CQRS에 대한 오해가 있는 것 같아 질문 드립니다. CQRS는 도메인을 도메인 답게 유지하기 위해 비지니스 로직에 query가 침투하는 것을 막는다. 즉 command, query를 역할에 따라 분리한다. 라고 이해했는데요. 그렇다면, command만 수행하는 서버, query만 수행하는 서버로 분리하는게 맞을까요? 로직상 command를 통해 데이터를 저장 혹은 업데이트하려고 하면, db에서 해당 데이터에 대한 조회가 필수적이라고 생각하는데 이러한 조회도 command의 한 종류라고 생각하면 되는걸까요?

  • msa
  • ddd
이홍규 댓글 1 좋아요 0 조회수 388

왜 @Configuration의 WebSecurity 클래스에서 생성자 주입을 하지 않나요?

미해결

Spring Cloud로 개발하는 마이크로서비스 애플리케이션(MSA)

@Configuration @EnableWebSecurity public class WebSecurity { extends WebSecurityConfigurerAdapter { private UserService userService; private BCryptPasswordEncoder bCryptPasswordEncoder; private Environment env; public WebSecurity(Environment env, UserService userService, BCryptPasswordEncoder bCryptPasswordEncoder) { this.env = env; this.userService = userService; this.bCryptPasswordEncoder = bCryptPasswordEncoder; } 강의에서 보면 @Configuration으로 WebSecurity클래스가 설정되어있기에 userService, bCryptPasswordEncoder, environment 인스턴스가 준비되어 있다고합니다. 따라서 위의 코드와 같이 생성자주입을 하지않는데, 왜 @Configuration으로 설정되어 있으면 @Autowired로 주입을 받지 않아도 되는 걸까요?

  • spring-boot
  • jpa
  • 아키텍처
  • spring-cloud
  • kafka
  • msa
  • rabbitmq
고은우 댓글 1 좋아요 0 조회수 331

user-service에 로그인 404뜨는데 뭐가 문제일까요?

미해결

Spring Cloud로 개발하는 마이크로서비스 애플리케이션(MSA)

깃허브 코드대로 했습니다

  • spring-boot
  • jpa
  • 아키텍처
  • spring-cloud
  • kafka
  • msa
  • rabbitmq
elixirgood 댓글 2 좋아요 0 조회수 427

특정 dir로 위치를 잡으려면 어떻게 설정을 해야할까요

해결됨

Spring Cloud로 개발하는 마이크로서비스 애플리케이션(MSA)

config를 root dir에 위치시킨게 아니라 특정 dir에 넣고 싶은데 그럴 때는 어떻게 uri를 잡아야하나요?

  • spring-boot
  • jpa
  • 아키텍처
  • spring-cloud
  • kafka
  • msa
  • rabbitmq
정영돈 댓글 2 좋아요 0 조회수 274

jjwt 0.12 이상으로 하시는 분들에게..

해결됨

Spring Cloud로 개발하는 마이크로서비스 애플리케이션(MSA)

jjwt가 버전업 되면서 강사님이 업데이트 해주신 코드들도 jwt valid할 때 안되는 경우가 발생하더라고요... 그래서 찾아본결과 다음과 같이 작성하시면 원활하게 동작을 합니다. 참고하세요. private boolean isJwtValid(String jwt) { byte[] secretKeyBytes = Base64.getEncoder().encode(env.getProperty("token.secret").getBytes()); SecretKey signingKey = new SecretKeySpec(secretKeyBytes, SignatureAlgorithm.HS512.getJcaName()); boolean returnValue = true; String subject = null; try { JwtParser jwtParser = Jwts.parser(). verifyWith(signingKey).build(); Jws<Claims> claimsJws = jwtParser.parseSignedClaims(jwt); Claims payload = claimsJws.getPayload(); subject = payload.getSubject(); }catch (Exception ex){ returnValue = false; } if(subject == null || subject.isEmpty()){ returnValue = false; } return returnValue; }

  • spring-boot
  • jpa
  • 아키텍처
  • spring-cloud
  • kafka
  • msa
  • rabbitmq
정영돈 댓글 1 좋아요 2 조회수 666

강의 음성 및 영상

미해결

Microservice 구현 (with EDA,Hexagonal, DDD)

- 학습 관련 질문을 남겨주세요. 상세히 작성하면 더 좋아요! - 먼저 유사한 질문이 있었는지 검색해보세요. - 서로 예의를 지키며 존중하는 문화를 만들어가요. - 잠깐! 인프런 서비스 운영 관련 문의는 1:1 문의하기를 이용해주세요. [내부영역:응용서비스 구현(어플리케이션 헥사곤)-InputPort구현,아우터 포트 정의]강의에서 음성이 불명확하고, 코드 포커스로 확대하신것같은데 잘린부분(클래스 명, 어노테이션 등)이 많아요

  • msa
  • ddd
화를참자 댓글 1 좋아요 0 조회수 371

config-servie 도커로 실행 시 에러 문의

미해결

Spring Cloud로 개발하는 마이크로서비스 애플리케이션(MSA)

안녕하세요. "섹션 16. 애플리케이션 배포 - Docker Container"을 학습하면서 config-service를 Docker로 만들어 실행하면 컨테이너 실행 됐다가 Exit가 되고, "docker logs config-service"로 로그를 보면 아래와 에러가 발생합니다. JDK11 , springboot 2.4.5 버전에 spring-cloud-starter-bootstrap 의존성은 추가 되어 있는 상태입니다. 답변 부탁드립니다. 감사합니다. =================================================================== 2024-03-22 06:50:22.104 WARN 1 --- [ main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'healthContributorRegistry' defined in class path resource [org/springframework/boot/actuate/autoconfigure/health/HealthEndpointConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [ org.springframework.boot.actuate.health .HealthContributorRegistry]: Factory method 'healthContributorRegistry' threw exception; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'configServerHealthIndicator' defined in class path resource [org/springframework/cloud/config/server/config/EnvironmentRepositoryConfiguration.class]: Unsatisfied dependency expressed through method 'configServerHealthIndicator' parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name ' org.springframework.cloud .config.server.config.CompositeConfiguration': Unsatisfied dependency expressed through method 'setEnvironmentRepos' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'defaultEnvironmentRepository' defined in class path resource [org/springframework/cloud/config/server/config/DefaultRepositoryConfiguration.class]: Invocation of init method failed; nested exception is java.lang.IllegalStateException: You need to configure a uri for the git repository. 2024-03-22 06:50:22.113 INFO 1 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Shutting down ExecutorService 'applicationTaskExecutor' 2024-03-22 06:50:22.117 INFO 1 --- [ main] o.apache.catalina.core.StandardService : Stopping service [Tomcat] 2024-03-22 06:50:22.134 INFO 1 --- [ main] ConditionEvaluationReportLoggingListener : Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled. 2024-03-22 06:50:22.149 ERROR 1 --- [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPLICATION FAILED TO START *************************** Description: Invalid config server configuration. Action: If you are using the git profile, you need to set a Git URI in your configuration. If you are using a native profile and have spring.cloud .config.server.bootstrap=true, you need to use a composite configuration. ===================================================================

  • spring-boot
  • jpa
  • 아키텍처
  • spring-cloud
  • kafka
  • msa
  • rabbitmq
댓글 2 좋아요 0 조회수 585

AuthenticationFilter 관련 질문

미해결

Spring Cloud로 개발하는 마이크로서비스 애플리케이션(MSA)

안녕하세요 강사님 좋은 강의 정말 감사드립니다. user service에서 어떤 요청이 들어오든 AuthenticationFilter 를 거치게 되는 것으로 알고 있는데 login 요청을 제외한 다른 요청들은(ex: health-check, welcome 등) AuthenticationFilter 에 존재하는 attemptAuthentication과 loadUserByUsername 메소드는 실행되지 않고 바로 필터가 통과되는 것인가요? 해당 질문은 msa 라기보다 시큐리티 관련 내용인 것 같아 여기에 질문하는 것이 좀 죄송한데 답변 주시면 정말 감사드리겠습니다. 감사합니다!

  • spring-boot
  • jpa
  • 아키텍처
  • spring-cloud
  • kafka
  • msa
  • rabbitmq
chaelynjang 댓글 1 좋아요 0 조회수 451

모듈형 모노리스의 컨테이너화

미해결

Microservice 이해(with MSA패턴)

모듈형 모노리스도 컨테이너화 할 수 있다. 쿠버네티스의 꼭 마이크로서비스만 올리는게 아닌 모노리스도 그냥 올릴 수 있다. 그것만으로도 확장성,배포성,탄력성이 보장이 되기도 한다. 라고 하셨었는데 이 부분에대해서 조금 더 상세하게 알고싶어서 질문드립니다. 확장성,배포성,탄력성 부분에서 어떤 장점들이 있는지 조금 더 디테일하게 궁금합니다. 그렇다면 모노리스 서버 구조의 아키텍처 설계 대신에 항상 쿠버네티스를 쓰는게 좋지 아니한가해서 질문드립니다.

  • 아키텍처
  • msa
긍구름 댓글 1 좋아요 1 조회수 452

KafkaListener DB에서 update 나 delete 이벤트 감지하는방법있을까요?

미해결

Spring Cloud로 개발하는 마이크로서비스 애플리케이션(MSA)

카프라 활용 1~2를 보면서 궁금한 점이 생겼는데 DB서 insert 가 발생했을 때는 @KafkaListener 를 통해 생성된 데이터를 받을 수 있는데 update나 delete 가 발생했을 때는 @KafkaListener로 받을 수 없더라고요? DB에서 update또는 delete문이 발생했을 때의 이벤트도 받으려면 어떻게 해야할까요?

  • spring-boot
  • jpa
  • 아키텍처
  • spring-cloud
  • kafka
  • msa
  • rabbitmq
백엔드 주니어 개발자 댓글 2 좋아요 1 조회수 529

open-telemetry config 예시 github 링크

미해결

[DevOps 정석 2] MSA 환경의 로그 분석 기술 구축을 통한 통합로깅

안녕하세요. 다른 강의 들으시는 분들께 공유드리는 내용입니다. 저는 강의 내용에서 알려주신 config로 적용하면 기동이 되질 않더라고요 helm 차트로 하지 않고 제가 docker 로 올려서 약간의 config 형식 차이가 발생했을 것 같습니다. 수업중인 signoz와 제가 설치한 signoz의 버전 차이가 있으리라 생각합니다. 제가 참고한 open-telemetry config 예시 파일 공유드립니다. https://github.com/open-telemetry/opentelemetry-collector-contrib/blob/main/processor/spanprocessor/testdata/config.yaml spanprocessor 부분 링크이고, 다른 카테고리에서 다른 proceccor 형식도 참고할 수 있습니다. 감사합니다.

  • msa
  • devops
  • monitoring
  • trace
  • observability
  • helm
jiin724 댓글 1 좋아요 0 조회수 384

카프카를 통해 다른 서비스의 데이터를 수정하는 과정에서 예외가 발생했을 경우처리하는 방법이 궁금합니다.

미해결

Spring Cloud로 개발하는 마이크로서비스 애플리케이션(MSA)

두개의 Service가 통신할 때 예외처리 시나리오 A, B 서비스가 있을 때 A 서비스에서 B 서비스로 데이터를 수정 또는 생성하는 요청을 했는데 이 때 개발자가 의도해서 예외를 발생시켰던 예상치못한 예외가 발생했던 간에 예외가 발생해서 B서비스의 데이터를 수정하지 못하는 경우라면 A서비스는 어떻게 롤백시켜주나요? 1번 시나리오에서 하나의 서비스가 추가되어 3개의 Service가 통신할 때 예외처리 시나리오 A서비스에서 B 서비스를 수정 or 생성 하고 C서비스를 수정 or 생성하는 시나리오일 경우 만약에 B서비스에 요청을 했을 때는 성공을하고 C서비스에 요청을 했을 때 실패를 했다면 A서비스로 롤백시켜줘야하고 B서비스도 롤백을 시켜주어야할텐데 이 경우에는 어떻게 롤백처리를 해주나요?? 구글해보니 그냥 추상적으로 오케스트레이션 Saga패턴? 그런걸로 처리한다는데 막연하게 글로만 설명있고 어떤 소프트웨어를 설치해서 코드를 짜면된다 이런건 없어서 어떻게 처리되어야하는건지 감을 못잡겠네요ㅠㅠ. Axon 서버 뭐 이런것도 본거 같기도 하고요.

  • spring-boot
  • jpa
  • 아키텍처
  • spring-cloud
  • kafka
  • msa
  • rabbitmq
백엔드 주니어 개발자 댓글 1 좋아요 0 조회수 339

인기 태그

인프런 TOP Writers

주간 인기글