Category: Spring

0

Spring Boot - MultipartFile 를 이용한 파일 업로드

목차 Spring Boot - StreamingResponseBody Spring Boot - ResourceRegion Spring Boot - 파일 다운로드 서비스 구현하기 Spring Boot - 파일 업로드 서비스 구현하기 Spring Boot - Resource 추상화 Spring Boot - MultipartFile 에서 발생하는 예외 처리 Spring Boot - MultipartFile 를 이용한 파일 업로드 Spring Boot - Part 객체를 이용한 파일 업로드 MultipartFile 인터페이스 multipart/form-data 요청을 처리하기 위해 만들어진 객체 Spring 에서는 멀티파트 요청을 처리 하기 위해 MultipartFile 객체를 제공합니다. public interface MultipartFile extends InputStreamSource { // 전달 받은 Parameter Key값을 가져온다. String getName(); // 파일 명을 가져온다. @Nullable String getOriginalFilename(); // 파일의 ContentType을 가져온다. // pdf 파일의 경우 application/pdf, mp4 파일의 경우 video/mp4, png 파일의 경우 image/png @Nullable String getContentType(); // 전달 받은 Parameter Value값이 비어 있는지 확인한다. boolean isEmpty(); // 전달 받은 파일의 크기를 가져온다. // 파일은 byte 단위로 표시된다. long getSize(); byte[] getBytes() throws IOException; // 전달 받은 파일을 읽기 위한 InputStream을 가져온다. @Override InputStream getInputStream() throws IOException; // MultipartFile 객체를 이용해 Resource(MultipartFileResource) 객체를 반환 받는다. default Resource getResource() { return new MultipartFileResource(this); } // MultipartFile 내 데이터를 전달받은 File 객체에 저장한다. // 한번만 호출이 가능한 메소드다. void transferTo(File dest) throws IOException, IllegalStateException; // MultipartFile 내 데이터를 전달받은 Path 객체에 저장한다. default void transferTo(Path dest) throws IOException, IllegalStateException { FileCopyUtils.copy(getInputStream(), Files.newOutputStream(dest)); }} 파일 업로드 구현파일 업로드를 위한 Controller 구현 multipart/form-data 요청은 Form 형식으로 요청이 오기 때문에 RequestBody 어노테이션이 아니라 RequestParam 어노테이션을 이용해 데이터를 받는다.

0

[Spring Cloud] - 29. Micro Service간 통신 Feign client 예외 처리

목차 [Spring Cloud] - 30. Micro Service간 통신 ErrorDecoder 구현 [Spring Cloud] - 29. Micro Service간 통신 Feign client 예외 처리 [Spring Cloud] - 28. Micro Service간 통신 Feign client [Spring Cloud] - 27. Micro Service간 통신 User serviceserver: port: 0spring: application: name: user-service h2: console: enabled: true settings: web-allow-others: true datasource: username: sa password: driver-class-name: org.h2.Driver url: jdbc:h2:mem:testdb rabbitmq: host: 127.0.0.1 port: 5672 username: guest password: guesteureka: instance: instanceId: ${spring.application.name}:${spring.application.instance_id:${random.value}} client: register-with-eureka: true fetch-registry: true service-url: defaultZone: http://localhost:8761/eurekagreeting: message: Welcome to the Simple E-commerce.management: endpoints: web: exposure: include: refresh, health, beans, busrefreshlogging: level: com.example.userservice.client: DEBUG#token:# expiration_time: 84600000# secret: user_token @SpringBootApplication@EnableDiscoveryClient@EnableFeignClients@Slf4jpublic class UserServiceApplication { public static void main(String[] args){ SpringApplication.run(UserServiceApplication.class, args); } @Bean public BCryptPasswordEncoder passwordEncoder() throws UnknownHostException { return new BCryptPasswordEncoder(); } @Bean @LoadBalanced public RestTemplate getRestTemplate(){ return new RestTemplate(); } @Bean public Logger.Level feignLoggerLevel(){ return Logger.Level.FULL; }} @Overridepublic UserDto getUserByUserId(String userId) { UserEntity userEntity = userRepository.findByUserId(userId); if (userEntity == null) throw new UsernameNotFoundException("User not found"); UserDto userDto = new ModelMapper().map(userEntity, UserDto.class); List<ResponseOrder> orderList = null; try { orderList = orderServiceClient.getOrders(userId); } catch (FeignException ex) { log.error(ex.getMessage()); } userDto.setOrders(orderList); return userDto;}

0

[Spring Cloud] - 28. Micro Service간 통신 Feign client

목차 [Spring Cloud] - 30. Micro Service간 통신 ErrorDecoder 구현 [Spring Cloud] - 29. Micro Service간 통신 Feign client 예외 처리 [Spring Cloud] - 28. Micro Service간 통신 Feign client [Spring Cloud] - 27. Micro Service간 통신 User service// https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-openfeignimplementation 'org.springframework.cloud:spring-cloud-starter-openfeign' @SpringBootApplication@EnableDiscoveryClient@EnableFeignClients@Slf4jpublic class UserServiceApplication { public static void main(String[] args){ SpringApplication.run(UserServiceApplication.class, args); } @Bean public BCryptPasswordEncoder passwordEncoder() throws UnknownHostException { return new BCryptPasswordEncoder(); } @Bean @LoadBalanced public RestTemplate getRestTemplate(){ return new RestTemplate(); }} FeignClient의 name속성에 들어가는 값은 eureka 서버에 등록 돼 있는 Application 이름이다. @FeignClient(name = "order-service")public interface OrderServiceClient { @GetMapping("/order-service/{userId}/orders") List<ResponseOrder> getOrders(@PathVariable String userId);} @Overridepublic UserDto getUserByUserId(String userId) { UserEntity userEntity = userRepository.findByUserId(userId); if (userEntity == null) throw new UsernameNotFoundException("User not found"); UserDto userDto = new ModelMapper().map(userEntity, UserDto.class); List<ResponseOrder> orderList = orderServiceClient.getOrders(userId); userDto.setOrders(orderList); return userDto;}

0

[Spring Cloud] - 27. Micro Service간 통신

목차 [Spring Cloud] - 30. Micro Service간 통신 ErrorDecoder 구현 [Spring Cloud] - 29. Micro Service간 통신 Feign client 예외 처리 [Spring Cloud] - 28. Micro Service간 통신 Feign client [Spring Cloud] - 27. Micro Service간 통신 User Service@SpringBootApplication@EnableDiscoveryClient@Slf4jpublic class UserServiceApplication { public static void main(String[] args){ SpringApplication.run(UserServiceApplication.class, args); } @Bean public BCryptPasswordEncoder passwordEncoder() throws UnknownHostException { return new BCryptPasswordEncoder(); } @Bean public RestTemplate getRestTemplate(){ return new RestTemplate(); }} @Overridepublic UserDto getUserByUserId(String userId) { UserEntity userEntity = userRepository.findByUserId(userId); if (userEntity == null) throw new UsernameNotFoundException("User not found"); UserDto userDto = new ModelMapper().map(userEntity, UserDto.class); // List<ResponseOrder> orders = new ArrayList<>(); // userDto.setOrders(orders); String orderUrl = String.format(env.getProperty("order_service.url"), userId); ResponseEntity<List<ResponseOrder>> orderListResponse = restTemplate.exchange(orderUrl , HttpMethod.GET , null , new ParameterizedTypeReference<List<ResponseOrder>>() {}); List<ResponseOrder> orderList = orderListResponse.getBody(); userDto.setOrders(orderList); return userDto;} application.ymltoken: expiration_time: 84600000 secret: user_token_native_application_changedgateway: ip: 192.168.123.106order_service: url: http://127.0.0.1:8080/order-service/%s/orders token: expiration_time: 84600000 secret: user_token_native_application_changedgateway: ip: 192.168.123.106order_service: url: http://ORDER-SERVICE/order-service/%s/orders @SpringBootApplication@EnableDiscoveryClient@Slf4jpublic class UserServiceApplication { public static void main(String[] args){ SpringApplication.run(UserServiceApplication.class, args); } @Bean public BCryptPasswordEncoder passwordEncoder() throws UnknownHostException { return new BCryptPasswordEncoder(); } @Bean @LoadBalanced public RestTemplate getRestTemplate(){ return new RestTemplate(); }}

0

[Spring Cloud] - 26. Spring Cloud Bus

Config Server// https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-actuatorimplementation 'org.springframework.boot:spring-boot-starter-actuator' // https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-bus-amqpimplementation 'org.springframework.cloud:spring-cloud-starter-bus-amqp' Users Microservice// https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-bus-amqpimplementation 'org.springframework.cloud:spring-cloud-starter-bus-amqp' Gateway Service// https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-bus-amqpimplementation 'org.springframework.cloud:spring-cloud-starter-bus-amqp' Config Serverserver: port: 8888spring: application: name: config-service profiles: active: native cloud: config: server: native: search-locations: file://${user.home}/dev/study/Spring-Cloud/gateway/git-local-repository rabbitmq: host: 127.0.0.1 port: 5672 username: guest password: guestmanagement: endpoints: web: exposure: include: health, busrefresh#spring:# application:# name: config-service# cloud:# config:# server:# git:# uri: https://github.com/ckck803/spring-cloud-config## uri: file:///Users/dongwoo-yang/dev/study/Spring-Cloud/gateway/git-local-repository User Service

0

[Spring Cloud] - 25. Spring Cloud Config Native

목차 [Spring Cloud] - 25. Spring Cloud Config Native [Spring Cloud] - 24. Client Service 에서 Config Server 연동하기 [Spring Cloud] - 23. Spring Cloud Config Server 만들기 [Spring Cloud] - 22. Spring Cloud Config 연동 Actuator 2 [Spring Cloud] - 21. Spring Cloud Config 연동 Actuactor server: port: 8888spring: application: name: config-service profiles: active: native cloud: config: server: native: search-locations: file://${user.home}/dev/study/Spring-Cloud/gateway/git-local-repository#spring:# application:# name: config-service# cloud:# config:# server:# git:# uri: https://github.com/ckck803/spring-cloud-config## uri: file:///Users/dongwoo-yang/dev/study/Spring-Cloud/gateway/git-local-repository

0

[Spring Cloud] - 24. Client Service 에서 Config Server 연동하기

목차 [Spring Cloud] - 25. Spring Cloud Config Native [Spring Cloud] - 24. Client Service 에서 Config Server 연동하기 [Spring Cloud] - 23. Spring Cloud Config Server 만들기 [Spring Cloud] - 22. Spring Cloud Config 연동 Actuator 2 [Spring Cloud] - 21. Spring Cloud Config 연동 Actuactor Client Service 에서 Config Server 로부터 Config 파일 읽어오기// 외부 Config를 가져오기 위한 Dependency 설정implementation 'org.springframework.cloud:spring-cloud-config-server'implementation 'org.springframework.cloud:spring-cloud-starter-bootstrap' spring: cloud: config: uri: http://127.0.0.1:8888 name: ecommerce profiles: active: dev spring: cloud: config: uri: http://127.0.0.1:8888 name: ecommerce profiles: active: prod

0

Spring Boot - 파일 업로드 2

목차 Spring Boot - StreamingResponseBody Spring Boot - ResourceRegion Spring Boot - 파일 다운로드 서비스 구현하기 Spring Boot - 파일 업로드 서비스 구현하기 Spring Boot - Resource 추상화 Spring Boot - MultipartFile 에서 발생하는 예외 처리 Spring Boot - MultipartFile 를 이용한 파일 업로드 Spring Boot - Part 객체를 이용한 파일 업로드 Spring boot 파일 업로드 2 getHeaderNames() part Type으로 전달된 데이터의 모든 해더 이름을 가져온다. getHeader(headerName) getHeader메소드에 헤더 이름을 넘겨주면 해더 이름이 갖는 요청의 모든 해더 정보를 가져온다. getSubmittedFileName() 파일 명을 가져오기 위한 메소드 getInputStream() Part에 저장된 데이터를 가져오기 위한 메소드 write(filepath) write 메소드에 파일이 저장될 File Path를 입력하면 해당 경로에 파일이 저장하는 메소드 Collection<Part> parts = request.getParts();log.info("parts={}", parts);for (Part part : parts) { log.info("==== PART ===="); log.info("name={}", part.getName()); Collection<String> headerNames = part.getHeaderNames(); for (String headerName : headerNames) { log.info("header {}: {}", headerName, part.getHeader(headerName)); } //편의 메서드 //content-disposition; filename log.info("submittedFilename={}", part.getSubmittedFileName()); log.info("size={}", part.getSize()); //part body size //데이터 읽기 InputStream inputStream = part.getInputStream(); String body = StreamUtils.copyToString(inputStream, StandardCharsets.UTF_8); log.info("body={}", body); //파일에 저장하기 if (StringUtils.hasText(part.getSubmittedFileName())) { String fullPath = fileDir + part.getSubmittedFileName(); log.info("파일 저장 fullPath={}", fullPath); part.write(fullPath); }} @Slf4j@Controller@RequestMapping("/servlet/v2")public class ServletUploadControllerV2 { @Value("${file.dir}") private String fileDir; @GetMapping("/upload") public String newFile() { return "upload-form"; } @PostMapping("/upload") public String saveFileV1(HttpServletRequest request) throws ServletException, IOException { log.info("request={}", request); String itemName = request.getParameter("itemName"); log.info("itemName={}", itemName); Collection<Part> parts = request.getParts(); log.info("parts={}", parts); for (Part part : parts) { log.info("==== PART ===="); log.info("name={}", part.getName()); Collection<String> headerNames = part.getHeaderNames(); for (String headerName : headerNames) { log.info("header {}: {}", headerName, part.getHeader(headerName)); } //편의 메서드 //content-disposition; filename log.info("submittedFilename={}", part.getSubmittedFileName()); log.info("size={}", part.getSize()); //part body size //데이터 읽기 InputStream inputStream = part.getInputStream(); String body = StreamUtils.copyToString(inputStream, StandardCharsets.UTF_8); log.info("body={}", body); //파일에 저장하기 if (StringUtils.hasText(part.getSubmittedFileName())) { String fullPath = fileDir + part.getSubmittedFileName(); log.info("파일 저장 fullPath={}", fullPath); part.write(fullPath); } } return "upload-form"; }}

0

[Spring Cloud] - 23. Spring Cloud Config Server 만들기

목차 [Spring Cloud] - 25. Spring Cloud Config Native [Spring Cloud] - 24. Client Service 에서 Config Server 연동하기 [Spring Cloud] - 23. Spring Cloud Config Server 만들기 [Spring Cloud] - 22. Spring Cloud Config 연동 Actuator 2 [Spring Cloud] - 21. Spring Cloud Config 연동 Actuactor Spring Cloud Config Server 의존성 추가// 외부 Config를 가져오기 위한 Dependency 설정implementation 'org.springframework.cloud:spring-cloud-config-server'implementation 'org.springframework.cloud:spring-cloud-starter-bootstrap' Config Server 만들기@EnableConfigServer 어노테이션을 추가하여 Config Server를 만들어 준다. @SpringBootApplication@EnableConfigServerpublic class ConfigServiceApplication { public static void main(String[] args) { SpringApplication.run(ConfigServiceApplication.class, args); }} Config 파일 읽어오기Config 파일 위치에 따라서 Spring Cloud Config Server 에서 Config 파일을 읽어오는 방식이 달라진다.

0

Spring Boot - Part 객체를 이용한 파일 업로드

목차 Spring Boot - StreamingResponseBody Spring Boot - ResourceRegion Spring Boot - 파일 다운로드 서비스 구현하기 Spring Boot - 파일 업로드 서비스 구현하기 Spring Boot - Resource 추상화 Spring Boot - MultipartFile 에서 발생하는 예외 처리 Spring Boot - MultipartFile 를 이용한 파일 업로드 Spring Boot - Part 객체를 이용한 파일 업로드 Spring boot 파일 업로드Form 태그에 enctype 옵션으로 multipart/form-data 를 명시하면 파일을 보낼 수 있다. <form th:action method="post" enctype="multipart/form-data"> <!DOCTYPE HTML><html xmlns:th="http://www.thymeleaf.org"><head> <meta charset="utf-8"></head><body><div class="container"> <div class="py-5 text-center"> <h2>상품 등록 폼</h2> </div> <h4 class="mb-3">상품 입력</h4> <form th:action method="post" enctype="multipart/form-data"> <ul> <li>상품명 <input type="text" name="itemName"></li> <li>파일<input type="file" name="file" ></li> </ul> <input type="submit"/> </form></div> <!-- /container --></body></html> Part 인터페이스Servlet 에서는 HTTP 멀티파트 요청을 처리하기 위해 Part 인터페이스를 제공합니다. getHeaderNames() part Type으로 전달된 데이터의 모든 해더 이름을 가져온다. getContentType() 파일의 ContentType을 가져온다. getHeader(headerName) getHeader메소드에 헤더 이름을 넘겨주면 해더 이름이 갖는 요청의 모든 해더 정보를 가져온다. getSubmittedFileName() 파일 명을 가져오기 위한 메소드 getInputStream() Part에 저장된 데이터를 가져오기 위한 메소드 write(filepath) write 메소드에 파일이 저장될 File Path를 입력하면 해당 경로에 파일이 저장하는 메소드

0

[Spring Cloud] - 22. Spring Cloud Config 연동 Actuator 2

목차 [Spring Cloud] - 25. Spring Cloud Config Native [Spring Cloud] - 24. Client Service 에서 Config Server 연동하기 [Spring Cloud] - 23. Spring Cloud Config Server 만들기 [Spring Cloud] - 22. Spring Cloud Config 연동 Actuator 2 [Spring Cloud] - 21. Spring Cloud Config 연동 Actuactor Spring Cloud로 개발하는 마이크로서비스 애플리케이션 22 - Spring Cloud Config 연동 Actuator 2// 외부 Config를 가져오기 위한 Dependency 설정implementation 'org.springframework.cloud:spring-cloud-starter-config'implementation 'org.springframework.cloud:spring-cloud-starter-bootstrap'// https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-actuatorimplementation 'org.springframework.boot:spring-boot-starter-actuator' spring: cloud: config: uri: http://127.0.0.1:8888 name: ecommerce @SpringBootApplicationpublic class ApigatewayServiceApplication { public static void main(String[] args) { SpringApplication.run(ApigatewayServiceApplication.class, args); } @Bean public HttpTraceRepository httpTraceRepository(){ return new InMemoryHttpTraceRepository(); }} server: port: 8080eureka: client: register-with-eureka: true fetch-registry: true service-url: defaultZone: http://localhost:8761/eurekaspring: application: name: apigateway-service cloud: gateway: default-filters: - name: GlobalFilter args: baseMessage: Spring Cloud Gateway Global Filter preLogger: true postLogger: true routes:# - id: user-service# uri: lb://USER-SERVICE# predicates:# - Path=/user-service/**# filters:# - CustomFilter - id: user-service uri: lb://USER-SERVICE predicates: - Path=/user-service/login - Method=POST filters: - RemoveRequestHeader=Cookie - RewritePath=/user-service/(?<segment>.*), /$\{segment} - id: user-service uri: lb://USER-SERVICE predicates: - Path=/user-service/users - Method=POST filters: - RemoveRequestHeader=Cookie - RewritePath=/user-service/(?<segment>.*), /$\{segment} - id: user-service uri: lb://USER-SERVICE predicates: - Path=/user-service/** - Method=GET filters: - RemoveRequestHeader=Cookie - RewritePath=/user-service/(?<segment>.*), /$\{segment} - AuthorizationHeaderFilter - id: user-service uri: lb://USER-SERVICE predicates: - Path=/user-service/actuator/** - Method=GET, POST filters: - RemoveRequestHeader=Cookie - RewritePath=/user-service/(?<segment>.*), /$\{segment} - id: catalog-service uri: lb://CATALOG-SERVICE predicates: - Path=/catalog-service/** filters: - CustomFilter - id: order-service uri: lb://ORDER-SERVICE predicates: - Path=/order-service/** filters: - CustomFiltertoken: secret: user_tokenmanagement: endpoints: web: exposure: include: refresh, health, beans, httptrace

0

[Spring Cloud] - 21. Spring Cloud Config 연동 Actuactor

목차 [Spring Cloud] - 25. Spring Cloud Config Native [Spring Cloud] - 24. Client Service 에서 Config Server 연동하기 [Spring Cloud] - 23. Spring Cloud Config Server 만들기 [Spring Cloud] - 22. Spring Cloud Config 연동 Actuator 2 [Spring Cloud] - 21. Spring Cloud Config 연동 Actuactor 참고 https://www.baeldung.com/spring-cloud-config-without-git https://mangkyu.tistory.com/253 Spring Cloud Config ServerSpring Cloud Config Server 의존성 추가// 외부 Config를 가져오기 위한 Dependency 설정implementation 'org.springframework.cloud:spring-cloud-config-server'implementation 'org.springframework.cloud:spring-cloud-starter-bootstrap' /{application}/{profile}[/{label}]/{application}-{profile}.yml/{label}/{application}-{profile}.yml/{application}-{profile}.properties/{label}/{application}-{profile}.properties @EnableConfigServer 어노테이션을 추가하여 Config Server를 만들어 준다.

0

[Spring Cloud] - 20. Users Microservice AuthorizationHeaderFilter 추가

목차 [Spring Cloud] - 20. Users Microservice AuthorizationHeaderFilter 추가 [Spring Cloud] - 19. Users Microservice JWT 생성 [Spring Cloud] - 18. Users Microservice 로그인 성공 처리 [Spring Cloud] - 17. Users Microservice Routes 정보 변경 [Spring Cloud] - 16. Users Microservice loadUserByUsername() 구현 [Spring Cloud] - 15. Users Microservice AuthenticationFilter [Spring Cloud] - 14. Users Microservice Order Service [Spring Cloud] - 13. Users Microservice Catalog [Spring Cloud] - 12. Users Microservice 사용자 조회 [Spring Cloud] - 11. Users Microservice Gateway 연동 [Spring Cloud] - 10. Users Microservice 사용자 추가 [Spring Cloud] - 개발하는 마이크로서비스 애플리케이션 9 [Spring Cloud] - Users Microservice Users Microservice AuthorizationHeaderFilter 추가@Component@Slf4jpublic class AuthorizationHeaderFilter extends AbstractGatewayFilterFactory<AuthorizationHeaderFilter.Config> { private Environment env; public AuthorizationHeaderFilter(Environment env){ super(Config.class); this.env = env; } // login -> token -> users (with token) -> header(include token) @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); } String authorizationHeader = request.getHeaders().get(HttpHeaders.AUTHORIZATION).get(0); String jwt = authorizationHeader.replace("Bearer ", ""); if(!isJwtValid(jwt)){ return onError(exchange, "JWT token is not valid", HttpStatus.UNAUTHORIZED); } return chain.filter(exchange); }); } private boolean isJwtValid(String jwt){ boolean returnValue = true; String subject = null; String key = env.getProperty("token.secret"); try { subject = Jwts.parser() .setSigningKey(env.getProperty("token.secret")) .parseClaimsJws(jwt).getBody() .getSubject(); } catch (Exception ex){ returnValue = false; } if(subject == null || subject.isEmpty()){ returnValue = false; } return returnValue; } private Mono<Void> onError(ServerWebExchange exchange, String error, HttpStatus httpStatus) { ServerHttpResponse response = exchange.getResponse(); response.setStatusCode(httpStatus); log.error(error); return response.setComplete(); } public static class Config{ }} // https://mvnrepository.com/artifact/javax.xml.bind/jaxb-api implementation group: 'javax.xml.bind', name: 'jaxb-api', version: '2.3.1' server: port: 8080eureka: client: register-with-eureka: true fetch-registry: true service-url: defaultZone: http://localhost:8761/eurekaspring: application: name: apigateway-service cloud: gateway: default-filters: - name: GlobalFilter args: baseMessage: Spring Cloud Gateway Global Filter preLogger: true postLogger: true routes:# - id: user-service# uri: lb://USER-SERVICE# predicates:# - Path=/user-service/**# filters:# - CustomFilter - id: user-service uri: lb://USER-SERVICE predicates: - Path=/user-service/login - Method=POST filters: - RemoveRequestHeader=Cookie - RewritePath=/user-service/(?<segment>.*), /$\{segment} - id: user-service uri: lb://USER-SERVICE predicates: - Path=/user-service/users - Method=POST filters: - RemoveRequestHeader=Cookie - RewritePath=/user-service/(?<segment>.*), /$\{segment} - id: user-service uri: lb://USER-SERVICE predicates: - Path=/user-service/** - Method=GET filters: - RemoveRequestHeader=Cookie - RewritePath=/user-service/(?<segment>.*), /$\{segment} - AuthorizationHeaderFilter - id: catalog-service uri: lb://CATALOG-SERVICE predicates: - Path=/catalog-service/** filters: - CustomFilter - id: order-service uri: lb://ORDER-SERVICE predicates: - Path=/order-service/** filters: - CustomFiltertoken: secret: user_token

0

[Spring Cloud] - 19. Users Microservice JWT 생성

목차 [Spring Cloud] - 20. Users Microservice AuthorizationHeaderFilter 추가 [Spring Cloud] - 19. Users Microservice JWT 생성 [Spring Cloud] - 18. Users Microservice 로그인 성공 처리 [Spring Cloud] - 17. Users Microservice Routes 정보 변경 [Spring Cloud] - 16. Users Microservice loadUserByUsername() 구현 [Spring Cloud] - 15. Users Microservice AuthenticationFilter [Spring Cloud] - 14. Users Microservice Order Service [Spring Cloud] - 13. Users Microservice Catalog [Spring Cloud] - 12. Users Microservice 사용자 조회 [Spring Cloud] - 11. Users Microservice Gateway 연동 [Spring Cloud] - 10. Users Microservice 사용자 추가 [Spring Cloud] - 개발하는 마이크로서비스 애플리케이션 9 [Spring Cloud] - Users Microservice Users Microservice JWT 생성// https://mvnrepository.com/artifact/io.jsonwebtoken/jjwtimplementation group: 'io.jsonwebtoken', name: 'jjwt', version: '0.9.1' @Slf4jpublic class AuthenticationFilter extends UsernamePasswordAuthenticationFilter { private UserService userService; private Environment env; public AuthenticationFilter(AuthenticationManager authenticationManager, UserService userService, Environment env){ super.setAuthenticationManager( authenticationManager); this.userService = userService; this.env = env; } @Override public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException { try { RequestLogin creds = new ObjectMapper().readValue(request.getInputStream(), RequestLogin.class); Authentication token = new UsernamePasswordAuthenticationToken(creds.getEmail(), creds.getPassword(), new ArrayList<>()); return getAuthenticationManager().authenticate(token); } catch (IOException e){ throw new RuntimeException(e); } } @Override protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException { String username = ((User)authResult.getPrincipal()).getUsername(); UserDto userDetails = userService.getUserDetailsByEmail(username); String token = Jwts.builder() .setSubject(userDetails.getUserId()) .setExpiration(new Date(System.currentTimeMillis() + Long.parseLong(env.getProperty("token.expiration_time")))) .signWith(SignatureAlgorithm.HS512, env.getProperty("token.secret")) .compact(); response.addHeader("token", token); response.addHeader("userId", userDetails.getUserId()); }}

0

[Spring Cloud] - 18. Users Microservice 로그인 성공 처리

목차 [Spring Cloud] - 20. Users Microservice AuthorizationHeaderFilter 추가 [Spring Cloud] - 19. Users Microservice JWT 생성 [Spring Cloud] - 18. Users Microservice 로그인 성공 처리 [Spring Cloud] - 17. Users Microservice Routes 정보 변경 [Spring Cloud] - 16. Users Microservice loadUserByUsername() 구현 [Spring Cloud] - 15. Users Microservice AuthenticationFilter [Spring Cloud] - 14. Users Microservice Order Service [Spring Cloud] - 13. Users Microservice Catalog [Spring Cloud] - 12. Users Microservice 사용자 조회 [Spring Cloud] - 11. Users Microservice Gateway 연동 [Spring Cloud] - 10. Users Microservice 사용자 추가 [Spring Cloud] - 개발하는 마이크로서비스 애플리케이션 9 [Spring Cloud] - Users Microservice Users Microservice 로그인 성공 처리@Slf4jpublic class AuthenticationFilter extends UsernamePasswordAuthenticationFilter { private UserService userService; private Environment env; public AuthenticationFilter(AuthenticationManager authenticationManager, UserService userService, Environment env){ super(authenticationManager); this.userService = userService; this.env = env; } @Override public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException { try { RequestLogin creds = new ObjectMapper().readValue(request.getInputStream(), RequestLogin.class); Authentication token = new UsernamePasswordAuthenticationToken(creds.getEmail(), creds.getPassword(), new ArrayList<>()); return getAuthenticationManager().authenticate(token); } catch (IOException e){ throw new RuntimeException(e); } } @Override protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException { String username = ((User)authResult.getPrincipal()).getUsername(); UserDto userDetails = userService.getUserDetailsByEmail(username); }} @Configuration@EnableWebSecuritypublic class WebSecurity extends WebSecurityConfigurerAdapter { private Environment env; private UserService userService; private BCryptPasswordEncoder bCryptPasswordEncoder; public WebSecurity(Environment evn, UserService userService, BCryptPasswordEncoder bCryptPasswordEncoder){ this.env = env; this.userService = userService; this.bCryptPasswordEncoder = bCryptPasswordEncoder; } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userService).passwordEncoder(bCryptPasswordEncoder); } @Override protected void configure(HttpSecurity http) throws Exception { http.csrf().disable(); http.authorizeRequests().antMatchers("/users/**") .hasIpAddress("192.168.0.2") .and() .addFilter(getAuthenticationFilter()); http.headers().frameOptions().disable(); } private AuthenticationFilter getAuthenticationFilter() throws Exception{ AuthenticationFilter authenticationFilter = new AuthenticationFilter(authenticationManager(), userService, env); return authenticationFilter; }} public interface UserService extends UserDetailsService { UserDto createUser(UserDto userDto); UserDto getUserByUserId(String userId); Iterable<UserEntity> getUserByAll(); UserDto getUserDetailsByEmail(String username);} @Servicepublic class UserServiceImpl implements UserService { UserRepository userRepository; BCryptPasswordEncoder passwordEncoder; @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { UserEntity userEntity = userRepository.findByEmail(username); if (userEntity == null) { throw new UsernameNotFoundException(username); } return new User(userEntity.getEmail() , userEntity.getEncryptedPwd() , true , true , true , true , new ArrayList<>()); } public UserServiceImpl(UserRepository userRepository, BCryptPasswordEncoder passwordEncoder) { this.userRepository = userRepository; this.passwordEncoder = passwordEncoder; } @Override public UserDto createUser(UserDto userDto) { userDto.setUserId(UUID.randomUUID().toString()); ModelMapper modelMapper = new ModelMapper(); modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT); UserEntity userEntity = modelMapper.map(userDto, UserEntity.class); userEntity.setEncryptedPwd(passwordEncoder.encode(userDto.getPwd())); userRepository.save(userEntity); UserDto returnUserDto = modelMapper.map(userEntity, UserDto.class); return returnUserDto; } @Override public UserDto getUserByUserId(String userId) { UserEntity userEntity = userRepository.findByUserId(userId); if (userEntity == null) throw new UsernameNotFoundException("User not found"); UserDto userDto = new ModelMapper().map(userEntity, UserDto.class); List<ResponseOrder> orders = new ArrayList<>(); userDto.setOrders(orders); return userDto; } @Override public Iterable<UserEntity> getUserByAll() { return userRepository.findAll(); } @Override public UserDto getUserDetailsByEmail(String email) { UserEntity userEntity = userRepository.findByEmail(email); if(userEntity == null){ throw new UsernameNotFoundException(email); } UserDto userDto = new ModelMapper().map(userEntity, UserDto.class); return userDto; }}