2, 프레임워크 및 CRUD ​ 스프링 부트 3 스프링 부트 Neo4j 스프링 부트 CKEditor5 스프링 부트 Swagger 스프링 부트 TDD 스프링 AI 스프링 메일 Sender JPA 1+N 문제 ​ MSA ​ Resilience4J 스프링 클라우드 MSA RabbitMQ ​ 시큐리티 ​ 스프링 시큐리티 내부 구조 스프링 시큐리티 7 스프링 시큐리티 6 스프링 시큐리티 7 JWT 스프링 시큐리티 6 JWT 스프링 시큐리티 Passkeys 스프링 시큐리티 7 MFA 스프링 OAuth2 인가 서버 스프링 OAuth2 리소스 서버 스프링 OAuth2 클라이언트 세션 스프링 OAuth2 클라이언트 JWT 스프링 OAuth2 최종 연동 스프링 시큐리티 OIDC 스프링 JWT 심화 스프링 + 리액트 로그인 ​ 데이터베이스 ​ 스프링 부트 데이터베이스 스프링 WebFlux 데이터베이스 엘라스틱서치 엘라스틱서치 플러그인 개발 ​ AI/ML ​ Open WebUI vLLM LLM 서빙 임베딩 벡터 API (NCP Clova) RAG, LoRA 기초 카나나 AI ​ 데이터 관련 ​ 셀레늄 스프링 배치 5 스프링 부트 엑셀 정보 검색 ​ 빌드 ​ 스프링 네이티브 GraalVM ​ 실무 ​ 개발 면접 개발 실무 ​ 기타 ​ 개발자 알쓸신잡 도커 단순 사용 유미 독스 (개발 이야기) 웹 보안 개념 웹 최적화 잡기술 자바 클린 코드 GitHub IntelliJ 실무 가이드 ​ 3, 스프링 부트 3 프레임워크를 기반으로 다양한 스프링 생태계를 활용 할 수 있도록, 생성 부터 기초 구현까지 수행하는 기초 스프링 부트 프로젝트입니다. ​ 스프링 부트 3 ​ 1. 실습 목표 및 스프링 부트란? 2. 프로젝트 다운 및 의존성 3. IntelliJ에서 열기 기타. Gradle 빌드 오류 해결 4. 프로젝트 구조 5. 기본 설정 기타. 프로젝트용 DB 준비 6. 스프링 시큐리티 추가 7. User 도메인 작성 1 8. User 계급화 9. User 도메인 작성 2 10. User CRUD 접근 제한 11. User 엔드포인트 작성 12. 메인 페이지 추가 13. Board 도메인 작성 1 14. User와 JOIN 15. Board 도메인 작성 2 16. Board CRUD 접근 제한 17. Board 엔드포인트 작성 코드 ​ 개발자 유미 코드 리포지토리 바로가기 4, 스프링 부트 3 > 1. 실습 목표 및 스프링 부트란? 안녕하세요 ​ 2024년이 얼마 남지 않았습니다. 백엔드에 관심 있는 학생분들은 다가올 방학에 스프링과 같은 서버 프레임워크를 많이 공부한다고 생각되어 이번 시리즈를 준비하게 되었습니다. 개인적으로 처음 스프링을 접했을 때 너무 어려웠던 기억이 있어, 쉽게 진행하려 하며, 시작부터 동작 원리나 내부 구조를 전부 공부하기 보단 가볍게 한 프로젝트를 따라 하시는 방법을 추천드리고 싶습니다. (그 후 하나씩 심화를 하는 게 좋은 거 같습니다.) 자동차 동작 원리나 다양한 운전 스킬을 알고 타도 좋지만 간단한 조작법만 알고 부딪혀 보는 방법도 재미있게 성장하는 방법인 거 같습니다. ​ 백엔드 개발자는? ​ 백엔드 개발자는 정말 많은 일을 하지만 대표적으로는 하나의 시스템을 동작하는 코딩을 많이 하게 됩니다. 정말 간단하게 말하면 홈페이지를 만든다고 보면 될 거 같습니다. (디자인 보단 데이터 저장 및 삭제와 같은 동작에 관련된) ​ - 네이버 블로그 : 포스팅 화면 제공, 포스팅 결과를 저장 -당근 마켓 앱 뒷단 : 앱에서 판매 완료 터치시 해당 데이터 처리 -네이버 지도 : 프론트가 만든 지도에서 2가지 좌표에 대한 길찾기 수행시 백엔드에서 알고리즘으로 길찾기 진행 -사내나 교내 관리 시스템 -등등 ​ 어떻게 동작할까? ​ 시스템들의 기본 동작 원리는 아래와 같습니다. ​ 그럼 어떤 언어로 코딩을 해야할까? 하면 대부분의 언어로 가능합니다. ​ - 몇 가지 예시 ​ 그럼 스프링은 뭔데? ​ 스프링은 자바 환경에서 서버 코드 작성을 편하게 할 수 있도록 도와주는 프레임워크입니다. ​ ​ 프레임워크 없이 개발을 하게 된다면 JDK 및 서버 엔진과 소통하는 부분도 모두 직접 작성을 해야 합니다. (사소한 설정들을 스프링 프레임워크가 전부 진행합니다.) ​ 이때 프레임워크를 도입하게 된다면 우리가 작성할 코드가 훨씬 줄어듭니다. 스프링 프레임워크는 프로젝트(폴더 내부에 java 파일들이 있음) 형태로 제공되기 때문에 다운 후 프로젝트에 우리 코드를 추가하면 됩니다. ​ 스프링 프레임워크 & 스프링 부트 ​ 스프링 프레임워크와 스프링 부트는 또 다릅니다. 스프링 프레임워크도 이미 많은 부분을 지원하지만 스프링 부트는 그것을 포함하여 더 많은 기능을 지원합니다. ​ ​ 기존에 따로 구성을 해야했던 서버 엔진은 톰캣과, 우리가 작성해야 할 추가적인 코드까지 대부분 포함하고 있어 아주 빠르게 개발을 진행할 수 있습니다. 스프링 부트 또한 프로젝트를 다운로드 받아서 프레임워크에 알맞게 우리 코드를 추가하시면 됩니다. ​ 그럼 우리는? ​ 이제 “스프링 부트” 사용법을 배워 간단한 서버 스크립트를 코딩해보도록 하겠습니다. (게시판과 같은) 스프링 부트 버전은 현재 3.4.0이 최신입니다. (2024.11.22 기준) 스프링 부트는 대략 2.7.X를 기준으로 구현 방법이 크게 바뀌었기 때문에 주의 깊게 신경써야하며 대부분 신규 프로젝트는 스프링 부트 3 이후 버전을 사용합니다. (스프링 부트와 스프링 프레임워크 버전의 상관 관계는 부트에서 3을 더하시면 됩니다.) ​ 다음 : 2. 프로젝트 다운 및 의존성 https://youtu.be/0QSxNyfkWJw 5, 스프링 부트 3 > 2. 프로젝트 다운 및 의존성 스프링 부트 프로젝트 다운로드 ​ ​ Java 기반의 서버 어플리케이션 작성을 위해 위 환경을 구성해야 하지만 몹시 귀찮기 때문에 스프링 부트의 도움을 받겠습니다. 서버엔진 ~ 기본 환경 코드가 제공되기 때문에 빠르게 시작할 수 있습니다. 즉, 아래 과정으로 진행하면 됩니다. 1. 스프링에서 만들어둔 프로젝트를 다운로드 함 2. 해당 프로젝트 코드 스타일(규칙)에 알맞게 우리가 필요한 로직을 추가 ​ - 다운로드 방법 : Spring Initializr 공식적으로 스프링 홈페이지에서 제공을하며, 추가적으로 IntelliJ Ultimate 버전에서도 다운할 수 있습니다. ​ https://start.spring.io/ {"_links":{"gradle-project":{"href":"https://start.spring.io/starter.zip?type=gradle-project{&dependencies,packaging,javaVersion,language,bootVersion,groupId,artifactId,version,name,description,packageName}","templated":true},"gradle-project-kotlin":{"href":"https://start.spring.io/starter.zip?type=... start.spring.io ​ 다운로드 설정 ​ 스프링 부트 프로젝트를 다운로드하기 위해 위 링크에 접속하게 되면 많은 설정들이 요구됩니다. ​ ​ - Project 스프링 부트 프로젝트 개발과 배포시 옆에서 도와주는 도구 선택 ​ - Language 스프링 부트 코딩 언어 - Spring Boot 스프링 부트 버전 설정 - Project Metadata 각종 패키지 및 자바 버전 설정 - Dependencies 스프링 부트 프로젝트에 필요한 의존성 추가 ​ 다운로드 ​ ​ ​ 우리가 앞으로 사용할 기본적인 프로젝트가 다운로드 경로로 다운로드가 됩니다. 이제 이 프로젝트를 압축 해제 후 IDE를 통해 열어주시면, 추가적으로 다운로드가 진행되고 사용하실 수 있습니다. (이 추가적인 다운로드는 Project에서 선택한, Gradle 이란 도구가 도와줍니다.) 다음 시간에는 프로젝트를 진행할 IntelliJ라는 IDE를 설치하고 구성하겠습니다. ​ 이전 : 1. 실습 목표 및 스프링 부트란? 다음 : 3. IntelliJ에서 열기 https://youtu.be/Wh8x5vQams8 6, 스프링 부트 3 > 3. IntelliJ에서 열기 IntelliJ란? ​ IntelliJ는 IDE입니다. VSCode와 같은 코딩을 도와주는 툴입니다. IntelliJ는 JetBrain이라는 회사에서 스프링 부트 프로젝트를 위해 만들었기 때문에 대부분의 사람들이 이 IDE를 사용합니다. - IntelliJ - Ultimate : 비용 지불, 코딩을 도와주는 많은 기능 (자동 완성) - Community : 무료 ​ IntelliJ 다운로드 및 설치 ​ https://www.jetbrains.com/idea/ IntelliJ IDEA – the IDE for Pro Java and Kotlin Development IntelliJ IDEA is the JetBrains IDE for pro development in Java and Kotlin. Built for your comfort, it unlocks productivity, ensures quality code, supports cutting-edge tech, and protects your privacy. www.jetbrains.com ​ ​ ​ 위 부분을 제외하면 모두 다음을 클릭하시면 됩니다. 약 3분 정도 소요된 후 설치가 완료됩니다. ​ 초기 설정 ​ ​ Ultimate 버전의 경우 유료이기 때문에 아래 사항을 선택해야 합니다. ​ - 30일 무료 체험 - 라이센스 등록 - 계정 로그인 : 구독 또는 ac.kr로 인증 받은 교육 계정 - 라이센스 코드 - 회사 인증 서버 ​ Log in to JetBrains Account 를 통해 JetBrains 계정 로그인을 진행하며, 이때 해당 계정은 라이센스가 활성화 되어 있어야 합니다. ​ ​ 로그인 후 Activate 클릭 ​ ​ 기본적인 단축키나 UX 적인 설정을 다른 IDE로 부터 불러오기 설정 (저는 Skip Import) ​ ​ 설정 완료 ​ 프로젝트 열기 ​ 저번 시간 다운로드 받은 스프링 부트 프로젝트를 IntelliJ에서 열어보도록 하겠습니다. ​ ​ 압축 해제 후 → 내부에 동일한 www 폴더가 있다면 해당 폴더를 꺼내기 ​ ​ Open으로 www 스프링 부트 프로젝트 열기 ​ ​ ​ 약, 1분 정도 시간을 통해 Gradle이라는 도구로 나머지 파일들을 다운로드 받은 후 BUILD SUCCESSFUL이라는 메시지가 출력되면 사용할 수 있습니다. 하지만 이 단계에서 많은 오류가 발생하는데 (초기 셋팅의 경우), 보통은 스프링 부트의 JDK와 Gradle의 JDK 버전이 상이하게 동작하기 때문에 발생합니다. ​ ​ 해결 : 기타. Gradle 빌드 오류 해결 ​ 이전 : 2. 프로젝트 다운 및 의존성 다음 : 4. 프로젝트 구조 https://youtu.be/ogGyeoEJxsk 7, 스프링 부트 3 > 기타. Gradle 빌드 오류 해결 초기 설정시 ​ 처음 IntelliJ를 설치하고, 스프링 부트 프로젝트를 열게 된다면 Gradle 빌드 오류를 자주 접하게 됩니다. 해당 문제는 스프링 부트 프로젝트도 JDK 위에서 동작하고 Gradle이라는 보조 도구도 JDK 위에서 동작하는데, 각각이 상이한 JDK 버전을 요구할 때 발생합니다. ​ ​ 해결 방법 ​ Gradle이 구동되는 JDK 환경 버전을 Gradle에 알맞게 설치하시면 됩니다. (스프링 부트 3는 JDK17을 사용해도, Gradle의 경우 JDK23을 따로 잡아줄 수 있습니다.) ​ - Gradle 버전별 호환 JDK​ https://docs.gradle.org/current/userguide/compatibility.html Compatibility Matrix Compatibility Matrix Contents Java Runtime Kotlin Groovy Android Target Platforms The sections below describe Gradle’s compatibility with several integrations. Versions not listed here may or may not work. § Java Runtime Gradle runs on the Java Virtual Machine (JVM), which is often provided by eithe... docs.gradle.org ​ - IntelliJ 설정 ​ ​ 인텔리제이 좌측 상탄의 햄버거 버튼 (Main Menu) 클릭 ​ ​ ​ Build, Execution, Deployment > Build Tools > Gradle 클릭 ​ ​ Gradle에 대한 Gradle JVM을 변경할 수 있습니다. JDK23 ~ JDK17 까지 다양한 JDK를 Apply 후 정상적으로 Build Success가 수행되는 Gradle JDK를 찾으시면 해결 가능합니다. ​ 기타. 스프링 부트 JDK 변경 ​ ​ 인텔리제이 좌측 상탄의 햄버거 버튼 (Main Menu) 클릭 ​ ​ File > Project Structure.. ​ ​ 스프링 프로젝트에 대한 JDK 버전을 선택할 수 있습니다. ​ 기타 ​ - build.gradle 파일의 자바 버전 변경 계속해서 JDK 버전을 변경해도 빌드가 실패할 경우에 대한 해결책으로 build.gradle 파일에 설정된 Java 버전을 변경하는 방법도 존재합니다. ​ java { toolchain { languageVersion = JavaLanguageVersion.of(19) } } ​ https://youtu.be/12makJdk4Tc 8, 스프링 부트 3 > 4. 프로젝트 구조 프로젝트 파일의 구조 ​ 우선 스프링부트 프로젝트 폴더의 구조를 확인하겠습니다. ​ ​ 주로 다룰 부분에 대해 박스 표시를 해두었습니다. ​ 작성할 스프링 부트 구조 ​ ​ 스프링 부트는 프레임워크로 우리의 코드를 작성할 때 전반적인 구조를 따라주어야 합니다. (스프링 프레임워크가 우리의 서버 코드를 읽을때 그 규칙을 따르기 때문) ​ ​ - DTO 데이터를 담아 이동 시키는 클래스 - Controller​ 클라이언트로 부터 요청을 받아 알맞은 Service를 부르거나 정적 자원 (HTML)을 응답해주는 클래스 - Service 게시글 CRUD와 같은 시스템의 주 업무를 수행하는 클래스 - Entity Service단에서 다루는 데이터를 DB 테이블로 부터 가져오기 위해 데이터를 담는 클래스 (DTO와 비슷하지만, Entity를 사용해야 DB 테이블에 데이터를 주고 받을 수 있다.) (하나의 테이블과 연결) - Repository Entity라는 바구니를 기반으로 실제 DB 테이블에 접근해서 SQL과 같은 DB 명령어를 날리는 클래스 (하나의 테이블과 연결) - 단을 나누는 이유 하는 일을 명확히 구분하고 (식당에서 서빙과 주방의 분리), 재사용성을 높이기 위해서 단을 분리하도록 유도하고 있습니다. ​ ​ 스프링 부트 자바 패키지 작성 방법 ​ 이제 위 규칙을 기반으로 클래스를 작성합니다. 그럼 Controller, Service, Repository들이 많이 생기기 때문에 클래스들을 모아둘 패키지를 만들면 됩니다. ​ ​ 간단하게 이렇게 만들면 될까요? 안됩니다. 추후 프로젝트가 커질 경우 너무 많은 클래스가 생기고, 정리가 불가능합니다. 다양한 Package 작성 방법이 존재하며, 정답은 없지만 DDD(도메인 주도 설계)라는 비슷한 일을 하는 Domain(영역)끼리 묶어서 정리하는 방법을 추천드립니다. ​ ​ - Config 스프링 프레임워크에 DB 등록과 같은 여러 설정 클래스 - Controller 클라이언트의 요청을 받고, 데이터나 정적 자원을 응답하는 API 클래스 - Domain 도메인별 Service - Repository 로직 클래스들을 모아둔 주요 서비스 로직 - Util 위의 여러 클래스들이 사용할 수 있는 유틸리티 클래스 (시간 관련, 날짜 관련 등) ​ 이전 : 3. IntelliJ에서 열기 다음 : 5. 기본 설정 https://youtu.be/VOrA9Dfn3vY 9, 스프링 부트 3 > 5. 기본 설정 스프링 프로젝트 전체에 설정을 적용 ​ 구동 환경을 구성했고, 구조도 확인했습니다. 이제 서비스 코드를 작성해도 되지만 추가적인 전체 설정이 필요합니다. 우리가 진행할 설정은 DB연결 및 포트 설정입니다. 앞으로 블로그 서비스를 작성하려면 사용자가 작성한 글에 대한 저장, 유저에 대한 저장이 필요하기 때문에 DB 연결이 필수적입니다. ​ ​ 전체 설정 방법은? ​ 프로젝트 전역에 영향을 미칠 수 있는 설정은 Config 패키지에 Java 클래스를 통해 할 수 있습니다. ​ ​ 다만 Java 클래스 작성은 매우 번거롭기 때문에 “스프링 부트”에서는 간단하게 변수 설정으로 해당 기능을 지원하고 있습니다. (스프링 부트의 장점) ​ 변수 설정 위치 ​ ​ ​ 변수 설정은 프로젝트 src > main > resources 경로에 application.properites라는 파일이 존재하는데, 여기에 작성하시면 됩니다. 작성 방법은 기본적으로 스프링들이 특정 변수를 읽을 수 있도록 변수명 설정이 되어 있는데 이 값을 맞춰주셔야 합니다. ​ MySQL DB 연결 ​ DB를 하나 연결할 계획이고, MySQL DB를 연결할 예정입니다. MySQL, Oracle과 같은 RDB의 경우는 아래 변수 설정을 통해 연결하실 수 있습니다. ​ # RDB 중 연결할 DB 엔진에 대한 드라이브 설정 spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver # DB가 구동되는 IP (주소) spring.datasource.url=jdbc:mysql://아이피:포트/디비명?useSSL=false&useUnicode=true&serverTimezone=Asia/Seoul&allowPublicKeyRetrieval=true # 접속 아이디/비밀번호 spring.datasource.username=root spring.datasource.password=root ​ - JPA 설정 JPA란 자바 클래스에서 SQL 쿼리로 데이터를 입출력하는 것이 아닌, 자바 메소드 형태로 다룰 수 있도록 만든 인터페이스 입니다. (따라서 우리는 직접 SQL 쿼리가 아닌 메소드를 사용해서 CRUD를 진행할 예정이고, 이에 필요한 설정도 합니다.) ​ ​ # 자바 클래스 기반으로 MySQL 테이블 자동 생성 여부 (update : 스프링 기반으로 MySQL 테이블 업데이트) spring.jpa.hibernate.ddl-auto=update # 스프링 Entity와 MySQL 테이블 필드간 필드명 작명 전략 spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl ​ (연결할 DB가 없으신 경우 생성 방법을 다음 영상을 통해 올리겠습니다.) ​ 포트 설정 ​ server.port=8080 ​ 이전 : 4. 프로젝트 구조 다음 : 6. 스프링 시큐리티 추가 https://youtu.be/YkYeJJCfjgw 10, 스프링 부트 3 > 기타. 프로젝트용 DB 준비 프로젝트용 DB 준비 ​ 5강에서 스프링 부트와 DB를 연결했습니다. 이때 DB 준비가 어려우신 분들을 위해 MySQL 데이터베이스를 준비하는 방법에 대해 알려드리겠습니다. ​ AWS RDS 빌리기 ​ https://youtu.be/DG4qwH9bUYA?si=628-cqZnYdzlwNvm ​ ​ 1분 50초 부터 시청하시면 됩니다. ​ ​ 도커 설치 후 MySQL 이미지 실행 ​ 도커 데스크탑을 통해서 MySQL 도커 환경을 구성하실 수 있습니다. ​ - 다운로드​ https://www.docker.com/products/docker-desktop/ Docker Desktop: The #1 Containerization Tool for Developers | Docker Docker Desktop is collaborative containerization software for developers. Get started and download Docker Desktop today on Mac, Windows, or Linux. www.docker.com ​ 페이지 하단으로 가시면 Download Docker Desktop을 통해 다운로드 가능 ​ - 설치 ​ - 설치 후 로그인 결제는 필요 없지만, 로그인을 진행하셔야 사용이 가능합니다. (간혹 로그인 없이도 사용 가능) - 도커 데스크탑 메인화면 진입 ​ ​ - 상단 검색창 MySQL 검색​ ​ ​ - MySQL 컨테이너 옵션 설정 ​ ​ - 실행 확인 ​ ​ 기타 ​ 앞으로 여러 프로젝트를 진행하실 때, 내 로컬 컴퓨터에 여러개의 MySQL을 설치해야 할 경우 도커를 활용하시면 매우 좋습니다. ​ https://youtu.be/QQjZ3oOIHJM 11, 스프링 부트 3 > 6. 스프링 시큐리티 추가 인증/인가 ​ 대부분의 서비스는 인증/인가가 필요합니다. - 인증/인가 예시 - 인증 : 호텔 프론트에서 특정 사람에게 키를 부여 - 인가 : 호텔의 각각의 서비스 (방, 라운지, 커뮤니티)에서 접근하는 사람을 검증 (여기서 인증을 했다면, 인증 종류에 따라 통과) 아무나 볼 수 있는 게시글 작성 플랫폼을 구축하더라도 작성, 수정, 삭제를 위해서는 인증/인가가 요구됩니다. ​ 인가는 클라이언트가 우리 스프링 부트 Controller에 접근할 때, 진행되며 설정 인가 값 이상의 값을 인증으로 부터 부여 받았는지 검증합니다. 이런 인증/인가를 처음부터 구현하기는 어렵기 때문에 “스프링 시큐리티”라는 의존성을 활용하겠습니다. ​ 스프링 시큐리티 의존성 추가 ​ 처음 프로젝트 구성시에는 시큐리티 의존성을 추가하지 않았지만, 추가로 넣을 수 있습니다. ​ - start.spring.io ​ - build.gradle ​ implementation 'org.springframework.boot:spring-boot-starter-security' testImplementation 'org.springframework.security:spring-security-test' ​ 프로젝트에 시큐리티 설정 ​ DB 연결과 같이 “스프링 시큐리티”도 스프링 부트 프로젝트 전체에 설정을 적용 시키기 위한 Config 클래스 작성이 요구 됩니다. Config 클래스 대신 application.properites 파일 변수 설정으로 가능하지만, 조금 더 복잡한 설정을 위해 Config 클래스를 작성하겠습니다. ​ - config>SecurityConfig @Configuration @EnableWebSecurity public class SecurityConfig { // 스프링 시큐리티에서는 비밀번호를 암호화해서 저장해야 합니다. 이때 사용할 암호화 클래스입니다. @Bean public BCryptPasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } // 시큐리티 설정 @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { // csrf 보안 해제 (개발 환경에서 설정시 복잡성) http .csrf(csrf -> csrf.disable()); // 접근 경로별 인가 설정 http .authorizeHttpRequests(auth -> auth .requestMatchers("/**").permitAll()); // 로그인 방식 설정 Form 로그인 방식 http .formLogin(Customizer.withDefaults()); return http.build(); } } ​ 기타 : 개발자 유미 채널에 시큐리티 관련 시리즈 ​ “스프링 시큐리티” : 아주 기초적인 세션 방식 시큐리티 구현 “스프링 시큐리티 JWT” : 기초적인 JWT(STATELESS) 방식 시큐리티 구현 “스프링 시큐리티 내부 구조” : 스프링 시큐리티의 개념과 자세한 동작 원리 “스프링 OAuth2 클라이언트 세션” : OAuth2 소셜 로그인 후 세션 방식 시큐리티 구현 ("스프링 시큐리티"와 형제 관계) “스프링 OAuth2 클라이언트 JWT” : OAuth2 소셜 로그인 후 JWT 방식 시큐리티 구현 ("스프링 시큐리티 JWT"와 형제 관계) "스프링 시큐리티 OIDC" : OAuth2 기반 OIDC 소셜 로그인 “스프링 JWT 심화” : JWT를 조금 더 심화적으로 다루는 시리즈 “스프링 OAuth2 인가 서버” : 직접 소셜 로그인 제공자 처럼 OAuth2 인가 서버 구현 “스프링 OAuth2 리소스 서버” : 인가 서버와 연동된 리소스 서버 구현 “스프링 OAuth2 최종 연동” : OAuth2 시리즈 연동 ​ 이전 : 5. 기본 설정 다음 : 7. User 도메인 작성 1 https://youtu.be/lv3zXFzx0mU 12, 스프링 부트 3 > 7. User 도메인 작성 1 User 도메인 구현 ​ 우리가 만드는 블로그 서비스는 아래와 같은 대략적인 요구사항이 있는 것을 알 수 있습니다. - 유저별 게시글 CRUD - 유저별 인증/인가 (로그인) 그렇다면 우리 서비스는 유저에 대한 정보를 저장하고, 사용(CRUD)할 수 있는 User 영역이 필요합니다. 즉, User를 관리하기 위한 Entity(테이블) - Service(테이블에 대한 CRUD) - Controller(API)를 만들어야 합니다. ​ ​ 작성 순서 ​ 아무튼, User를 저장하고 관리해야 합니다. 생각을 나열하면 대략적으로 구현해야 할 부분이 정해집니다. - 저장 - User를 저장할 테이블 - 행위 - 회원가입 : Create - 회원정보 수정 : Update - 회원탈퇴 : Delete 또는 Update를 통한 블락 - 회원정보 읽기 : Read - 로그인 : Read 1. 테이블 생성 : Entity 우선 User에 대한 특정 행위를 하기 위한 User 정보를 저장할 테이블을 생성합니다. 2. 테이블에 행위를 수행할 메소드 작성 : Service 다음 User 테이블에 행위를 수행할 Service단 CRUD 메소드를 작성합니다. 3. User 도메인 메소드와 다른 도메인 메소드를 조합한 API 작성 : Controller 이제 우리가 작성한 User 테이블을 다룰 수 있는 Service 메소드를 클라이언트가 사용하기 편하게 여러 Service 메소드와 조합하여 Controller를 작성합니다. UserEntity 작성 ​ - domain>user>entity>UserEntity import jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; import jakarta.persistence.GenerationType; import jakarta.persistence.Id; import lombok.Getter; import lombok.Setter; @Entity @Getter @Setter public class UserEntity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String username; private String password; private String nickname; } ​ - domain>user>repository>UserRepository import com.devyummi.www.domain.user.entity.UserEntity; import org.springframework.data.jpa.repository.JpaRepository; public interface UserRepository extends JpaRepository { } ​ 이전 : 6. 스프링 시큐리티 추가 다음 : 8. User 계급화 https://youtu.be/bZaOcZWQnZo 13, 스프링 부트 3 > 8. User 계급화 인가시 계급의 필요 ​ 아래 예시를 통해 2가지 계급 체계에 대해 알아보겠습니다. - 수직적 계급 : 호텔에 있는 사람들의 계급을 나눔, - 직원 : 호텔에 대한 관리 감독과 모든 장소 접근 권한 - VIP 고객 : 호텔의 대부분의 서비스를 이용 가능 - 일반 고객 : 호텔의 객실 서비스만 이용 가능 - 수평적 계급 : “일반 고객”은 여러 객실 중 자신의 객실만 접근 가능 (블로그 서비스 모든 일반 유저도 자신의 글만 삭제 가능) 이번 시간에는 수직적인 계급을 도입하겠습니다. ​ ROLE과 enum ​ - ROLE 인증/인가를 쉽게 구현하도록 도와주는 “스프링 시큐리티”는 ROLE이라는 속성을 가지고 수직적인 계급을 관리합니다. 따라서 UserEntity라는 유저 정보를 저장하는 테이블에 role 필드를 만들겠습니다. - enum 단, ROLE의 경우 String 형태의 필드 보다는 미리 계급을 정해서 enum화 시켜주는 것이 좋습니다. (HTML의 input 태그 대신 select 태그와 같이 시스템이 가지는 수직 계급을 나열 함) ​ UserRoleType ​ - UserRoleType : enum import lombok.Getter; @Getter public enum UserRoleType { ADMIN("어드민"), USER("유저"); private final String description; UserRoleType(String description) { this.description = description; } } ​ - UserEntity에 추가​ import jakarta.persistence.*; import lombok.Getter; import lombok.Setter; @Entity @Getter @Setter public class UserEntity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String username; private String password; private String nickname; @Enumerated(EnumType.STRING) private UserRoleType role; } ​ ROLE 계층 추가 우리 서비스에 대해 “수직적 계급”을 만들었지만, 스프링 시큐리티 프레임워크는 우리가 만든 enum 계급을 알지 못합니다. 따라서 SecurityConfig에 @Bean 메소드를 등록하여 우리의 계급 체계를 알려주겠습니다. ​ - SecurityConfig.java // 시큐리티 role 계층화 @Bean public RoleHierarchy roleHierarchy() { return RoleHierarchyImpl.withRolePrefix("ROLE_") .role(UserRoleType.ADMIN.toString()).implies(UserRoleType.USER.toString()) .build(); } ​ - ROLE 계층 관련하여 자세한 글 ​ Role Hierarchy 시큐리티 6.3.X 이후 버전의 Role Hierarchy ​ 이전 : 7. User 도메인 작성 1 다음 : 8. User 도메인 작성 2 https://youtu.be/rrA-76wRl7E 14, 스프링 부트 3 > User 도메인 작성 2 User 정보 저장소에 대한 CRUD ​ 시스템에서 필요한 User 정보 저장소인 UserEntity 구현을 마쳤고, 이제 이 저장소에 데이터를 저장, 읽기, 수정, 삭제를 진행할 CRUD 메소드를 구현해야 합니다. ​ ​ UserService 클래스 추가 ​ User 도메인에서 UserEntity 데이터 저장소에 CRUD 명령을 내릴 메소드를 구현할 Service단 클래스를 생성합니다. ​ - domain>user>service>UserService import com.devyummi.www.domain.user.repository.UserRepository; import org.springframework.stereotype.Service; @Service public class UserService { private final UserRepository userRepository; private final BCryptPasswordEncoder bCryptPasswordEncoder; public UserService(UserRepository userRepository, BCryptPasswordEncoder bCryptPasswordEncoder) { this.userRepository = userRepository; this.bCryptPasswordEncoder = bCryptPasswordEncoder; } } ​ CRUD : Create 작성 ​ - UserEntity에 회원 등록 : 즉, 회원 가입 회원 가입시에는 앞에서 부터 정보를 받아 저장을 해야 합니다. 즉, DTO → Service → Entity → Repository 과정이 필요하며, DTO가 필요합니다. ​ - 회원 정보를 앞에서 받아 올 DTO import lombok.Getter; import lombok.Setter; @Getter @Setter public class UserRequestDTO { private String username; private String password; private String nickname; } ​ - Service단에 메소드 // 유저 한 명 생성 @Transactional public void createOneUser(UserRequestDTO dto) { String username = dto.getUsername(); String password = dto.getPassword(); String nickname = dto.getNickname(); // 동일한 username이 있는지 확인 if (userRepository.existsByUsername(username)) { return; } // 유저에 대한 Entity 생성 : DTO -> Entity 및 추가 정보 set UserEntity entity = new UserEntity(); entity.setUsername(username); entity.setPassword(bCryptPasswordEncoder.encode(password)); entity.setNickname(nickname); entity.setRole(UserRoleType.USER); // Entity 저장 userRepository.save(entity); } ​ - 이미 존재하는 유저인지 확인 UserRepository에서 DB에 존재 확인 쿼리를 날리는 메소드 구현 Boolean existsByUsername(String username); ​ CRUD : Read 작성 1 ​ - UserEntity에 존재하는 특정 유저 읽기 DB 테이블에 저장되어 있는 유저 데이터를 확인해야 하는 경우가 있습니다. 사용자로 부터 특정 유저의 unique한 username 데이터를 받아 select를 진행해야 합니다. 즉, 특정 username → Service → Repository → Entity → Service → DTO 과정이 필요합니다. - 회원 정보를 응답할 DTO import lombok.Getter; import lombok.Setter; @Getter @Setter public class UserResponseDTO { private String username; private String nickname; private String role; } ​ - Service단에 메소드 // 유저 한 명 읽기 @Transactional(readOnly = true) public UserResponseDTO readOneUser(String username) { UserEntity entity = userRepository.findByUsername(username).orElseThrow(); UserResponseDTO dto = new UserResponseDTO(); dto.setUsername(entity.getUsername()); dto.setNickname(entity.getNickname()); dto.setRole(entity.getRole().toString()); return dto; } ​ - 특정 username 기반으로 테이블에서 데이터를 찾는 쿼리 Optional findByUsername(String username); ​ CRUD: Read 작성 2 ​ - UserEntity에 존재하는 모든 유저 읽기 어드민 대시보드에서 사용할 가능성이 높은 UserEntity에 존재하는 모든 유저를 읽는 메소드도 작성하겠습니다. - Service단에 메소드 // 유저 모두 읽기 @Transactional(readOnly = true) public List readAllUsers() { List list = userRepository.findAll(); List dtos = new ArrayList<>(); for (UserEntity user : list) { UserResponseDTO dto = new UserResponseDTO(); dto.setUsername(user.getUsername()); dto.setNickname(user.getNickname()); dto.setRole(user.getRole().toString()); dtos.add(dto); } return dtos; } ​ CRUD : Read 로그인용 ​ - 로그인 동작 방식은? 로그인은 HTML Form 태그로 클라이언트가 보낸 username/password를 서비스단에서 username 기반으로 유저를 조회하여 비교 검증하는 플로우라고 생각하시면 됩니다. 다만, 스프링 시큐리티 프레임워크를 사용하면 특수한 케이스로 동작하기 때문에 “비교 검증 부” 같은 경우 자동으로 생성되고, UserEntity 테이블에서 특정 username 데이터를 읽는 메소드만 시큐리티 형식으로 구현하면 됩니다. - UserDetailsService 구현 UserService 클래스에 스프링 시큐리티의 인터페이스인 UserDetailsService를 구현하도록 해야 합니다. ​ @Service public class UserService implements UserDetailsService { } ​ - 시큐리티 전용 로그인용 메소드 Override // 유저 로그인 (로그인 같은 경우 읽기지만, 시큐리티 형식으로 맞춰야 합니다.) @Transactional(readOnly = true) @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { UserEntity entity = userRepository.findByUsername(username).orElseThrow(); return User.builder() .username(entity.getUsername()) .password(entity.getPassword()) .roles(entity.getRole().toString()) .build(); } ​ CRUD : Update 작성 ​ - UserEntity에 존재하는 특정 유저 수정 : 즉, 회원 정보 수정 username과 같은 unique 데이터를 제외하면 회원 정보를 수정하는 일이 종종 발생합니다. (닉네임 변경, 비밀번호 변경) 수정 흐름은 아래와 같습니다. 1. 사용자가 수정할 username과 수정할 데이터를 DTO로 보냄 2. Service단에서 username 기반으로 데이터를 Read 3. DTO에서 받은 데이터를 기반으로 기존 데이터에 신규 값을 초기화 4. 다시 저장 - Service단에 메소드 // 유저 한 명 수정 @Transactional public void updateOneUser(UserRequestDTO dto, String username) { // 기존 유저 정보 읽기 UserEntity entity = userRepository.findByUsername(username).orElseThrow(); if (dto.getPassword() != null && !dto.getPassword().isEmpty()) { entity.setPassword(bCryptPasswordEncoder.encode(dto.getPassword())); } if (dto.getNickname() != null && !dto.getNickname().isEmpty()) { entity.setNickname(dto.getNickname()); } userRepository.save(entity); } ​ CRUD : Delete 작성 ​ - UserEntity에 존재하는 특정 유저 삭제 : 즉, 회원 탈퇴 특정 username 기반으로 회원 데이터를 삭제하는 방법입니다. - Service단에 메소드 // 유저 한 명 삭제 @Transactional public void deleteOneUser(String username) { userRepository.deleteByUsername(username); } ​ - 특정 username 기반으로 테이블에서 데이터를 지우는 쿼리 @Transactional void deleteByUsername(String username); ​ 이전 : 8. User 계급화 다음 : 10. User CRUD 접근 제한 https://youtu.be/08XB9OmZaeQ 15, 스프링 부트 3 > 10. User CRUD 접근 제한 User 계급화를 한 이유 ​ 8. User 계급화 - 수직적 계급 : 여러 유저를 Class 별로 관리하기 위해 - ADMIN - USER - 수평적 계급 : 동일한 계급 내부에서 각각의 유저를 관리하기 위해 (같은 USER 계급이라도 자신의 계정, 자신의 글만 삭제 가능하게) - 구현 수직적 계급은 메소드에 접근하는 유저의 ROLE 체크를 진행합니다. → 시큐리티로 편하게 설정 가능 수평적 계급은 메소드에 접근하려는 username과 현재 로그인한 유저의 username을 비교합니다. → 직접 구현 ​ 메소드 구현 ​ - UserService // 유저 접근 권한 체크 public Boolean isAccess(String username) { // 현재 로그인 되어 있는 유저의 username String sessionUsername = SecurityContextHolder.getContext().getAuthentication().getName(); // 현재 로그인 되어 있는 유저의 role String sessionRole = SecurityContextHolder.getContext().getAuthentication().getAuthorities().iterator().next().getAuthority(); // 수직적으로 ADMIN이면 무조건 접근 가능 if ("ROLE_ADMIN".equals(sessionRole)) { return true; } // 수평적으로 특정 행위를 수행할 username에 대해 세션(현재 로그인한) username과 같은지 if (username.equals(sessionUsername)) { return true; } // 나머지 다 불가 return false; } ​ 이전 : 9. User 도메인 작성 2 다음 : 11. User 엔드포인트 작성 https://youtu.be/k-X7XtO-fA0 16, 스프링 부트 3 > 11. User 엔드포인트 작성 회원 관련 엔드포인트 생성 ​ ​ User 도메인에 특정한 행위 (CRUD)를 할 수 있는 UserService단을 생성했습니다. ​ 이제 사용자로 부터 POST “/user/join” 이라는 경로에 데이터를 보냈을때 UserService의 addOneUser()가 실행되도록 Controller 엔드포인트를 만들어 보겠습니다. ​ 컨트롤러 생성 ​ 클라이언트로 부터 uri에 따라 특정한 페이지를 주고, api 호출을 받는 부분은 모두 Controller 클래스에 작성을 해야 합니다. 영상을 위해 하나의 Controller에 유저 관련된 기능을 다 넣을 예정이지만 로그인, 회원가입, 유저 정보와 같이 세부 분야별로 분리하셔도 무방합니다. - controller>UserController import com.devyummi.www.domain.user.service.UserService; import org.springframework.stereotype.Controller; @Controller public class UserController { private final UserService userService; public UserController(UserService userService) { this.userService = userService; } } ​ API 엔드포인트는? ​ 간단하게 몇 가지 엔드포인트를 작성하겠습니다. - 회원 가입 페이지 : GET : “/user/join” - 회원 가입 진행 : POST : “/user/join” - 회원 수정 페이지 : GET : “/user/update/{username}” - 회원 수정 진행 : POST : "/user/update/{username}” - 회원 삭제 진행 : POST : “/user/delete/{username}” - 로그인 페이지 : GET : “/login” (스프링 시큐리티가 기본 제공) - 로그인 진행 : POST : “/login” (스프링 시큐리티가 기본 제공) ​ 구현 : 회원 가입 ​ - Controller 메소드 작성 // 회원 가입 : 페이지 응답 @GetMapping("/user/join") public String joinPage() { return "join"; } // 회원 가입 : 수행 @PostMapping("/user/join") public String joinProcess(UserRequestDTO dto) { userService.createOneUser(dto); return "redirect:/login"; } ​ - 회원가입 페이지

join page


​ - 시큐리티 API 접근 설정 : SecurityConfig.java .requestMatchers("/user/join").permitAll() ​ 구현 : 회원 수정 ​ - Controller 메소드 작성 // 회원 수정 : 페이지 응답 @GetMapping("/user/update/{username}") public String updatePage(@PathVariable("username") String username, Model model) { // 본인 또는 ADMIN 권한만 접근 가능 if (userService.isAccess(username)) { UserResponseDTO dto = userService.readOneUser(username); model.addAttribute("USER", dto); return "update"; } return "redirect:/login"; } // 회원 수정 : 수행 @PostMapping("/user/update/{username}") public String updateProcess(@PathVariable String username, UserRequestDTO dto) { // 본인 또는 ADMIN 권한만 접근 가능 if (userService.isAccess(username)) { userService.updateOneUser(dto, username); } return "redirect:/user/update/" + username; } ​ - 회원 수정 페이지

user update page


​ - 시큐리티 API 접근 설정 : SecurityConfig.java .requestMatchers("/user/update/**").hasRole("USER") ​ 이전 : 10. User CRUD 접근 제한 다음 : 12. 메인 페이지 추가 https://youtu.be/Rf8LXibDLo4 17, 스프링 부트 3 > 12. 메인 페이지 추가 메인 페이지 추가 ​ 간단하게 메인페이지를 하나 추가하겠습니다. - MainController import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; @Controller public class MainController { @GetMapping("/") public String mainPage() { return "main"; } } ​ - main.mustache main page

main page

login
logout
join
​ - 시큐리티 인가 설정 : SecurityConfig.java .requestMatchers("/").permitAll() ​ mustache 한글 표시 문제 ​ mustache 템플릿 엔진에 한글 입력시 아래와 같은 문제가 발생합니다. - 한글 표시 불가능 : ????와 같이 표시 - 한글 입력 불가능 : 입력 후 다른곳에서 확인하면 입력한 문자가 아님 이런 문제는 UTF-8 문제로 UTF-8 설정을 진행하시면 됩니다. ​ - application.properties 설정 파일 server.servlet.encoding.charset=UTF-8 server.servlet.encoding.force=true spring.mustache.servlet.expose-request-attributes=true ​ 이전 : 11. User 엔드포인트 작성 다음 : 13. Board 도메인 작성 1 https://youtu.be/83W36h-y5q4 18, 스프링 부트 3 > 13. Board 도메인 작성 1 Board 도메인 구현 ​ User 도메인 구현을 완료했고, 블로그 서비스에 필요한 게시판 도메인을 만들겠습니다. - 게시글 CRUD 앞서 User에 대한 도메인 구현을 완료했기 때문에 빠르게 진행하겠습니다. ​ 작성 순서 ​ - 저장 - Board(게시글)를 저장할 테이블 - 행위 - 게시글 저장 : Create - 게시글 수정 : Update - 게시글 읽기 : Read - 게시글 삭제 : Delete 1. 테이블 생성 : Entity 우선 Board에 대한 특정 행위를 하기 위한 Board 정보를 저장할 테이블을 생성합니다. 2. 테이블에 행위를 수행할 메소드 작성 : Service 다음 Board 테이블에 행위를 수행할 Service단 CRUD 메소드를 작성합니다. 3. Board 도메인 메소드와 다른 도메인 메소드를 조합한 API 작성 : Controller 이제 우리가 작성한 Board 테이블을 다룰 수 있는 Service 메소드를 클라이언트가 사용하기 편하게 여러 Service 메소드와 조합하여 Controller를 작성합니다. ​ BoardEntity 작성 ​ ​ - domain>board>entity>BoardEntity.java​ import jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; import jakarta.persistence.GenerationType; import jakarta.persistence.Id; import lombok.Getter; import lombok.Setter; @Entity @Getter @Setter public class BoardEntity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String title; @Column(columnDefinition = "TEXT") private String content; } ​ - domain>board>repository>BoardRepository.java import com.devyummi.www.domain.board.entity.BoardEntity; import org.springframework.data.jpa.repository.JpaRepository; public interface BoardRepository extends JpaRepository { } ​ 이전 : 12. 메인 페이지 추가 다음 : 14. User와 JOIN https://youtu.be/O9ufihA-x5o 19, 스프링 부트 3 > 14. User와 JOIN User와 Board 의 상관 관계 ​ 서비스에서 활동하는 유저는 게시글을 작성합니다. 따라서 한명의 유저는 0개 이상의 게시글을 가질 수 있습니다. (User 1에 대해 Board 다) 그럼 User 도메인과 Board 도메인간의 연관 관계가 발생합니다. 즉, SQL에서는 JOIN이 걸릴 수 있습니다. ​ ​ 생각나는 방법 ​ 이를 스프링 부트쪽에서는 어떻게 처리해야 할까요? 아주 간단하게 생각하면 아래와 같이 할 수 있지만, 스프링 부트에서 SQL과 같이 User를 들고 왔을때 관련된 Board를 들고오거나 반대 작업을 수행하기가 어렵습니다. ​ - BoardEntity 에서 : 가능은 하지만 비추천 @Entity @Getter @Setter public class BoardEntity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String title; private String content; // 게시글에 UserEntity의 username 적어주기? private String username; } ​ JOIN으로 해결 : 1대다 양항뱡 ​ - BoardEntity : 다쪽 @Entity @Getter @Setter public class BoardEntity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String title; @Column(columnDefinition = "TEXT") private String content; @ManyToOne private UserEntity userEntity; } ​ - UserEntity : 1쪽 @Entity @Getter @Setter public class UserEntity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String username; private String password; private String nickname; @Enumerated(EnumType.STRING) private UserRoleType role; @OneToMany(mappedBy = "userEntity", cascade = CascadeType.ALL, orphanRemoval = true) private List boardEntityList = new ArrayList<>(); // 유저에 대해 새로운 글을 추가할 때 : 추가할 글을 받아서 연관관계에 매핑해줌 public void addBoardEntity(BoardEntity entity) { entity.setUserEntity(this); boardEntityList.add(entity); } // 유저에 대해 기존 글을 삭제할 때 : 삭제할 글을 받아서 연관관계에서 뺌 public void removeBoardEntity(BoardEntity entity) { entity.setUserEntity(null); boardEntityList.remove(entity); } } ​ 이렇게 1대다 양방향 매핑을 걸면 각각의 Entity를 불러와도 서로 연관된 Entity도 함께 볼 수 있습니다. (매핑에 대해서는 아주 내용이 많기 때문에 추후 스프링 Data JPA에 관해 자세하게 다루겠습니다.) ​ 이전 : 13. Board 도메인 작성 1 다음 : 15. Board 도메인 작성 2 https://youtu.be/TBIc1oJ3gPE 20, 스프링 부트 3 > 15. Board 도메인 작성 2 Board 정보 저장소에 대한 CRUD ​ 시스템에서 필요한 Board 정보 저장소인 BoardEntity 구현을 마쳤고, 이제 이 저장소에 데이터 저장, 읽기, 수정, 삭제를 진행할 CRUD 메소드를 구현해야 합니다. ​ ​ BoardService 클래스 추가 ​ Board 도메인에서 BoardEntity 데이터 저장소에 CRUD 명령을 내릴 메소드를 구현할 Service단 클래스를 생성합니다. ​ - domain>board>service>BoardService.java import com.devyummi.www.domain.board.repository.BoardRepository; import com.devyummi.www.domain.user.repository.UserRepository; import org.springframework.stereotype.Service; @Service public class BoardService { private final BoardRepository boardRepository; private final UserRepository userRepository; public BoardService(BoardRepository boardRepository, UserRepository userRepository) { this.boardRepository = boardRepository; this.userRepository = userRepository; } } ​ CRUD : create 작성 ​ - BoardEntity에 게시글 등록 게시글 등록시에는 앞에서 부터 정보를 받아 저장합니다. 즉, DTO → Service → Entity → Repository 과정이 필요하며, DTO가 필요합니다. - 게시글 정보를 앞에서 받아 올 DTO import lombok.Getter; import lombok.Setter; @Getter @Setter public class BoardRequestDTO { private String title; private String content; } ​ - Service단에 메소드 // 게시글 생성 @Transactional public void createOneBoard(BoardRequestDTO dto) { // 게시글 dto -> entity BoardEntity boardEntity = new BoardEntity(); boardEntity.setTitle(dto.getTitle()); boardEntity.setContent(dto.getContent()); // entity 저장 boardRepository.save(boardEntity); // //User 와 Board 연관 관계 생성 // 현재 게시글을 작성하는 유저 String username = SecurityContextHolder.getContext().getAuthentication().getName(); // 해당 유저의 Entity 가져오기 UserEntity userEntity = userRepository.findByUsername(username).orElseThrow(); // 연관 관계 만드는 메소드 호출 userEntity.addBoardEntity(boardEntity); userRepository.save(userEntity); } ​ CRUD : read 작성 1 ​ - BoardEntity에 존재하는 특정 글 읽기 DB 테이블에 저장되어 있는 글 데이터를 확인해야 하는 경우가 있습니다. 사용자로 부터 특정 유저의 unique한 id 데이터를 받아 select를 진행해야 합니다. 즉, 게시글 id → Service → Repository → Entity → Service → DTO 과정이 필요합니다. - 게시글 정보를 응답할 DTO import lombok.Getter; import lombok.Setter; @Getter @Setter public class BoardResponseDTO { private Long id; private String title; private String content; } ​ - Service단에 메소드 // 게시글 하나 읽기 @Transactional(readOnly = true) public BoardResponseDTO readOneBoard(Long id) { BoardEntity boardEntity = boardRepository.findById(id).orElseThrow(); BoardResponseDTO dto = new BoardResponseDTO(); dto.setId(boardEntity.getId()); dto.setTitle(boardEntity.getTitle()); dto.setContent(boardEntity.getContent()); return dto; } ​ CRUD : read 작성 2 ​ - BoardEntity에 존재하는 모든 게시글 읽기 사용할 일이 없지만, 추후 Pageable이라는 페이징으로 변환하시면 좋습니다. - Service단에 메소드 // 게시글 모두 읽기 @Transactional(readOnly = true) public List readAllBoards() { List list = boardRepository.findAll(); List dtos = new ArrayList<>(); for (BoardEntity boardEntity : list) { BoardResponseDTO dto = new BoardResponseDTO(); dto.setId(boardEntity.getId()); dto.setTitle(boardEntity.getTitle()); dto.setContent(boardEntity.getContent()); dtos.add(dto); } return dtos; } ​ CRUD : update 작성 ​ - BoardEntity에 존재하는 특정 게시글 수정 특정 게시글 id를 기반으로 데이터 수정 진행 - Service단에 메소드 // 게시글 하나 수정 @Transactional public void updateOneBoard(Long id, BoardRequestDTO dto) { // 기존의 id에 대한 게시글 데이터 불러오기 BoardEntity boardEntity = boardRepository.findById(id).orElseThrow(); // 게시글 dto -> entity boardEntity.setTitle(dto.getTitle()); boardEntity.setContent(dto.getContent()); boardRepository.save(boardEntity); } ​ CRUD : delete 작성 ​ - BoardEntity에 존재하는 특정 게시글 삭제 특정 id를 기반으로 게시글 데이터를 삭제하는 방법 - Service단에 메소드 // 게시글 하나 삭제 @Transactional public void deleteOneBoard(Long id) { boardRepository.deleteById(id); } ​ 이전 : 14. User와 JOIN 다음 : 16. Board CRUD 접근 제한 https://youtu.be/ZoUz3BRYRrM 21, 스프링 부트 3 > 16. Board CRUD 접근 제한 게시글 접근 권한이 필요한 이유 ​ 게시글 수정 및 삭제의 경우 작성한 유저만 수정, 삭제를 할 수 있어야하기 때문에 접근 권한 확인이 필요합니다. ​ 메소드 구현 ​ - BoardService.java // 유저 접근 권한 체크 public Boolean isAccess(Long id) { // 현재 로그인 되어 있는 유저의 username String sessionUsername = SecurityContextHolder.getContext().getAuthentication().getName(); // 현재 로그인 되어 있는 유저의 role String sessionRole = SecurityContextHolder.getContext().getAuthentication().getAuthorities().iterator().next().getAuthority(); // 수직적으로 ADMIN이면 무조건 접근 가능 if ("ROLE_ADMIN".equals(sessionRole)) { return true; } // 특정 게시글 id에 대해 본인이 작성 했는지 확인 String boardUsername = boardRepository.findById(id).orElseThrow().getUserEntity().getUsername(); if (sessionUsername.equals(boardUsername)) { return true; } // 나머지 다 불가 return false; } ​ 이전 : 15. Board 도메인 작성 2 다음 : 17. Board 엔드포인트 작성 https://youtu.be/mhDDkwv99Ek 22, 스프링 부트 3 > 17. Board 엔드포인트 작성 게시글 관련 엔드포인트 생성 ​ ​ Board 도메인에 특정한 행위 (CRUD)를 할 수 있는 BoardService단을 생성했습니다. ​ 이제 사용자로 부터 POST : “/board/create” 이라는 경로에 데이터를 보냈을때 BoardService의 createOneBoard()가 실행되도록 Controller 엔드포인트를 만들겠습니다. ​ 구현 전 ​ 이번 시리즈는 스프링 부트의 도메인 (Service - Repo)에 대해 윤곽을 잡는 부분을 중점으로 진행하기 때문에 VIEW에 해당되는 mustache 페이지 작성이 부실합니다. 만약 에디터와 같은 자세한 부분을 다르고 싶으시면 아래 시리즈를 참조 부탁드립니다. (아래 시리즈는 Service단 설계는 부족하지만, 에디터 부분에서 게시판 CRUD를 만드는 부분은 괜찮습니다.) https://www.youtube.com/playlist?list=PLJkjrxxiBSFCrLW3SuMjsUTbB8GZjsYlw 컨트롤러 생성 ​ 클라이언트로 부터 uri에 따라 특정한 페이지를 주고, api 호출을 받는 부분은 모두 Controller 클래스에 작성해야 합니다. - controller>BoardController @Controller public class BoardController { private final BoardService boardService; public BoardController(BoardService boardService) { this.boardService = boardService; } } ​ API 엔드포인트는? ​ 간단하게 몇 가지 엔드포인트를 작성하겠습니다. - 글 작성 페이지 : GET : “/board/create” - 글 작성 진행 : POST : “/board/create” - 글 목록 페이지 : GET : “/board/read” - 글 읽기 페이지 : GET : “/board/read/{id}” - 글 수정 페이지 : GET : “/board/update/{id}” - 글 수정 진행 : POST : “/board/update/{id}” - 글 삭제 진행 : POST : “/board/delete/{id}” 구현 : 글 작성 ​ - Controller 메소드 작성 // 글 생성 : 페이지 응답 @GetMapping("/board/create") public String createPage() { return "createBoard"; } // 글 생성 : 수행 @PostMapping("/board/create") public String createProcess(BoardRequestDTO dto) { boardService.createOneBoard(dto); return "redirect:/board/read"; } ​ - 글 작성 페이지

board create page


​ 구현 : 글 읽기 : 목록 ​ - Controller 메소드 작성 // 글 목록 : 페이지 응답 @GetMapping("/board/read") public String readPage(Model model) { model.addAttribute("BOARDLIST", boardService.readAllBoards()); return "readBoard"; } ​ - 글 목록 페이지

board list


{{#BOARDLIST}} {{title}}
{{/BOARDLIST}} ​ 구현 : 글 읽기 2 ​ - Controller 메소드 작성 // 글 읽기 : 페이지 응답 @GetMapping("/board/read/{id}") public String readIdPage(Model model, @PathVariable("id") Long id) { model.addAttribute("BOARD", boardService.readOneBoard(id)); return "readIdBoard"; } ​ - 글 페이지 {{BOARD.title}} {{BOARD.content}} ​ 구현 : 글 수정 ​ - Controller 메소드 작성 // 글 수정 : 페이지 응답 @GetMapping("/board/update/{id}") public String updatePage(Model model, @PathVariable("id") Long id) { // 접근 권한 확인 if (!boardService.isAccess(id)) { return "redirect:/board/read"; } model.addAttribute("BOARD", boardService.readOneBoard(id)); return "updateBoard"; } // 글 수정 : 수행 @PostMapping("/board/update/{id}") public String updateProcess(BoardRequestDTO dto, @PathVariable("id") Long id) { // 접근 권한 확인 if (!boardService.isAccess(id)) { return "redirect:/board/read"; } boardService.updateOneBoard(id, dto); return "redirect:/board/read/" + id; } ​ - 수정 페이지

board update page


​ 구현 : 글 삭제 ​ - Controller 메소드 작성 // 글 삭제 : 수행 @PostMapping("/board/delete/{id}") public String deleteProcess(@PathVariable("id") Long id) { // 접근 권한 확인 if (boardService.isAccess(id)) { boardService.deleteOneBoard(id); } return "redirect:/board/read"; } ​ 시큐리티 인가 설정 ​ - board 도메인에 대해 : SecurityConfig .requestMatchers("/board/**").hasRole("USER") ​ 이전 : 16. Board CRUD 접근 제한 https://youtu.be/GxWd7DMUw9s 23, 스프링 생태계에서 LLM API를 활용한 서비스를 쉽게 구현하기 위한 프레임워크 ​ 스프링 AI ​ 1. 스프링 AI란? 2. 프로젝트 생성 및 OpenAI 의존성 3. 챗봇 Controller, VIEW 4. 챗 멀티턴 및 히스토리 : ChatMemory 5. 히스토리 구현 JPA 6. ChatClient 7. Structured Output 8. 에이전트를 위한 Tool Calling 9. RAG를 위한 Advisor 10. Document Reader ​ 기타 ​ 기타. gpt5 400 응답 에러 기타. openai 샘플링 파라미터 설명 기타. Document 객체 필드 에러 24, 스프링 AI > 1. 스프링 AI란? 스프링 AI ​ 스프링 AI는 LLM API를 활용한 여러 웹 시스템 (챗봇, 멀티모달, RAG)을 쉽게 구축하도록 도와주는 스프링 기반의 모듈입니다. 현재 AI 진영에서는 LangChain/LangGraph와 같은 파이썬 모듈의 편의성으로 자바/스프링 기반의 구현이 줄어들고 있습니다. 자바/스프링 또한 API 호출을 하는 기초 코드 부터 작성해 일련의 과정들을 수행할 수 있지만, 프레임워크 대비 많이 번거롭습니다. 이 문제를 해결하기 위해 2024년 스프링은 스프링 AI라는 모듈을 출시하게 됩니다. ​ 공식 홈페이지 ​ https://docs.spring.io/spring-ai/reference/index.html 결론 ​ AI와 연관된 도구들을 쉽게 통합하도록 하는 프레임워크 ​ - LLM API 호출 - 챗모델 : 앤트로픽, 애저, OpenAI, 딥시크 - 임베딩 모델 - 이미지 모델 - 오디오 모델 - 챗 메모리 : 채팅 히스토리 관리 - 툴 호출 - MCP - RAG - 벡터 DB - ES - Neo4j - PostgresML 시리즈 예상 샘플 프로젝트를 구현하기 위한 목적이 아닌, 스프링 AI가 가진 각각의 모듈들을 확인하고 활용하는 과정을 진행하겠습니다. (아주 긴 주기로 진행할 예정입니다.) ​ 다음 : 2. 프로젝트 생성 및 OpenAI 의존성 https://youtu.be/-g6goXtCilM 25, 스프링 AI > 2. 프로젝트 생성 및 OpenAI 의존성 스프링 AI : OpenAI ​ 스프링 AI 의존성들을 활용하기 위한 스프링 부트 프로젝트를 생성하겠습니다. 첫 번째 의존성 활용은 OpenAI입니다. ​ 스프링 부트 기반의 웹 서비스를 구축하며, 그 웹 서비스에서 OpenAI의 서비스가 필요한 경우, 기존에 RestTemplate, WebClient 와 같은 API 호출 클라이언트를 통해 모든 과정을 작성해야 했습니다. ​ 하지만 OpenAI 의존성만 사용하면 위 과정들을 추상화하여 사용할 수 있습니다. ​ ​ - 기타 파이썬이 익숙하신 분들은 FastAPI 프로젝트에서 import openai를 하는 원리입니다. ​ OpenAI 클라이언트 등록 ​ OpenAI API를 활용하기 위한 Bean (API 키)등록을 진행하겠습니다. - 1단계 API 키 발급 받기 개별적으로 수행하셔야 합니다. OpenAI API Platform에 가신 후 API 키를 발급 받으셔야 합니다. - application.properites 등록 : 스프링 AI OpenAI 클라이언트에서 사용 spring.ai.openai.api-key= ​ OpenAI API 제공 서비스 ​ - Chat 모델 - Embedding 모델 - Image 모델 (DALL-E) - Audio 모델 - TTS - STT ​ Service단 : OpenAI API 호출 ​ - 공통 : 클래스 및 의존성 @Service public class OpenAIService { private final OpenAiChatModel openAiChatModel; private final OpenAiEmbeddingModel openAiEmbeddingModel; private final OpenAiImageModel openAiImageModel; private final OpenAiAudioSpeechModel openAiAudioSpeechModel; private final OpenAiAudioTranscriptionModel openAiAudioTranscriptionModel; // 생성자 } ​ 위의 api 키 등록시 AutoConfig로 OpenAI 관련 @Bean들이 활성화 됩니다. ​ - Chat 모델 메소드 public String generate(String text) { // 메시지 SystemMessage systemMessage = new SystemMessage(""); UserMessage userMessage = new UserMessage(text); AssistantMessage assistantMessage = new AssistantMessage(""); // 옵션 OpenAiChatOptions options = OpenAiChatOptions.builder() .model("gpt-4.1-mini") .temperature(0.7) .build(); // 프롬프트 Prompt prompt = new Prompt(List.of(systemMessage, userMessage, assistantMessage), options); // 요청 및 응답 ChatResponse response = openAiChatModel.call(prompt); return response.getResult().getOutput().getText(); } public Flux generateStream(String text) { // 메시지 SystemMessage systemMessage = new SystemMessage(""); UserMessage userMessage = new UserMessage(text); AssistantMessage assistantMessage = new AssistantMessage(""); // 옵션 OpenAiChatOptions options = OpenAiChatOptions.builder() .model("gpt-4.1-mini") .temperature(0.7) .build(); // 프롬프트 Prompt prompt = new Prompt(List.of(systemMessage, userMessage, assistantMessage), options); // 요청 및 응답 return openAiChatModel.stream(prompt) .mapNotNull(response -> response.getResult().getOutput().getText()); } ​ https://docs.spring.io/spring-ai/reference/api/chat/openai-chat.html OpenAI Chat :: Spring AI Reference Spring AI / Reference / Models / Chat Models / OpenAI OpenAI Chat Spring AI supports the various AI language models from OpenAI, the company behind ChatGPT, which has been instrumental in sparking interest in AI-driven text generation thanks to its creation of industry-leading text generation models... docs.spring.io ​ - Embedding 모델 메소드 public List generateEmbedding(List texts, String model) { // 옵션 EmbeddingOptions embeddingOptions = OpenAiEmbeddingOptions.builder() .model(model).build(); // 프롬프트 EmbeddingRequest prompt = new EmbeddingRequest(texts, embeddingOptions); // 요청 및 응답 EmbeddingResponse response = openAiEmbeddingModel.call(prompt); return response.getResults().stream() .map(Embedding::getOutput) .toList(); } ​ https://docs.spring.io/spring-ai/reference/api/embeddings/openai-embeddings.html OpenAI Embeddings :: Spring AI Reference Spring AI / Reference / Models / Embedding Models / OpenAI OpenAI Embeddings Spring AI supports the OpenAI’s text embeddings models. OpenAI’s text embeddings measure the relatedness of text strings. An embedding is a vector (list) of floating point numbers. The distance between two vectors measures ... docs.spring.io ​ - Image 모델 (DALL-E) 메소드 public List generateImages(String text, int count, int height, int width) { // 옵션 OpenAiImageOptions imageOptions = OpenAiImageOptions.builder() .quality("hd") .N(count) .height(height) .width(width) .build(); // 프롬프트 ImagePrompt prompt = new ImagePrompt(text, imageOptions); // 요청 및 응답 ImageResponse response = openAiImageModel.call(prompt); return response.getResults().stream() .map(image -> image.getOutput().getUrl()) .toList(); } https://docs.spring.io/spring-ai/reference/api/image/openai-image.html OpenAI Image Generation :: Spring AI Reference Spring AI / Reference / Models / Image Models / OpenAI OpenAI Image Generation Spring AI supports DALL-E, the Image generation model from OpenAI. # Prerequisites You will need to create an API key with OpenAI to access ChatGPT models. Create an account at OpenAI signup page and generate the token on... docs.spring.io ​ - Audio 모델 메소드 // TTS public byte[] tts(String text) { // 옵션 OpenAiAudioSpeechOptions speechOptions = OpenAiAudioSpeechOptions.builder() .responseFormat(OpenAiAudioApi.SpeechRequest.AudioResponseFormat.MP3) .speed(1.0f) .model(OpenAiAudioApi.TtsModel.TTS_1.value) .build(); // 프롬프트 SpeechPrompt prompt = new SpeechPrompt(text, speechOptions); // 요청 및 응답 SpeechResponse response = openAiAudioSpeechModel.call(prompt); return response.getResult().getOutput(); } // STT public String stt(Resource audioFile) { // 옵션 OpenAiAudioApi.TranscriptResponseFormat responseFormat = OpenAiAudioApi.TranscriptResponseFormat.VTT; OpenAiAudioTranscriptionOptions transcriptionOptions = OpenAiAudioTranscriptionOptions.builder() .language("ko") // 인식할 언어 .prompt("Ask not this, but ask that") // 음성 인식 전 참고할 텍스트 프롬프트 .temperature(0f) .model(OpenAiAudioApi.TtsModel.TTS_1.value) .responseFormat(responseFormat) // 결과 타입 지정 VTT 자막형식 .build(); // 프롬프트 AudioTranscriptionPrompt prompt = new AudioTranscriptionPrompt(audioFile, transcriptionOptions); // 요청 및 응답 AudioTranscriptionResponse response = openAiAudioTranscriptionModel.call(prompt); return response.getResult().getOutput(); } ​ https://docs.spring.io/spring-ai/reference/api/audio/transcriptions/openai-transcriptions.html Untitled :: Spring AI Reference Spring AI / Reference / Models / Audio Models / Transcription API / OpenAI # OpenAI Transcriptions Spring AI supports OpenAI’s Transcription model . # Prerequisites You will need to create an API key with OpenAI to access ChatGPT models. Create an account at OpenAI signup page and generate the token... docs.spring.io https://docs.spring.io/spring-ai/reference/api/audio/speech/openai-speech.html OpenAI Text-to-Speech (TTS) :: Spring AI Reference Spring AI / Reference / Models / Audio Models / Text-To-Speech (TTS) API / OpenAI OpenAI Text-to-Speech (TTS) # Introduction The Audio API provides a speech endpoint based on OpenAI’s TTS (text-to-speech) model, enabling users to: Narrate a written blog post. Produce spoken audio in multiple languag... docs.spring.io ​ 이전 : 1. 스프링 AI란? 다음 : 3. 챗봇 Controller, VIEW https://youtu.be/up4TrRvLI-E 26, 스프링 AI > 3. 챗봇 Controller, VIEW API 클라이언트 활용 : 응용 시간 ​ 지난 2강에서 등록한 OpenAI Chat 모델을 호출하는 메소드를 활용해 챗봇을 만들어 보겠습니다. 따라서 Chat 호출 메소드를 활용할 Controller 엔드포인트, VIEW 페이지를 생성하겠습니다. ​ Controller ​ - api > ChatController @Controller public class ChatController { private final OpenAIService openAIService; public ChatController(OpenAIService openAIService) { this.openAIService = openAIService; } @ResponseBody @PostMapping("/chat") public String chat(@RequestBody Map body) { return openAIService.generate(body.get("text")); } @ResponseBody @PostMapping("/chat/stream") public Flux streamChat(@RequestBody Map body) { return openAIService.generateStream(body.get("text")); } } ​ “/chat” : 논 스트림, “/chat/stream” 스트림 ​ 테스트 : 논 스트림 ​ POSTMAN을 통해 테스트를 진행하겠습니다. ​ ​ 채팅 페이지 : VIEW ​ - chat.mustache Chat Bot
​ - api > ChatController.java : 메소드 추가 @GetMapping("/") public String chatPage() { return "chat"; } ​ 문제는? ​ 멀티턴, 히스토리 관리가 안됨 따라서 구현 예정 이전 : 2. 프로젝트 생성 및 OpenAI 의존성 다음 : 4. 챗 멀티턴 및 히스토리 : ChatMemory https://youtu.be/SUwmtUjTArw 27, 스프링 AI > 4. 챗 멀티턴 및 히스토리 : ChatMemory 멀티턴 및 히스토리 (multi-turn) ​ 여러 대화간의 문맥을 고려해 앞선 내용에 이어 응답할 수 있는 멀티턴 기능, 동일한 페이지에 재접속 할 경우 그동안의 대화 내용을 보여줄 수 있는 히스토리 기능을 구현하겠습니다. https://www.skelterlabs.com/blog/multiturn-rag ​ ​ 멀티턴 : ChatMemoryRepository와 문제점 ​ - 멀티턴 구현 원리는? 멀티턴 기능을 구현하기 위해선 결국 과거에 챗봇과 나눴던 QnA를 다시 프롬프트에 담아야 합니다. (결국 히스토리를 저장해야하기 때문에 히스토리 주제와 함께 다룹니다.) - 스프링 AI에서 제공 그 기능을 스프링 AI에서는 제공합니다. 과거 N개의 대화 데이터를 ChatMemoryRepository 인터페이스에 담을 수 있도록 제공합니다. ChatMemoryRepository, 구현체는 InMemory, JDBC를 기본 제공합니다. - 그럼? : 문제점은? 좋습니다. 과거 N개의 대화 이력을 ChatMemoryRepository를 통해 관리할 수 있습니다. 하지만 멀티턴이라고 해서 과거 모든 데이터를 다룰 수 없습니다. 이유는 max_prompt_size, 비용, 딜레이 문제입니다. 이 문제로 대략 과거 몇 개 또는 요약 데이터를 활용해 멀티턴을 구현합니다. 이렇게 된다면 페이지 로딩을 위해 과거 모든 대화 히스토리를 불러와야하는 상황에 문제가 생깁니다. - 해결책 2개의 저장소를 사용합니다. 전체 히스토리 저장용, 멀티턴용 ChatMemoryRepository ​ 멀티턴 : ChatMemoryRepository Bean 등록 ​ 구현체가 크게 2종류 (InMemory, JDBC) 입니다. 대화 내역 저장을 위해 각각의 Bean 등록 방법을 알아보겠습니다. (기본적으로 스프링 AI 의존성을 추가한다면 InMemory Bean이 자동 활성화, 수동 등록해도 무방) - config > AIConfig.java : InMemory (안해도 됨, 자동 등록) @Configuration public class AIConfig { // 기본 설정시 자동 등록이지만, 수동 등록 가능 @Bean public ChatMemoryRepository chatMemoryRepository() { return new InMemoryChatMemoryRepository(); } } ​ - JDBC 구현체 사용을 위한 의존성 추가 (+MySQL) InMemory는 간단하지만, JDBC는 추가 의존성과 작업이 요구됩니다. 우리는 MySQL을 사용하겠습니다. https://docs.spring.io/spring-ai/reference/api/chat-memory.html#_jdbcchatmemoryrepository ​ implementation 'org.springframework.ai:spring-ai-starter-model-chat-memory-repository-jdbc' runtimeOnly 'com.mysql:mysql-connector-j' - application.properties 변수 추가 spring.datasource.url=jdbc:mysql://아이피:3306/디비?serverTimezone=UTC&useSSL=false spring.datasource.username=root spring.datasource.password=비밀번호 spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver spring.ai.chat.memory.repository.jdbc.initialize-schema=never ​ - 테이블 생성 테이블 생성 오류가 자주 발생합니다. 직접 생성하는걸 추천드립니다. https://github.com/spring-projects/spring-ai/tree/main/memory/repository/spring-ai-model-chat-memory-repository-jdbc/src/main/resources/org/springframework/ai/chat/memory/repository/jdbc CREATE TABLE IF NOT EXISTS SPRING_AI_CHAT_MEMORY ( `conversation_id` VARCHAR(36) NOT NULL, `content` TEXT NOT NULL, `type` ENUM('USER', 'ASSISTANT', 'SYSTEM', 'TOOL') NOT NULL, `timestamp` TIMESTAMP NOT NULL, INDEX `SPRING_AI_CHAT_MEMORY_CONVERSATION_ID_TIMESTAMP_IDX` (`conversation_id`, `timestamp`) ); ​ - config > AIConfig.java : JDBC(MySQL) @Configuration public class AIConfig { @Bean public ChatMemoryRepository chatMemoryRepository(JdbcTemplate jdbcTemplate, PlatformTransactionManager transactionManager) { return JdbcChatMemoryRepository.builder() .jdbcTemplate(jdbcTemplate) .transactionManager(transactionManager) .build(); } } ​ 멀티턴 : Service단 Chat 메소드 수정 ​ - domain > openai > service > OpenAIService.java private final ChatMemoryRepository chatMemoryRepository; public Flux generateStream(String text) { // 유저&페이지별 ChatMemory를 관리하기 위한 key (우선은 명시적으로) String userId = "xxxjjhhh" + "_" + "3"; ChatMemory chatMemory = MessageWindowChatMemory.builder() .maxMessages(10) .chatMemoryRepository(chatMemoryRepository) .build(); chatMemory.add(userId, new UserMessage(text)); // 신규 메시지도 추가 // 옵션 OpenAiChatOptions options = OpenAiChatOptions.builder() .model("gpt-4.1-mini") .temperature(0.7) .build(); // 프롬프트 Prompt prompt = new Prompt(chatMemory.get(userId), options); // 응답 메시지를 저장할 임시 버퍼 StringBuilder responseBuffer = new StringBuilder(); // 요청 및 응답 return openAiChatModel.stream(prompt) .mapNotNull(response -> { String token = response.getResult().getOutput().getText(); responseBuffer.append(token); return token; }) .doOnComplete(() -> { chatMemory.add(userId, new AssistantMessage(responseBuffer.toString())); chatMemoryRepository.saveAll(userId, chatMemory.get(userId)); }); } ​ 히스토리는? ​ 전체 대화에 대한 히스토리는 따로 DB 테이블을 만들어 관리하겠습니다. ​ 이전 : 3. 챗봇 Controller, VIEW 다음 : 5. 히스토리 구현 JPA https://youtu.be/mODouW9WaSE 28, 스프링 부트 3 > 5. 히스토리 구현 JPA 히스토리 지난 4강의 ChatMemory, ChatMemoryRepository와 별개로 전체 대화를 저장하는 히스토리를 만들겠습니다. 히스토리가 필요한 이유는 ChatGPT와 같이 채팅에 재접속 할 경우 기존 대화를 보여줘야하기 때문입니다. JPA를 활용하겠습니다. ​ JPA 의존성 추가 및 설정 ​ - build.gradle implementation 'org.springframework.boot:spring-boot-starter-data-jpa' 기존에 MySQL 드라이버와 DB연결은 진행했기 때문에 JPA만 추가하겠습니다. ​ - application.properties : ddl 설정 추가​ spring.jpa.hibernate.ddl-auto=update spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl spring.jpa.show-sql=true ​ Entity, Repository 생성 ​ - domain > openai > entity > ChatEntity.java @Entity @Getter @Setter public class ChatEntity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(name = "user_id") private String userId; @Column(columnDefinition = "TEXT") private String content; @Enumerated(EnumType.STRING) private MessageType type; @CreationTimestamp @Column(updatable = false, name = "created_at") private LocalDateTime createdAt; } ​ - domain > openai > repository > ChatRepository.java public interface ChatRepository extends JpaRepository { } ​ Service단 채팅 내역 추가 ​ - domain > openai > service > OpenAIService.java : 의존성 추가 private final ChatRepository chatRepository; ​ - domain > openai > service > OpenAIService.java : 챗 스트림 메소드 public Flux generateStream(String text) { // 유저&페이지별 ChatMemory를 관리하기 위한 key (우선은 명시적으로) String userId = "xxxjjhhh" + "_" + "3"; // 전체 대화 저장용 ChatEntity chatUserEntity = new ChatEntity(); chatUserEntity.setUserId(userId); chatUserEntity.setType(MessageType.USER); chatUserEntity.setContent(text); // 메시지 ChatMemory chatMemory = MessageWindowChatMemory.builder() .maxMessages(10) .chatMemoryRepository(chatMemoryRepository) .build(); chatMemory.add(userId, new UserMessage(text)); // 신규 메시지도 추가 // 옵션 OpenAiChatOptions options = OpenAiChatOptions.builder() .model("gpt-4.1-mini") .temperature(0.7) .build(); // 프롬프트 Prompt prompt = new Prompt(chatMemory.get(userId), options); // 응답 메시지를 저장할 임시 버퍼 StringBuilder responseBuffer = new StringBuilder(); // 요청 및 응답 return openAiChatModel.stream(prompt) .mapNotNull(response -> { String token = response.getResult().getOutput().getText(); if (token != null) { responseBuffer.append(token); return token; } return null; }) .doOnComplete(() -> { chatMemory.add(userId, new AssistantMessage(responseBuffer.toString())); chatMemoryRepository.saveAll(userId, chatMemory.get(userId)); // 전체 대화 저장용 ChatEntity chatAssistantEntity = new ChatEntity(); chatAssistantEntity.setUserId(userId); chatAssistantEntity.setType(MessageType.ASSISTANT); chatAssistantEntity.setContent(responseBuffer.toString()); chatRepository.saveAll(List.of(chatUserEntity, chatAssistantEntity)); }); } ​ 사용자, LLM 프롬프트를 각각 저장합니다. ​ 조회 API 작성 ​ 저장한 전체 대화 내역을 조회하는 API를 만들겠습니다. ​ - domain > openai > repository > ChatRepository.java : 커스텀 메소드 추가 List findByUserIdOrderByCreatedAtAsc(String userId); ​ - domain > openai > service > ChatService.java @Service public class ChatService { private final ChatRepository chatRepository; public ChatService(ChatRepository chatRepository) { this.chatRepository = chatRepository; } @Transactional(readOnly = true) public List readAllChats(String userId) { return chatRepository.findByUserIdOrderByCreatedAtAsc(userId); } } ​ - api > ChatController.java private final ChatService chatService; @ResponseBody @PostMapping("/chat/history/{userid}") public List getChatHistory(@PathVariable("userid") String userId) { return chatService.readAllChats(userId); } ​ VIEW 조회 Javascript 추가 ​ - chat.mustache Chat Bot
​ 이전 : 4. 챗 멀티턴 및 히스토리 : ChatMemory 다음 : 6. ChatClient https://youtu.be/85qxgRIEycY 29, 스프링 AI > 6. ChatClient ChatClient DSL Wrapper ​ - 기존 사용 : OpenAI 기준 private final OpenAiChatModel openAiChatModel; ​ 기존에 사용한 openAiChatModel을 ChatClient에 Wrapping해서 사용하는 방법을 알아보겠습니다. ChatClient를 활용하면 스프링 AI의 다양한 기능들을 함께 활용할 수 있습니다. https://docs.spring.io/spring-ai/reference/api/chatclient.html Chat Client API :: Spring AI Reference Spring AI / Reference / Chat Client API Chat Client API The ChatClient offers a fluent API for communicating with an AI Model. It supports both a synchronous and streaming programming model. Note See the Implementation Notes at the bottom of this document related to the combined use of imperative an... docs.spring.io - ChatClient ChatClient chatClient = ChatClient.create(openAiChatModel); ​ - Bean 등록 예시 Bean으로 등록하는 경우도 있습니다. @Configuration public class ChatClientConfig { @Bean public ChatClient openAiChatClient(OpenAiChatModel chatModel) { return ChatClient.create(chatModel); } @Bean public ChatClient anthropicChatClient(AnthropicChatModel chatModel) { return ChatClient.create(chatModel); } } ​ Service 챗 스트림 메소드 수정 ​ - domain > openai > service > OpenAIService.java public Flux generateStream(String text) { ChatClient chatClient = ChatClient.create(openAiChatModel); // 유저&페이지별 ChatMemory를 관리하기 위한 key (우선은 명시적으로) String userId = "xxxjjhhh" + "_" + "4"; // 전체 대화 저장용 ChatEntity chatUserEntity = new ChatEntity(); chatUserEntity.setUserId(userId); chatUserEntity.setType(MessageType.USER); chatUserEntity.setContent(text); // 메시지 ChatMemory chatMemory = MessageWindowChatMemory.builder() .maxMessages(10) .chatMemoryRepository(chatMemoryRepository) .build(); chatMemory.add(userId, new UserMessage(text)); // 신규 메시지도 추가 // 옵션 OpenAiChatOptions options = OpenAiChatOptions.builder() .model("gpt-4.1-mini") .temperature(0.7) .build(); // 프롬프트 Prompt prompt = new Prompt(chatMemory.get(userId), options); // 응답 메시지를 저장할 임시 버퍼 StringBuilder responseBuffer = new StringBuilder(); // 요청 및 응답 return chatClient.prompt(prompt) .stream() .content() .map(token -> { responseBuffer.append(token); return token; }) .doOnComplete(() -> { // chatMemory 저장 chatMemory.add(userId, new AssistantMessage(responseBuffer.toString())); chatMemoryRepository.saveAll(userId, chatMemory.get(userId)); // 전체 대화 저장용 ChatEntity chatAssistantEntity = new ChatEntity(); chatAssistantEntity.setUserId(userId); chatAssistantEntity.setType(MessageType.ASSISTANT); chatAssistantEntity.setContent(responseBuffer.toString()); chatRepository.saveAll(List.of(chatUserEntity, chatAssistantEntity)); }); } ​ ChatClient를 사용하는 이유 ​ ChatClient로 감싼 객체를 통해 아래 기능들을 쉽게 추가 가능 ​ - ObservationRegistry : 로깅 - tools : LLM에게 사용할 툴을 붙여줌 - advisors : RAG - entity : 응답 데이터 객체 파싱 (call 메소드만) - 추상화 : 모델 변경되어도 동일한 메소드 즉, 기존의 OpenAiChatModel 객체만으로는 가질 수 없는 여러 기능을 붙일 수 있습니다. ​ 이전 : 5. 히스토리 구현 JPA 다음 : 7. Structured Output https://youtu.be/YD8s9n4WCAU 30, 스프링 AI > 7. Structured Output LLM 응답 구조화 ​ LLM 응답을 자연어스러움에서 구조화하여 자바스러움의 객체로 응답을 받는 방법을 알아보겠습니다. https://docs.spring.io/spring-ai/reference/api/structured-output-converter.html Structured Output Converter :: Spring AI Reference Spring AI / Reference / Structured Output Structured Output Converter Note As of 02.05.2024 the old OutputParser , BeanOutputParser , ListOutputParser and MapOutputParser classes are deprecated in favor of the new StructuredOutputConverter , BeanOutputConverter , ListOutputConverter and MapOutputCon... docs.spring.io ​ 응답을 객체로 담기 : 예상 시나리오 ​ LLM에게 데이터를 만들라고 요청하는 경우가 많습니다. ​ 정말 간단하게 특정 국가명을 보내면 국가에 속한 도시 N개를 데이터로 받고 싶습니다. 이 데이터는 DTO에 담도록 구성하고 싶다면 Structured Output을 활용하면 됩니다. ​ - 담을 DTO 준비​ public record CityResponseDTO(List city) { } ​ Output 컨버터 등록 ​ 문장 형태로 받은 데이터를 DTO로 맞춰 넣기 위한 컨버터가 요구됩니다. 컨버터는 다양하게 제공됩니다. - AbstractConversionServiceOutputConverter​ 추상 클래스, 상속해서 커스텀 컨버터 생성 - AbstractMessageOutputConverter 메시지 기반 변환 추상 클래스, 상속해서 커스텀 컨버터 생성 - BeanOutputConverter DTO/Record/Bean 클래스 기반 자동 JSON 컨버터 - MapOutputConverter Map 기반 자동 컨버터 - ListOutputConverter List 기반 자동 컨버터 https://docs.spring.io/spring-ai/reference/api/structured-output-converter.html#_available_converters Structured Output Converter :: Spring AI Reference Spring AI / Reference / Structured Output Structured Output Converter Note As of 02.05.2024 the old OutputParser , BeanOutputParser , ListOutputParser and MapOutputParser classes are deprecated in favor of the new StructuredOutputConverter , BeanOutputConverter , ListOutputConverter and MapOutputCon... docs.spring.io ​ 적용 ​ - domain > openai > service > OpenAIService.java public CityResponseDTO generate(String text) { ChatClient chatClient = ChatClient.create(openAiChatModel); // 메시지 SystemMessage systemMessage = new SystemMessage(""); UserMessage userMessage = new UserMessage(text); AssistantMessage assistantMessage = new AssistantMessage(""); // 옵션 OpenAiChatOptions options = OpenAiChatOptions.builder() .model("gpt-4.1-mini") .temperature(0.7) .build(); // 프롬프트 Prompt prompt = new Prompt(List.of(systemMessage, userMessage, assistantMessage), options); // 요청 및 응답 return chatClient.prompt(prompt) .call() .entity(CityResponseDTO.class); } ​ 원래 컨버터 등록을 해야하지만 (DTO라 Bean 컨버터) 자동 타입 추론이 되기 때문에 명시하지 않아도 사용 가능 - 컨버터 등록 방법 : 공식 문서 코드인데 안돌아감 BeanOutputConverter beanOutputConverter = new BeanOutputConverter<>(ActorsFilms.class); String format = this.beanOutputConverter.getFormat(); String actor = "Tom Hanks"; String template = """ Generate the filmography of 5 movies for {actor}. {format} """; Generation generation = chatModel.call( new PromptTemplate(this.template, Map.of("actor", this.actor, "format", this.format)).create()).getResult(); ActorsFilms actorsFilms = this.beanOutputConverter.convert(this.generation.getOutput().getText()); ​ 원리 자체는 프롬프트 보낼때, 내 포맷대로 만들어 주세요 → 이후 포맷으로 파싱 ​ 현재 1.0.0이 나온지 얼마되지 않아 공식 문서 코드도 이상함 ​ 이전 : 6. ChatClient 다음 : 8. 에이전트를 위한 Tool Calling https://youtu.be/VqFQRubD4Gg 31, 스프링 AI > 8. 에이전트를 위한 Tool Calling Agent와 Tools ​ 에이전트란 목표가 주어지면, 그것을 이행하기 위해 LLM이 스스로 판단하여 행동을 수행하는 방식입니다. LLM이 문제를 해결하는 과정에서 외부의 도움이 필요하다고 판단하면, 필요한 도구(Tool)를 사용해 작업을 수행할 수 있습니다. - 툴 샘플 - 검색 툴 - DB 조회 툴 - 계산 툴 - 코드 실행 툴 - 시각화 툴 - 등등 내가 가진 스프링 서비스단을 툴화 시켜 붙여줄 수 있습니다. 즉, LLM에게 메소드 사용법을 알려주고 활용하도록 하는 방식입니다. https://docs.spring.io/spring-ai/reference/api/tools.html Tool Calling :: Spring AI Reference Spring AI / Reference / Tool Calling Tool Calling Tool calling (also known as function calling ) is a common pattern in AI applications allowing a model to interact with a set of APIs, or tools , augmenting its capabilities. Tools are mainly used for: Information Retrieval . Tools in this category c... docs.spring.io Tool 사용 동작 원리 ​ ​ 1. 사용자의 프롬프트와 툴 목록을 함께 보내줌 2. LLM API가 사용자의 질문과 툴 목록을 확인 후, 특정 툴을 사용하겠다고 콜백을 줌 3. 툴을 활용해서 데이터를 처리하거나 가져옴 (스프링 AI 어플리케이션에서 툴 실행) 4. 툴 처리 완료 5. 툴 실행 결과를 다시 LLM API에 제공 6. LLM API 최종 응답 ​ 툴 등록 ​ 간단하게 명시적인 데이터를 넣었지만, 세션 유저별 DB 조회라 생각하면 됩니다. ​ package org.example.spai.domain.openai.service; import org.example.spai.domain.openai.dto.UserResponseDTO; import org.springframework.ai.tool.annotation.Tool; public class ChatTools { @Tool(description = "User personal information : name, age, address, phone, etc") public UserResponseDTO getUserInfoTool() { return new UserResponseDTO("김지훈", 15L, "서울특별시 종로구 청와대로 1", "010-0000-0000", "03048"); } } ​ - UserResponseDTO public record UserResponseDTO(String name, Long age, String address, String phoneNumber, String zipCode) { } ​ 2 ~ 3 과정을 통해 LLM API로 부터 인자 데이터를 받을 수 있습니다. (인자 데이터는 @ToolParam으로 정규화 가능) ​ ChatClient 호출시 등록 ​ ​ return chatClient.prompt(prompt) .tools(new ChatTools()) .stream() .content() // 이하 생략 ​ 이전 : 7. Structured Output 다음 : 9. RAG를 위한 Advisor https://youtu.be/AvmoGHyl6mE 32, 스프링 AI > 9. RAG를 위한 Advisor RAG : Retrieval Augmented Generation ​ RAG란 LLM에게 우리 도메인의 지식을 부여하기 위해 “사용자의 프롬포트”에 유사한 문서 N개(문서는 특정 도메인 데이터)를 뽑아 프롬프트에 붙여 보내는 기법입니다. ​ ​ ​ (지난 RAG, LoRA 기초 시리즈 1강의 이미지) 스프링 AI : Advisor ​ 스프링 AI의 ChatClient advisors() 메소드는 RAG를 쉽게 통합할 수 있는 기능을 제공합니다. 이 advisors() 메소드에는 VectorStore라는 객체를 넣어주어야 하는데 관련된 아래 의존성이 요구됩니다. - build.gradle > dependencies implementation 'org.springframework.ai:spring-ai-advisors-vector-store' ​ https://docs.spring.io/spring-ai/reference/api/retrieval-augmented-generation.html Retrieval Augmented Generation :: Spring AI Reference Spring AI / Reference / Retrieval Augmented Generation (RAG) Retrieval Augmented Generation Retrieval Augmented Generation (RAG) is a technique useful to overcome the limitations of large language models that struggle with long-form content, factual accuracy, and context-awareness. Spring AI support... docs.spring.io ​ 위 의존성을 통해 advisor API를 추가하면 통합할 수 있는 어댑터는 활성화 되지만, 결국 RAG를 위한 DB가 요구됩니다. 이번 시간에는 Elasticsearch가 있다고 가정하고 진행하겠습니다. ​ 스프링 AI : Elasticsearch 의존성 추가 ​ Elasticsearch는 따로 있다고 가정 “엘라스틱서치” 시리즈 참조 ​ https://docs.spring.io/spring-ai/reference/api/vectordbs/elasticsearch.html Elasticsearch :: Spring AI Reference Spring AI / Reference / Vector Databases / Elasticsearch Elasticsearch This section walks you through setting up the Elasticsearch VectorStore to store document embeddings and perform similarity searches. Elasticsearch is an open source search and analytics engine based on the Apache Lucene library. docs.spring.io ​ - build.gradle > dependencies implementation 'org.springframework.ai:spring-ai-starter-vector-store-elasticsearch' ​ - 기타 : 버전 불일치 실행 에러시 등록 (Elasticsearch 버전 명시해서) implementation 'co.elastic.clients:elasticsearch-java:8.13.3' ​ https://docs.spring.io/spring-ai/reference/api/vectordbs/elasticsearch.html#_auto_configuration Elasticsearch :: Spring AI Reference Spring AI / Reference / Vector Databases / Elasticsearch Elasticsearch This section walks you through setting up the Elasticsearch VectorStore to store document embeddings and perform similarity searches. Elasticsearch is an open source search and analytics engine based on the Apache Lucene library. docs.spring.io ​ Elasticsearch 연결 ​ - application.properties spring.elasticsearch.uris=https://아아피:9200 spring.elasticsearch.username=elastic spring.elasticsearch.password=123456 ​ VectorStore Bean 등록 : Elasticsearch 기반 ​ 이제 벡터를 저장할 VectorStore Bean을 등록합니다. 우리는 Elasticsearch 기반으로 생성합니다. - config > VectorStoreConfig.java @Configuration public class VectorStoreConfig { private final EmbeddingModel embeddingModel; public VectorStoreConfig(EmbeddingModel embeddingModel) { this.embeddingModel = embeddingModel; } @Bean public VectorStore elasticsearchVectorStore(RestClient restClient) { ElasticsearchVectorStoreOptions options = new ElasticsearchVectorStoreOptions(); options.setIndexName("yummi-docs"); options.setSimilarity(SimilarityFunction.cosine); options.setDimensions(1536); return ElasticsearchVectorStore.builder(restClient, embeddingModel) .options(options) .initializeSchema(true) .batchingStrategy(new TokenCountBatchingStrategy()) .build(); } } ​ 연결 뿐만 아니라, 스프링 기반의 자동 인덱스 생성, 자연어 추가시 자동 임베딩 API 연결을 처리할 수 있습니다. ​ RAG 클래스 작성 ​ Advisor API에 Elasticsearch 벡터 디비를 붙인 클래스인 VectorStore 객체를 넣어주면 됩니다. - VectorStore 주입 private final VectorStore elasticsearchVectorStore; ​ - 사용 Advisor ragAdvisor = QuestionAnswerAdvisor.builder(elasticsearchVectorStore) .searchRequest(SearchRequest.builder().similarityThreshold(0.8d).topK(6).build()) .build(); .advisors(ragAdvisor) ​ 기타 : RetrievalAugmentationAdvisor Deprecated ​ 공식 문서에도 존재하는 advisor의 여러 API들이 Deprecated 되었습니다. 흔히 사용하는 RetrievalAugmentationAdvisor 같은 클래스도 Deprecated되고 QuestionAnswerAdvisor 기반으로 생성해야 합니다. ​ https://docs.spring.io/spring-ai/docs/1.0.0-M8/api/deprecated-list.html Deprecated List (Spring AI Parent 1.0.0-M8 API) Deprecated API Contents Terminally Deprecated Interfaces Classes Enum Classes Record Classes Fields Methods Constructors Enum Constants Terminally Deprecated Elements Element Description org.springframework.ai.chat.client.ChatClient.ChatClientRequestSpec.tools (String...) Deprecated Interfaces Inter... docs.spring.io ​ 이전 : 8. 에이전트를 위한 Tool Calling 다음 : 10. Document Reader https://youtu.be/x8sF68VFJBg 33, 스프링 AI > 10. Document Reader 응용 AI ​ LLM API를 활용하다보면 데이터로 사용하기 위해 문서를 불러와야하는 경우가 많습니다. 스프링 AI의 ETL 파이프라인 중 Document Reader 부분을 통해 문서별 Reader 객체를 알아보겠습니다. ​ https://docs.spring.io/spring-ai/reference/api/etl-pipeline.html ETL Pipeline :: Spring AI Reference Spring AI / Reference / Retrieval Augmented Generation (RAG) / ETL Pipeline ETL Pipeline The Extract, Transform, and Load (ETL) framework serves as the backbone of data processing within the Retrieval Augmented Generation (RAG) use case. The ETL pipeline orchestrates the flow from raw data sources t... docs.spring.io ​ ETL 파이프라인 ​ ETL 파이프라인은 데이터를 : Extract → Transfer → Load 하는 일련의 과정을 부릅니다. ETL은 기존 데이터 분야에서 이미 사용되는 용어이며, 응용 AI에서는 RAG를 구축하기 위해, 내 데이터로 부터 다른 데이터를 만들기 위해 위의 과정을 활용 합니다. 스프링 AI에서는 각 과정을 interface와 기본 구현체로 제공하고 있습니다. - Extract 인터페이스 public interface DocumentReader extends Supplier> { default List read() { return get(); } } ​ - Transfer 인터페이스 public interface DocumentTransformer extends Function, List> { default List transform(List transform) { return apply(transform); } } ​ - Load 인터페이스 public interface DocumentWriter extends Consumer> { default void write(List documents) { accept(documents); } } ​ https://docs.spring.io/spring-ai/reference/api/etl-pipeline.html#_etl_interfaces ETL Pipeline :: Spring AI Reference Spring AI / Reference / Retrieval Augmented Generation (RAG) / ETL Pipeline ETL Pipeline The Extract, Transform, and Load (ETL) framework serves as the backbone of data processing within the Retrieval Augmented Generation (RAG) use case. The ETL pipeline orchestrates the flow from raw data sources t... docs.spring.io ​ 스프링 AI ETL 사용? ​ ETL 자체는 기존에도 관련 도구들이 많고 스프링 배치로도 충분히 좋은 퍼포먼스를 가질 수 있어, 모든 요소를 스프링 AI 모듈 기반으로 사용하지는 않을것 같고, Extract의 여러 DocumentReader 들을 응용할 거 같습니다. ​ - Extract : Reader 구현체를 위한 의존성 추가 implementation 'org.springframework.ai:spring-ai-markdown-document-reader' implementation 'org.springframework.ai:spring-ai-pdf-document-reader' implementation 'org.springframework.ai:spring-ai-tika-document-reader' ​ - 스프링 AI DocumentReader 구현체 - JsonReader - TextReader - JsoupDocumentReader - MarkdownDocumentReader - PagePdfDocumentReader - ParagraphPdfDocumentReader - TikaDocumentReader (DOCX, PPTX, …) ​ 대략적인 적용법 ​ - resources 경로에 파일 업로드 (Controller로 받아도 무방) - Reader 구현체 컴포넌트 등록 @Component public class MyJsonReader { private final Resource resource; public MyJsonReader(@Value("classpath:data.PageCollection.json") Resource resource) { this.resource = resource; } public List loadJsonAsDocuments() { JsonReader jsonReader = new JsonReader(this.resource, "_id"); return jsonReader.get(); } } import시 비슷한 클래스 이름들이 많은데, 거의 ai path가 들어간 모듈들을 찾으면 됩니다. ​ - 활용 return myJsonReader.loadJsonAsDocuments(); ​ 이전 : 9 RAG를 위한 Advisor https://youtu.be/gdN916ZC3EI 34, 스프링 시큐리티에서 OAuth2 클라이언트 의존성을 활용한 OAuth2.0 프로토콜 기반의 OIDC(OpenID Connect) 인증 방법을 알아보도록 하겠습니다. 본 시리즈는 개발자 유미 채널의 “스프링 OAuth2 클라이언트 세션”, “스프링 OAuth2 클라이언트 JWT” 중 하나를 시청하신 상태로 OAuth2 인증 절차의 개념을 아시는 분을 타겟으로 진행합니다. ​ 스프링 시큐리티 OIDC ​ 1. OAuth2와 OIDC 2. 프로젝트 생성 및 의존성 추가 3. 네이버, 구글 OIDC 변수 등록 4. OidcUserService 데이터 커스텀 ​ 35, 스프링 시큐리티 OIDC > 1. OAuth2와 OIDC 사전 지식 ​ OAuth2.0 code 인증 방식의 원리와 스프링 OAuth2 클라이언트의 대략적인 동작 적용 방법을 알고 계셔야 합니다. 아래 2개의 시리즈 중 1개를 시청하셨다고 가정하고 진행합니다. - 스프링 OAuth2 클라이언트 (세션/JWT) 시리즈 https://www.youtube.com/playlist?list=PLJkjrxxiBSFBGk0b931ZkCVlNUo7sFisu https://www.youtube.com/playlist?list=PLJkjrxxiBSFALedMwcqDw_BPaJ3qqbWeB ​ 기존 OAuth2 Code 방식 인증 흐름과 OIDC 비교 ​ - OAuth2 code 방식 : 스프링 시큐리티 백엔드 요청 과정 ​ - OIDC ​ OIDC는 CODE → 토큰 교환 과정에서 scope에 openid라는 값을 명시해서 보내면 “인증 서버” 측에서 Access/Refresh 이외에도 id 토큰도 보내줍니다. 기존 OAuth2는 받은 Access 토큰을 다시 리소스 서버에 보내 유저 정보를 받아오지만, id 토큰은 토큰 payload에 간략한 유저 정보가 함께 담겨 옵니다. ​ 사실 OAuth2는 ​ OAuth2는 사실 권한을 위임하는 프로토콜이라 정확한 유저 정보는 그 과정에서 받은 토큰으로 리소스 서버에 접근해야 함. 반면 OIDC는 유저 정보를 포함하는 id 토큰으로 그 과정을 수행할 수 있음 - OIDC 장점 - 표준화 됨 : id 토큰 payload가 표준화 되어 있어 서비스 제공자가(네이버, 카카오, 구글) OIDC만 지원한다면 어떤 데이터를 받는지 예측 가능 → OAuth2에서는 제공자 마다 어떤 데이터를 주는지 공식 문서를 읽고 맞춰줘야함 - SSO 구현 쉬움 id 토큰만 내려주면 됨 ​ 다음 : 2. 프로젝트 생성 및 의존성 추가 https://youtu.be/pmwz5q9VURw 36, 스프링 시큐리티 OIDC > 2. 프로젝트 생성 및 의존성 추가 의존성 ​ - build.gradle > dependencies implementation 'org.springframework.boot:spring-boot-starter-oauth2-client' implementation 'org.springframework.boot:spring-boot-starter-security' implementation 'org.springframework.boot:spring-boot-starter-web' compileOnly 'org.projectlombok:lombok' annotationProcessor 'org.projectlombok:lombok' testImplementation 'org.springframework.boot:spring-boot-starter-test' testImplementation 'org.springframework.security:spring-security-test' testRuntimeOnly 'org.junit.platform:junit-platform-launcher' ​ SecurityConfig 작성 ​ - config > SecurityConfig.java @Configuration @EnableWebSecurity public class SecurityConfig { @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http .csrf((csrf) -> csrf.disable()); http .formLogin((login) -> login.disable()); http .httpBasic((basic) -> basic.disable()); http .oauth2Login(Customizer.withDefaults()); http .authorizeHttpRequests((auth) -> auth .requestMatchers("/**").permitAll() .anyRequest().authenticated()); return http.build(); } } ​ 기타 이미 OAuth2 클라이언트에서 소셜 로그인을 하는 과정을 알았기 때문에, 따로 DB는 붙이지 않겠습니다. ​ 소셜 로그인 제공 업체에게 OIDC를 사용하겠다라는 설정 방법과 id_token으로 부터 값을 파싱하는 OidcUserService 클래스의 메소드에 대해 알아보겠습니다. ​ 이전 : 1. OAuth2와 OIDC 다음 : 3. 네이버, 구글 OIDC 변수 등록 https://youtu.be/cUf6rLpuTis 37, 스프링 시큐리티 OIDC > 3. 네이버, 구글 OIDC 변수 등록 OIDC를 위한 application.properties 등록 ​ OIDC 소셜 로그인 신청은 기존 “네이버”, “구글” OAuth2 시리즈 방식과 완전 동일합니다. ​ 다만 아래 주의점을 봐야합니다. 1. 서비스 제공 업체의 OIDC 지원 여부 2. OIDC 지원 api 주소 (OAuth2와 조금 다름) 3. scope 설정 ​ Scope 설정은 ​ OIDC는 단 하나 scope 설정에 무조건 openid가 포함되어야 합니다. openid 값을 명시 했다면 “OAuth2 클라이언트” 의존성은 OIDC 로그인으로 판단합니다. - scope=openid 설정시 Provider 선택 OAuth2 인증과 OIDC 인증 모두 code를 발급 받은 후 동일한 OAuth2LoginAuthenticationFilter를 사용합니다. 하지만 그 뒤에 존재하는 Provider는 각기 다릅니다. 다르게 선택되는 이유는 결국 scope=openid 설정 때문에 그렇습니다. scope 값에 openid가 포함된다면 Provider 중 OidcAuthorizationCodeAuthenticationProvider가 선택되게 됩니다. - OAuth2LoginAuthenticationProvider : OAuth2 사용시 ​ - OidcAuthorizationCodeAuthenticationProvider : OIDC 사용시 ​ 2개의 인증 메소드 (authenticate) 모두 scope의 OPENID 여부에 따른 사용 여부가 달라진다. ​ 네이버 OIDC 설정 ​ - application.properties spring.security.oauth2.client.registration.naver.client-name=naver spring.security.oauth2.client.registration.naver.client-id= spring.security.oauth2.client.registration.naver.client-secret= spring.security.oauth2.client.registration.naver.redirect-uri=http://localhost:8080/login/oauth2/code/naver spring.security.oauth2.client.registration.naver.authorization-grant-type=authorization_code spring.security.oauth2.client.registration.naver.scope=openid spring.security.oauth2.client.provider.naver.issuer-uri=https://nid.naver.com spring.security.oauth2.client.provider.naver.authorization-uri=https://nid.naver.com/oauth2/authorize spring.security.oauth2.client.provider.naver.jwk-set-uri=https://nid.naver.com/oauth2/jwks spring.security.oauth2.client.provider.naver.token-uri=https://nid.naver.com/oauth2/token ​ https://developers.naver.com/docs/login/devguide/devguide.md#3-5-open-id-connect%EB%A1%9C-%EB%84%A4%EC%9D%B4%EB%B2%84-%EB%A1%9C%EA%B7%B8%EC%9D%B8-%EC%97%B0%EB%8F%99%ED%95%98%EA%B8%B0 네이버 로그인 개발가이드 - LOGIN 네이버 로그인 개발가이드 1. 개요 2. 네이버 로그인 서비스 소개 2.1 네이버 로그인 서비스에 대하여 2.2 제공하는 기능 2.2.1 소셜 로그인 2.2.2 로그인 연동 회원 프로필 조회 2.2.3 네이버의 로그인 오픈API 이용 2.2.4 서비스 이용 통계 developers.naver.com ​ 구글 OIDC 설정 ​ - application.properties spring.security.oauth2.client.registration.google.client-name=google spring.security.oauth2.client.registration.google.client-id= spring.security.oauth2.client.registration.google.client-secret= spring.security.oauth2.client.registration.google.redirect-uri=http://localhost:8080/login/oauth2/code/google spring.security.oauth2.client.registration.google.authorization-grant-type=authorization_code spring.security.oauth2.client.registration.google.scope=openid ​ 결론 ​ 1. 서비스 제공 업체의 OIDC 지원 여부 2. OIDC 지원 api 주소 (OAuth2와 조금 다름) 3. scope 설정 위 3가지를 확인과 설정한다면 바로 OIDC 로그인이 가능합니다. 이렇게 로그인을 했지만, 추가적으로 id_token으로 부터 유저 정보를 파싱하는 OidcUserService 클래스 메소드를 커스텀 하겠습니다. ​ 이전 : 2. 프로젝트 생성 및 의존성 추가 다음 : 4. OidcUserService 데이터 커스텀 https://youtu.be/m7TZPXymWyw 38, 스프링 시큐리티 OIDC > 4. OidcUserService 데이터 커스텀 id_token 데이터 파싱 ​ application.properties에 변수 설정만 하더라도 OIDC 기본 설정으로 로그인을 수행할 수 있습니다. 하지만 우리는 몇가지를 커스텀해야하는 경우 (서비스로 부터 제공 받은 유저 정보 저장, SecurityContext 커스텀)를 위해 id_tokne을 파싱하는 Service단을 커스텀하겠습니다. ​ ​ 기본 Service단은 OidcUserService 입니다. ​ OidcUserService 메소드 Override ​ - UserService.java @Service public class UserService extends OidcUserService { @Override public OidcUser loadUser(OidcUserRequest userRequest) throws OAuth2AuthenticationException { OidcUser oidcUser = super.loadUser(userRequest); System.out.println(oidcUser); System.out.println(oidcUser.getIdToken()); System.out.println(oidcUser.getUserInfo()); System.out.println(oidcUser.getClaims()); // ROLE 만들어 넣기 Set authorities = new HashSet<>(); authorities.add(new SimpleGrantedAuthority("ROLE_USER")); return new DefaultOidcUser(authorities, oidcUser.getIdToken(), oidcUser.getUserInfo()); } } ​ 이전 : 3. 네이버, 구글 OIDC 변수 등록 https://youtu.be/F4BYXYUet-o 40, Open WebUI는 OpenAI 등 다양한 LLM API와 연동해, ChatGPT와 유사한 대화형 웹 인터페이스를 구축할 수 있게 해주는 오픈소스로, 이를 활용해 자체 AI 시스템을 구축하는 방법에 대해 알아보겠습니다. ​ Open WebUI ​ 1. Open WebUI란? 2. Quick Start 3. 운용 범위 4. 웹 검색 5. pipeline ​ 41, Open WebUI > 1. Open WebUI란? Open WebUI ​ 다양한 LLM API를 기반으로 ChatGPT와 같은 인터페이스를 가진 서비스를 설계하려면 어떻게 해야할까요? ​ - 서비스 업체 : OpenAI, Anthropic - 직접 서빙 : vLLM, Ollama, Llama.cpp 스프링 부트, FastAPI, Express.js 와 같은 프레임워크를 활용하여 직접 구축해야 합니다. 하지만 아래와 같은 요구사항이 발생할 거 같습니다. ​ - UI - 유저별 인증/인가, 독립된 환경 - 멀티턴, 대화 저장 - 파라미터 설정 - 다양한 LLM API 통합 - RAG - 플러그인, 이미지 업로드 위의 솔루션을 최대한 빠르게 충족 시키기 위한 LLM API 웹 기반 인터페이스 프레임워크가 존재합니다. ​ ​ 다음 : 2. Quick Start https://youtu.be/Qk74tAvJNls?si=4EYBNPYL47NEt8HE 42, Open WebUI > 2. Quick Start Quick Start 목표 ​ LLM API : OpenAI API 키 발급 Open WebUI : 도커 기반으로 구동 ​ OpenAI API 키 발급 (개인 준비) ​ 여기서 OpenAI API 키를 발급하는데 오래 걸릴거 같습니다. 대략적으로 아래와 같이 진행됩니다. ​ 1. OpenAI 회원 가입 2. Billing을 위한 카드 등록 (처음 몇 달러 결제 후 자동 취소) 3. 크레딧 충전 4. API Key 발급 - OpenAI API 키 발급 구글 검색 바로가기 ​ - API 플랫폼 Home https://platform.openai.com/docs/overview ​ - API keys https://platform.openai.com/settings/organization/api-keys ​ ​ 도커 환경 Open WebUI 설치 ​ Open WebUI도 결국 웹 어플리케이션입니다. (스프링 부트 jar 배포 파일과 같은) 따라서 여러 방식으로 설치할 수 있습니다. ​ 이번 시간엔 도커 컨테이너 기반으로 운용하겠습니다. ​ - 도커 명령어​ sudo docker run -d --name openwebui -p 3000:8080 -v /home/xxxjjhhh/openwebui:/app/backend/data ghcr.io/open-webui/open-webui:main ​ 마운트가 필요합니다. ​ 첫 회원 가입 : 관리자 계정 ​ 도커 구동 이후 웹으로 접근한다면, 회원 가입창이 발생합니다. 이때 가입하는 첫 계정이 관리자 계정으로 할당됩니다. ​ ​ OpenAI API 키 등록 ​ 관리자 계정 로그인 후, 설정을 진행하셔야 LLM API를 연결하실 수 있습니다. ​ ​ ​ ​ 기타 ​ 정말 간단하게 Quick Start 했습니다. 이를 통해 대략적인 큼직한 틀을 확인하실 수 있을거 같습니다. 다음 시간부터 조금 더 자세하게 파고들어가겠습니다. ​ 이전 : 1. Open WebUI란? 다음 : 3. 운용 범위 https://youtu.be/rPsWvdVhvw0?si=Lg5G7lYXEbLX81pZ 43, Open WebUI > 3. 운용 범위 운용 범위 ​ Open WebUI를 기반으로 LLM 챗봇 서비스를 구축할 때, 서비스 주최자에 따른 운용 범위가 있을거 같습니다. 범위 설정 및 몇 가지 설정에 대해 알아보겠습니다. - 가입 요구 - 가입 후 승인 요구 됨 : 특정 집단 - 가입 후 바로 사용 가능 : 단순 회원 파악용 - 공개 : 국가 공식 홈페이지와 같이 오픈용 각각의 범위에 대한 유저 설정을 알아보겠습니다. ​ 가입 요구 : 승인/비승인 ​ 어드민 계정으로 접속하여 설정을 진행합니다. - 설정 진행 ​ ​ ​ 1차적으로 새 회원가입 활성화를 enable 시킨 후, 승인/비승인에 따라 보류 중, 사용자로 선택하시면 됩니다. ​ - 기타 접근 유저 ​ ​ ​ 보류 중 설정을 진행한다면, 관리자가 승인까지 사용이 불가능합니다. ​ 공개 ​ 아쉽게도 오픈 방식은 제공하지 않습니다. 극단적으로 1인 사용 모드가 존재하지만, 외부인에게 공개하는 순간 1개의 계정을 함께 사용하는 방식이 됩니다. 어드민 계정을 따로 두고, 나머지 이용자는 로그인 없이 사용하도록 하려면 FastAPI와 프론트 코드를 많이 수정해야 합니다. ​ OAuth2 ​ OIDC 로그인 설정도 가능합니다. ​ https://docs.openwebui.com/features/sso/#oidc 🔒 SSO: Federated Authentication Support | Open WebUI Open WebUI supports several forms of federated authentication: docs.openwebui.com ​ Google, MS, Github는 공식 지원되며, 기타는 커스텀 가능합니다. 아래는 네이버 기반으로 테스트 등록을 마친 상태입니다. (OAuth2의 OIDC 개념만 아신다면 바로 설정 가능합니다, 진행하시면서 어려운 부분 댓글 남겨주시면 답변드리겠습니다.) ​ sudo docker run -d \ --name openwebui1 \ -p 3000:8080 \ -v /home/xxxjjhhh/openwebui:/app/backend/data \ -e OAUTH_CLIENT_ID= \ -e OAUTH_CLIENT_SECRET= \ -e OPENID_PROVIDER_URL=https://nid.naver.com/.well-known/openid-configuration \ -e OAUTH_PROVIDER_NAME="NAVER Login" \ -e OAUTH_SCOPES="openid" \ -e ENABLE_OAUTH_SIGNUP=true \ -e OAUTH_MERGE_ACCOUNTS_BY_EMAIL=false \ -e OAUTH_UPDATE_PICTURE_ON_LOGIN=false \ -e ENABLE_SIGNUP=false \ ghcr.io/open-webui/open-webui:main ​ ​ 모델 사용 설정 ​ 어드민 계정을 통해 추가한 모델은 나머지 사용자에게도 보여야 합니다. 하지만 기본 설정만으론 보여지지 않습니다. - 모델 공개 ​ ​ ​ 기타 ​ 공개된 역사가 길지 않고 커스텀할 수 있는 부분이 많이 알려져 있지 않다보니, 자세한 설정은 어렵습니다. 직접 코드 레벨까지 다가가야하는 부분이 많지만, 매 릴리즈마다 새로운 기능들이 추가되고 있어 앞으로 GUI 기반 설정들이 많아질 거 같습니다. ​ 이전 : 2. Quick Start 다음 : 4. 웹 검색 https://youtu.be/YsDkn9e-pNU 44, Open WebUI > 4. 웹 검색 툴 추가 : 웹 검색 ​ Open WebUI를 사용하기 위한 기본적인 환경 구축은 마무리 했습니다. 여기에 함께 사용할 수 있는 툴들을 붙이겠습니다. 가장 처음으로 붙일 툴은 웹 검색 툴 입니다. ​ 웹 검색 ​ https://docs.openwebui.com/category/-web-search/ 🌐 Web Search | Open WebUI 🌐 Web Search 📄️ Bing This tutorial is a community contribution and is not supported by the Open WebUI team. It serves only as a demonstration on how to customize Open WebUI for your specific use case. Want to contribute? Check out the contributing tutorial. 📄️ Brave This tutorial is a community c... docs.openwebui.com ​ 검색 툴은 다양한 검색 API를 기반으로 연결할 수 있습니다. 그 중 Google PSE를 예시로 진행하겠습니다. ​ 신청 방법 ​ 총 2가지의 단계를 거쳐 진행해야 합니다. 우선 Custom Search JSON API 키를 발급 받아야하고, PSE id를 발급 받아야 합니다. - Custom Search JSON API 키 발급 https://developers.google.com/custom-search/v1/overview?hl=ko Custom Search JSON API | Programmable Search Engine | Google for Developers 이 페이지는 Cloud Translation API 를 통해 번역되었습니다. 홈 chevron_right 제품 chevron_right Programmable Search Engine chevron_right 가이드 Custom Search JSON API Custom Search JSON API를 사용하면 프로그래밍 검색 엔진의 검색결과를 프로그래매틱 방식으로 검색하여 표시하는 웹사이트와 애플리케이션을 개발할 수 있습니다. 이 API를 사용하면 RESTful 요청을 사용하여 웹 검색 또는 이미지 검색 결과를 JSON 형식으로 얻을... developers.google.com ​ ​ ​ - PSE ID 발급 https://programmablesearchengine.google.com/controlpanel/all Sign in - Google Accounts Couldn’t sign you in The browser you’re using doesn’t support JavaScript, or has JavaScript turned off. To keep your Google Account secure, try signing in on a browser that has JavaScript turned on. Learn more Help Privacy Terms programmablesearchengine.google.com ​ ​ ​ ​ 등록 ​ ​ 기타 : 발급한 API 키 삭제 방법 ​ GCP > 콘솔 > 좌측 햄버거 버튼 > API 및 서비스 > 사용자 인증 정보 > API 키 ​ 이전 : 3. 운용 범위 다음 : 5. pipeline https://youtu.be/mq2J8zTfEsk 45, Open WebUI > 5. pipeline 파이프라인 ​ Open WebUI의 파이프라인은 사용자의 요청을 처리할 수 있는 모듈로 “커스텀 API”, “API 호출 전/후 처리”가 가능합니다. Open WebUI 공식 문서를 통해 제공되는 케이스들을 확인하겠습니다. https://docs.openwebui.com/pipelines/ ⚡ Pipelines | Open WebUI DO NOT USE PIPELINES IF! docs.openwebui.com ​ - 함수 호출 (툴) - 커스텀 RAG - 메시지 모니터링 - Rate Limit - 실시간 번역 - 스팸 필터 ​ 파이프라인을 붙이기 위해 pipeline 어댑터가 요구됩니다. ​ “Open WebUI” 앱은 바로 pipeline을 붙일 수 없기 때문에 “pipeline”이라는 어댑터 앱이 요구됩니다. 다양한 방식 (로컬 설치, 도커)으로 제공되지만 도커로 구동하겠습니다. ​ sudo docker run -d -p 9099:9099 --add-host=host.docker.internal:host-gateway -v pipelines:/app/pipelines --name pipelines --restart always ghcr.io/open-webui/pipelines:main ​ Open WebUI에서 Pipeline 어댑터 연결 ​ 이전 설정들과 동일하게 어드민 계정으로 관리자 패널에 접근해야 합니다. (GUI로 진행) ​ ​ ​ 가장 처음으로 도커로 띄운 Pipeline 어댑터를 붙이기 위한 연결에 접속합니다. ​ ​ OpenAI API 연결과 동일한 규격이라 OpenAI API에서 + 버튼을 클릭합니다. ​ ​ Open WebUI와 Pipeline 어댑터가 같은 서버에 존재하기 때문에 localhost로 칭했으며 다른 서버일 경우 IP 값을 입력하시면 됩니다. (같은 서버라도 localhost 오류가 있기 때문에 IP를 입력하시면 해결될 수 있습니다.) ​ 비밀번호(키)는 아래와 같습니다. 0p3n-w3bu! ​ Pipeline 어댑터에 커스텀 파이프라인 추가 ​ 이제 우리가 붙여둔 어댑터에 개인적으로 준비한 파이프라인을 붙이면 됩니다. ​ ​ 설정에서 파이프라인 항목 선택 ​ ​ py 파일을 선택하려면 여기를 클릭하세요.를 통해 다운 받거나 개인적으로 만드신 파이프라인을 업로드 후 우측 버튼을 클릭하면 아래 “파이프라인 밸브”에 항목을 확인할 수 있습니다. ​ 파이프라인 종류 ​ 파이프라인 파이썬 코드를 만들어야합니다. (제공되는 것을 사용해도 됩니다.) 만들기 위해 대략적인 내용에 대해 살펴보겠습니다. 파이프라인은 크게 2종류로 나뉩니다. - 응답 생성형 : Pipe : 사용자의 프롬프트를 받아 API 호출을 해서 최종 응답 까지 만들어냄 - 필터형 (전/후 처리) : Filter : API 호출 전후에 처리 과정을 넣을 수 있음 제공되는 샘플들도 2개로 나뉩니다. ​ https://github.com/open-webui/pipelines/tree/main/examples pipelines/examples at main · open-webui/pipelines Pipelines: Versatile, UI-Agnostic OpenAI-Compatible Plugin Framework - open-webui/pipelines github.com ​ - 생성 (동일) : 클래스 선언 class Pipeline: ​ - 메소드 구현 (동일) : 모듈 시작과 종료시 사용할 메소드 async def on_startup(self): async def on_shutdown(self): ​ - Pipe용 메소드 def pipe(self, user_message, model_id, messages, body) -> response: ​ - Filter용 메소드 async def inlet(self, body: dict, user: dict) -> dict: async def outlet(self, body: dict, user: dict) -> dict: ​ 이전 : 4. 웹 검색 다음 : 6. https://youtu.be/APJVaYBsyO8 46, 스프링 시큐리티의 내부 구조와 각 필터들의 동작 원리를 살펴보는 시리즈입니다. ​ 스프링 시큐리티 내부 구조 ​ 1. 시리즈 목표 2. 시큐리티 동작 원리 3. DelegatingFilterProxy FilterChainProxy 4. SecurityFilterChain 등록 5. SecurityFilterChain 구조 6. SecurityContextHolder 7. 필터 상속과 요청 전파 8. GenericFilterBean, OncePerRequestFilter 9. DisableEncodeUrlFilter 10. WebAsyncManagerIntegrationFilter 11. SecurityContextHolderFilter 12. HeaderWriterFilter 13. CorsFilter 14. CsrfFilter 15. LogoutFilter 16. UsernamePasswordAuthenticationFilter 17. DefaultLoginPageGeneratingFilter 18. DefaultLogoutPageGeneratingFilter 19. BasicAuthenticationFilter 20. RequestCacheAwareFilter 21. SecurityContextHolderAwareRequestFilter 22. AnonymousAuthenticationFilter 23. ExceptionTranslationFilter 24. AuthorizationFilter 25. SessionManagementConfigurer ​ 47, 스프링 시큐리티 내부 구조 > 1. 시리즈 목표 목표 ​ 스프링 시큐리티 프레임워크의 구조와 각각의 동작 원리를 확인하여 기본적으로 어떻게 동작하고 커스텀한 부분이 어떻게 적용되는지 이해합니다. 버전 및 의존성 ​ - Spring Boot 3.2.X - Spring Security 6.2.X ​ 기타 ​ - 스프링 시큐리티 의존성을 추가하여 사용하지만 내부적으로 어떻게 동작되는지 모르시는 분들을 위해 준비했습니다. ​ - 현재 스프링 부트 3 (시큐리티 6) 버전으로 많은 부분이 변경되었지만 대부분의 블로그가 예전 버전의 구조도와 클래스를 가지고 설명하기 때문에 현재 버전에 알맞은 내용을 올리고자 합니다. ​ - 실제로 구현하는 실습적인 부분은 없습니다. 전부 개념적인 내용입니다. ​ 참조 ​ https://docs.spring.io/spring-security/reference/servlet/architecture.html Architecture :: Spring Security Spring Security / Servlet Applications / Architecture Architecture This section discusses Spring Security’s high-level architecture within Servlet based applications. We build on this high-level understanding within the Authentication , Authorization , and Protection Against Exploits sections of the... docs.spring.io ​ 다음 : 2. 시큐리티 동작 원리 https://youtu.be/ovXZrpZ2X7U 48, 스프링 시큐리티 내부 구조 > 2. 시큐리티 동작 원리 https://docs.spring.io/spring-security/reference/servlet/architecture.html Architecture :: Spring Security Spring Security / Servlet Applications / Architecture Architecture This section discusses Spring Security’s high-level architecture within Servlet based applications. We build on this high-level understanding within the Authentication , Authorization , and Protection Against Exploits sections of the... docs.spring.io 목표 ​ 전반적인 동작 로직을 살펴본 뒤, 추후 영상에서 각각의 자세한 과정을 살펴볼 예정입니다. ​ 사용자의 요청 → 컨트롤러 : (시큐리티 의존성 없는 경우) ​ ​ 클라이언트의 요청은 서버 컴퓨터의 WAS (톰캣)의 필터들을 통과한 뒤 스프링 컨테이너의 컨트롤러에 도달한다. (컨트롤러 앞단에 여러 과정이 존재하지만, 시큐리티를 다루는 과정에서 중요하지 않기 때문에 생략) ​ ​ 시큐리티 의존성의 추가 : 사용자의 요청을 감시하려면? ​ - 스프링 시큐리티가 사용자의 요청을 감시하고 통제하는 지점 WAS의 필터단에서 요청을 가로챈 후 시큐리티의 역할을 수행한다. - 엄밀한 정의 WAS의 필터에 하나의 필터를 만들어서 넣고 해당 필터에서 요청을 가로챔 해당 요청은 스프링 컨테이너 내부에 구현되어 있는 스프링 시큐리티 감시 로직을 거침 시큐리티 로직을 마친 후 다시 WAS의 다음 필터로 복귀 - 모식도 ​ ​ - 공식 이미지 ​ ​ 스프링 시큐리티 로직은 어떻게 구성되는지 ​ ​ 스프링 시큐리티 로직은 여러개의 필터들이 나열된 필터 체인 형태로 구성되어 있다. ​ ​ 각각의 필터에서 CSRF, 로그아웃, 로그인, 인가, 등 여러 작업을 수행한다. ​ - 시큐리티 필터 체인 : 일연의 과정들을 수행하는 필터들의 묶음 ​ ​ - 여러개의 시큐리티 필터 체인을 가질 수 있음 ​ ​ 주요 부분 용어 ​ - DelegatingFilterProxy 스프링 Bean을 찾아 요청을 넘겨주는 서블릿 필터 - FilterChainProxy 스프링 시큐리티 의존성을 추가하면 DelegatingFilterProxy에 의해 호출되는 SecurityFilterChain들을 들고 있는 Bean - SecurityFilterChain 스프링 시큐리티 필터들의 묶음으로 실제 시큐리티 로직이 처리되는 부분, FilterChainProxy가 SecurityFilterChain들을 들고 있다. 이전 : 1. 시리즈 목표 다음 : 3. DelegatingFilterProxy FilterChainProxy https://youtu.be/OmP-GNRLA0Y 49, 스프링 시큐리티 내부 구조 > 3. DelegatingFilterProxy FilterChainProxy 모식도 ​ ​ - FilterChainProxy ​ ​ DelegatingFilterProxy ​ - 시큐리티 DelegatingFilterProxy 등록 Config : SecurityAutoConfiguration @AutoConfiguration(after = SecurityAutoConfiguration.class) @ConditionalOnWebApplication(type = Type.SERVLET) @EnableConfigurationProperties(SecurityProperties.class) @ConditionalOnClass({ AbstractSecurityWebApplicationInitializer.class, SessionCreationPolicy.class }) public class SecurityFilterAutoConfiguration { private static final String DEFAULT_FILTER_NAME = AbstractSecurityWebApplicationInitializer.DEFAULT_FILTER_NAME; @Bean @ConditionalOnBean(name = DEFAULT_FILTER_NAME) public DelegatingFilterProxyRegistrationBean securityFilterChainRegistration( SecurityProperties securityProperties) { DelegatingFilterProxyRegistrationBean registration = new DelegatingFilterProxyRegistrationBean( DEFAULT_FILTER_NAME); registration.setOrder(securityProperties.getFilter().getOrder()); registration.setDispatcherTypes(getDispatcherTypes(securityProperties)); return registration; } private EnumSet getDispatcherTypes(SecurityProperties securityProperties) { if (securityProperties.getFilter().getDispatcherTypes() == null) { return null; } return securityProperties.getFilter() .getDispatcherTypes() .stream() .map((type) -> DispatcherType.valueOf(type.name())) .collect(Collectors.toCollection(() -> EnumSet.noneOf(DispatcherType.class))); } } ​ 이때 등록되는 DelegatingFilterProxy의 이름은 springSecurityFilterChain (스프링 시큐리티 의존성을 추가하면 자동으로 등록 됨) ​ - DelegatingFilterProxy public class DelegatingFilterProxy extends GenericFilterBean { } ​ ​ FilterChainProxy : springSecurityFilterChain ​ - SecurityFilterChain 목록 : FilterChainProxy public class FilterChainProxy extends GenericFilterBean { } ​ ​ SecurityFilterChain 등록 ​ 4강에서 진행 ​ 이전 : 2. 시큐리티 동작 원리 다음 : 4. SecurityFilterChain 등록 https://youtu.be/f4uNwHd3kUw 50, 스프링 시큐리티 내부 구조 > 4. SecurityFilterChain 등록 모식도 ​ ​ ​ 커스텀 SecurityFilterChain 등록 ​ 스프링 시큐리티 의존성을 추가하면 기본적인 DefaultSecurityFilterChain 하나가 등록된다. 내가 원하는 SecurityFilterChain을 등록하기 위해서는 SecurityFilterChain을 리턴하는 @Bean 메소드를 등록하면 된다. (한 개 이상 등록 가능) - 커스텀 SecurityFilterChain 한 개 등록 @Configuration @EnableWebSecurity public class SecurityConfig { @Bean public SecurityFilterChain filterChain1(HttpSecurity http) throws Exception{ return http.build(); } } ​ - 커스텀 SecurityFilterChain 두 개 등록 @Configuration @EnableWebSecurity public class SecurityConfig { @Bean public SecurityFilterChain filterChain1(HttpSecurity http) throws Exception{ return http.build(); } @Bean public SecurityFilterChain filterChain2(HttpSecurity http) throws Exception { return http.build(); } } ​ filterChainProxy에서 등록 확인 ​ - filterChainProxy : break 포인트 후 debug 모드 실행 ​ ​ - 디버그 로그를 통한 SecurityFilterChain 사이즈 확인 ​ ​ 멀티 SecurityFilterChain 중 하나 선택 ​ FilterChainProxy는 N개의 SecurityFilterChain 중 하나를 선택해서 요청을 전달한다. 선택 기준은 아래와 같다. - 기준 1. 등록 인덱스 순 2. 필터 체인에 대한 RequestMatcher 값이 일치하는지 확인 (인가 설정이 아님, 아래에서 설명) ​ ​ 멀티 SecurityFilterChain 경로 설정 : 필수 ​ - 참고 자료 스프링 시큐리티 Authorize HttpServletRequests 공식 문서 바로가기 - 문제 상황 발생 멀티 SecurityFilterChain을 설정시 N개의 SecurityFilterChain이 모두 “/**” 경로에서 매핑된다. - 예시 상황 @Bean public SecurityFilterChain filterChain1(HttpSecurity http) throws Exception { http .authorizeHttpRequests((auth) -> auth .requestMatchers("/user").permitAll()); return http.build(); } @Bean public SecurityFilterChain filterChain2(HttpSecurity http) throws Exception { http .authorizeHttpRequests((auth) -> auth .requestMatchers("/admin").permitAll()); return http.build(); } ​ 2개의 커스텀 SecurityFilterChain을 등록하고 “/user”, “/admin” 경로에 대해서 permitAll() 설정을 진행한다. (해당하는 컨트롤러는 만들어 둠) 이후 “/admin” 경로로 요청을 보내면 별다른 인증 과정 없이 “/admin” 컨트롤러의 데이터를 획득할 수 있다고 생각하지만 시큐리티의 매핑 자체가 없어서 잘못된 응답이 발생한다. 이유는 filterChain1이 filterChain2 보다 먼저 등록되어 있고 SecurityFilterChain에 대한 경로 설정을 추가적으로 하지 않았기 때문에 “/**” 경로에 대해서 반응하기 때문이다. 따라서 filterChain1로 요청이 전달되었고 filterChain1 내부의 인가 설정에서는 “/admin”에 대한 설정이 없기 때문에 거부가 발생된다. ​ - SecurityFilterChain에 대한 경로 매핑 : securityMatchers @Bean public SecurityFilterChain filterChain1(HttpSecurity http) throws Exception { http .securityMatchers((auth) -> auth.requestMatchers("/user")); http .authorizeHttpRequests((auth) -> auth .requestMatchers("/user").permitAll()); return http.build(); } @Bean public SecurityFilterChain filterChain2(HttpSecurity http) throws Exception { http .securityMatchers((auth) -> auth.requestMatchers("/admin")); http .authorizeHttpRequests((auth) -> auth .requestMatchers("/admin").authenticated()); return http.build(); } ​ 멀티 SecurityFilterChain 순서 설정 : 선택 ​ N개의 SecurityFilterChain을 등록 한 뒤 등록되는 순서를 직접 선정하고 싶은 경우 @Order() 어노테이션에 값을 명시할 수 있다. ​ @Bean @Order(1) public SecurityFilterChain filterChain1(HttpSecurity http) throws Exception{ return http.build(); } @Bean @Order(2) public SecurityFilterChain filterChain2(HttpSecurity http) throws Exception { return http.build(); } ​ 특정 요청은 필터를 거치지 않도록 ​ SecurityFilterChain을 거치게 된다면 내부적으로 여러 가지 필터를 거치게 됩니다. 이때 서버의 자원을 사용하고 상주 시간이 발생하기 때문에 원하는 값은 필터를 통과하지 못하도록 설정할 수 있다. 보통 정적 자원 (이미지, CSS)의 경우 필터를 통과하지 않도록 아래 구문을 통해 설정할 수 있다. 설정시 하나의 SecurityFilterChain이 0 번 인덱스로 설정되며 해당 필터 체인 내부에는 필터가 없는 상태로 생성된다. ​ - 코드 @Bean public WebSecurityCustomizer webSecurityCustomizer() { return web -> web.ignoring().requestMatchers("/img/**"); } ​ - 자료 https://docs.spring.io/spring-security/site/docs/current/api/org/springframework/security/config/annotation/web/configuration/WebSecurityCustomizer.html WebSecurityCustomizer (spring-security-docs 6.5.2 API) Package org.springframework.security.config.annotation.web.configuration Interface WebSecurityCustomizer Functional Interface: This is a functional interface and can therefore be used as the assignment target for a lambda expression or method reference. @FunctionalInterface public interface WebSecur... docs.spring.io ​ 이전 : 3. DelegatingFilterProxy FilterChainProxy 다음 : 5. SecurityFilterChain 구조 https://youtu.be/QoPXJ2LEqTc 51, 스프링 부트 어플리케이션에서 DB 테이블을 자동으로 생성하는 방법에 대해 알아보겠습니다. (DB에서 테이블을 먼저 만드는 케이스가 많지만, 스프링 부트 앱 기반으로 모든 셋팅을 하는 경우 앱에서 DB 테이블을 자동 생성하는 방법에 대해 알아보겠습니다.) ​ 방식 ​ JPA의 유무로 2가지 방식에 대해 다뤄보겠습니다. - JPA가 없는 경우 - JPA가 있는 경우 (Entity) ​ DB 연결 ​ - build.gradle dependencies { implementation 'org.springframework.boot:spring-boot-starter-data-jpa' implementation 'org.springframework.boot:spring-boot-starter-jdbc' implementation 'org.springframework.boot:spring-boot-starter-web' runtimeOnly 'com.mysql:mysql-connector-j' testImplementation 'org.springframework.boot:spring-boot-starter-test' testRuntimeOnly 'org.junit.platform:junit-platform-launcher' } ​ ​ - application.properties spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver spring.datasource.url=jdbc:mysql://아이피:3306/디비명?useSSL=false&useUnicode=true&serverTimezone=Asia/Seoul&allowPublicKeyRetrieval=true spring.datasource.username=root spring.datasource.password=비밀번호 ​ JDBC (JPA Entity 없이 생성) ​ JPA를 사용하지 않아서 Entity가 없는 케이스가 있습니다. 그 경우 따로 테이블 생성 SQL 구문을 스프링 부트 프로젝트에 넣어서 DB 테이블 생성을 자동화 할 수 있습니다. ​ - application.properties : 테이블 생성을 위한 셋팅 spring.sql.init.mode=always spring.sql.init.schema-locations=classpath:schema.sql ​ - 테이블 생성 SQL 구문 저장 위치 ​ ​ - schema.sql CREATE TABLE IF NOT EXISTS oauth2_authorized_client ( client_registration_id varchar(100) NOT NULL, principal_name varchar(200) NOT NULL, access_token_type varchar(100) NOT NULL, access_token_value blob NOT NULL, access_token_issued_at timestamp NOT NULL, access_token_expires_at timestamp NOT NULL, access_token_scopes varchar(1000) DEFAULT NULL, refresh_token_value blob DEFAULT NULL, refresh_token_issued_at timestamp DEFAULT NULL, created_at timestamp DEFAULT CURRENT_TIMESTAMP NOT NULL, PRIMARY KEY (client_registration_id, principal_name) ); CREATE TABLE IF NOT EXISTS SPRING_AI_CHAT_MEMORY ( `conversation_id` VARCHAR(36) NOT NULL, `content` TEXT NOT NULL, `type` ENUM('USER', 'ASSISTANT', 'SYSTEM', 'TOOL') NOT NULL, `timestamp` TIMESTAMP NOT NULL, INDEX `SPRING_AI_CHAT_MEMORY_CONVERSATION_ID_TIMESTAMP_IDX` (`conversation_id`, `timestamp`) ); ​ JPA (Entity 기반 테이블 생성) ​ - application.properties spring.jpa.hibernate.ddl-auto=update spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl ​ https://youtu.be/3QoI_5olDf8 52, 스프링 시큐리티 내부 구조 > 5. SecurityFilterChain 구조 SecurityFilterChain ​ ​ SecurityFilterChain은 스프링 시큐리티의 보안, 인증/인가와 같은 주요 로직을 담당한다. 하나의 SecurityFilterChain 내부에 N개의 필터를 구성하여 각각의 필터가 하나의 로직 (로그아웃, 로그인, 인가, 등등) 수행의 시작점이 된다. ​ ​ ​ SecurityFilterChain에 등록된 필터 확인 ​ - filterChainProxy의 break point 활용 4강에서 진행한 filterChainProxy 클래스의 getFilters() 메소드를 break point를 걸어 debug 모드로 실행하는 방법. - @EnableWebecurity debug 모드 설정 @Configuration @EnableWebSecurity(debug = true) public class SecurityConfig { } ​ @EnableWebSecurity 어노테이션을 debug 모드로 설정하고 어플리케이션을 실행 후 웹 브라우저에서 아무 경로로 요청을 보내면 터미널에 통과하는 securityFilterChain의 필터 목록이 출력된다. ​ - 기본 securityFilterChain 상태에서 출력 ​ ​ - 커스텀 securityFilterChain 등록 후 출력 @Configuration @EnableWebSecurity(debug = true) public class SecurityConfig { @Bean public SecurityFilterChain filterChain1(HttpSecurity http) throws Exception { return http.build(); } } ​ ​ 스프링 시큐리티 제공 필터 간단 설명 ​ - DisableEncodeUrlFilter URL로 간주되지 않는 부분을 포함하지 않도록 설정 ​ - WebAsyncManagerIntegrationFilter 비동기로 처리되는 작업에 대해 알맞은 시큐리티 컨텍스트(세션)을 적용 ​ - SecurityContextHolderFilter 접근한 유저에 대해 시큐리티 컨텍스트 관리 ​ - HeaderWriterFilter 보안을 위한 응답 헤더 추가 (X-Frame-Options, X-XSS-Protection and X-Content-Type-Options) ​ - CorsFilter CORS 설정 필터 ​ - CsrfFilter CSRF 방어 필터 ​ - LogoutFilter 로그아웃 요청 처리 시작점 GET : “/logout” ​ - UsernamePasswordAuthenticationFilter username/password 기반 로그인 처리 시작점 POST : “/login” ​ - DefaultLoginPageGeneratingFilter 기본 로그인 페이지 생성 GET : “/login” ​ - DefaultLogoutPageGeneratingFilter 기본 로그아웃 페이지 생성 GET : “/logout” ​ - BasicAuthenticationFilter http basic 기반 로그인 처리 시작점 ​ - RequestCacheAwareFilter 이전 요청 정보가 존재하면 처리 후 현재 요청 판단 ​ - SecurityContextHolderAwareRequestFilter ServletRequest에 서블릿 API 보안을 구현 ​ - AnonymousAuthenticationFilter 최초 접속으로 인증 정보가 없고, 인증을 하지 않았을 경우 세션에 익명 사용자 설정 ​ - ExceptionTranslationFilter 인증 및 접근 예외에 대한 처리 ​ - AuthorizationFilter 경로 및 권한별 인가 (구. filterSecurityIntercepter) ​ SecurityFilterChain에 필터 활성화 및 비활성화 ​ - CORS 필터 설정 http .cors((cors) -> cors.disable()); ​ - CSRF 필터 설정 http .csrf((csrf) -> csrf.disable()); ​ - UsernamePasswordAuthenticationFilter 활성 비활성 //활성 http .formLogin(withDefaults()); //비활성 http .formLogin((login) -> login.disable()); ​ - 로그인/로그아웃 페이지 필터 활성 비활성 //formLogin 메소드 설정시 기본적으로 활성화 //커스텀시 기본 필터 비활성 http .formLogin((login) -> login.loginPage("/login").permitAll()); ​ - BasicAuthenticationFilter 활성 비활성 //활성 http .httpBasic(withDefaults()); //비활성 http .httpBasic((basic) -> basic.disable()); ​ SecurityFilterChain에 커스텀 필터 등록 ​ - SecurityConfig.java //특정필터이전 http .addFilterBefore(추가할필터, 기존필터.class); //특정필터위치 http .addFilterAt(추가할필터, 기존필터.class); //특정필터이후 http .addFilterAfter(추가할필터, 기존필터.class); ​ 이전 : 4. SecurityFilterChain 등록 다음 : 6. SecurityContextHolder https://youtu.be/pkxGYnm4UZs 53, 스프링 시큐리티 내부 구조 > 6. SecurityContextHolder https://docs.spring.io/spring-security/reference/servlet/authentication/architecture.html Servlet Authentication Architecture :: Spring Security Spring Security / Servlet Applications / Authentication / Authentication Architecture Servlet Authentication Architecture This discussion expands on Servlet Security: The Big Picture to describe the main architectural components that Spring Security uses in Servlet authentication. If you need concre... docs.spring.io SecurityFilterChain 필터별 작업 상태 저장 ​ - 상태 저장 필요 ​ ​ SecurityFilterChain 내부에 존재하는 각각의 필터가 시큐리티 관련 작업을 진행한다. 모든 작업은 기능 단위로 분업하여 진행함으로 앞에서 한 작업을 뒤 필터가 알기 위한 저장소 개념이 필요하다. 예를들어, 인가 필터가 작업을 하려면 유저의 ROLE 정보가 필요한데, 앞단의 필터에서 유저에게 ROLE값을 부여한 결과를 인가 필터까지 공유해야 확인할 수 있다. ​ - 저장 : Authentication 객체 ​ ​ 해당하는 정보는 Authentication이라는 객체에 담긴다. (이 객체에 아이디, 로그인 여부, ROLE 데이터가 담긴다.) ​ Authentication 객체는 SecurityContext에 포함되어 관리되며 SecurityContext는 0개 이상 존재할 수 있다. 그리고 이 N개의 SecurityContext는 하나의 SecurityContextHolder에 의해서 관리된다. ​ - Authentication 객체 - Principal : 유저에 대한 정보 - Credentials : 증명 (비밀번호, 토큰) - Authorities : 유저의 권한(ROLE) 목록 ​ - 접근 SecurityContextHolder.getContext().getAuthentication().getAuthorities(); ​ SecurityContextHolder의 메소드는 static 으로 선언되기 때문에 어디서든 접근할 수 있다. ​ - SecurityContextHolder public class SecurityContextHolder { } ​ - 특이 사항 다수의 사용자인 멀티 쓰레드 환경에서 SecurityContextHolder를 통해 SecurityContext를 부여하는 관리 전략은 위임하여 다른 클래스에게 맡긴다. (사용자별로 다른 저장소를 제공해야 인증 정보가 겹치는 일이 발생하지 않는다.) 즉, SecurityContextHolder는 SecurityContext들을 관리하는 메소드를 제공하지만 실제로 등록, 초기화, 읽기와 같은 작업은 SecurityContextHolderStrategy 인터페이스를 활용한다. ​ - SecurityContextHolderStrategy 구현 종류 private static void initializeStrategy() { if (MODE_PRE_INITIALIZED.equals(strategyName)) { Assert.state(strategy != null, "When using " + MODE_PRE_INITIALIZED + ", setContextHolderStrategy must be called with the fully constructed strategy"); return; } if (!StringUtils.hasText(strategyName)) { // Set default strategyName = MODE_THREADLOCAL; } if (strategyName.equals(MODE_THREADLOCAL)) { strategy = new ThreadLocalSecurityContextHolderStrategy(); return; } if (strategyName.equals(MODE_INHERITABLETHREADLOCAL)) { strategy = new InheritableThreadLocalSecurityContextHolderStrategy(); return; } if (strategyName.equals(MODE_GLOBAL)) { strategy = new GlobalSecurityContextHolderStrategy(); return; } // Try to load a custom strategy try { Class clazz = Class.forName(strategyName); Constructor customStrategy = clazz.getConstructor(); strategy = (SecurityContextHolderStrategy) customStrategy.newInstance(); } catch (Exception ex) { ReflectionUtils.handleReflectionException(ex); } } ​ 기본적으로 threadlocal 방식을 사용한다. ​ ThreadLocal 방식에서 SecurityContext ​ - ThreadLocalSecurityContextHolderStrategy final class ThreadLocalSecurityContextHolderStrategy implements SecurityContextHolderStrategy { private static final ThreadLocal> contextHolder = new ThreadLocal<>(); } ​ - 접근 쓰레드별 SecurityContext 배분 ​ 톰캣 WAS는 멀티 쓰레드 방식으로 동작한다. 유저가 접속하면 유저에게 하나의 쓰레드를 할당한다. 각각의 유저는 동시에 시큐리티 로그인 로직을 사용할 수 있다. 이때 SecurityContextHolder의 필드에 선언된 SecurityContext를 호출하게 된다면 쓰레드간 공유하는 메모리의 code 영역에 데이터가 있기 때문에 정보가 덮어지는 현상이 발생한다고 생각할 수 있는데, threadLocal로 관리되기 때문에 쓰레드별 다른 구획을 나눠 제공한다. ​ ​ SecurityContext의 생명 주기 ​ Authentication 객체를 관리하는 SecurityContext는 사용자의 요청이 서버로 들어오면 생성되고, 처리가 끝난 후 응답되는 순간에 초기화 된다. ​ 요약 ​ - SecurityFilterChain의 각각의 필터에서 수행한 작업 내용이 전달되기 위해 요청(유저) 별로Authentication 객체를 할당하여 확인함. - Authentication 객체는 SecurityContextHolder의 SecurityContext가 관리함. - 멀티 쓰레드 환경에서 SecurityContext를 만들고 필드의 static 영역에 선언된 SecutiyContext를 다루는 전략은 기본적으로 threadLocal 전략을 이용함. ​ 어디에서 사용하는가? : 예시 ​ - 로그아웃 필터 : 로그아웃 로직을 수행하면서 SecurityContext의 Authentication 객체를 비움 ​ - 로그인 필터 : 인증을 완료한 뒤 유저 정보를 담은 Authentication 객체를 넣음 ​ 추가 ​ - SecurityContextHolder는 왜 Bean이 아닌 static으로 등록하는지? Util 클래스의 경우 static으로 선언하는게 암묵적인 룰. (static vs bean 으로 검색하면 비슷한 내용을 찾을 수 있습니다.) ​ - 스레드 safe한 함수의 local 변수 대신 왜 필드 변수를 사용하고 threadLocal을 사용하는지? 쓰레드 단위로 기억을 하는 경우 필드 변수를 사용함. ​ 이전 : 5. SecurityFilterChain 구조 다음 : 7. 필터 상속과 요청 전파 https://youtu.be/WoGzk5Iw64g 54, 스프링 시큐리티 내부 구조 > 7. 필터 상속과 요청 전파 SecurityFilterChain의 필터 ​ ​ SecurityFilterChain에 속한 각각의 필터를 알아보기 전에 필터의 전반적인 구조를 살펴보겠습니다. 각각의 필터의 조상은 모두 동일합니다. 필터의 기반이 되는 필터 클래스를 만들어두고 해당 클래스를 상속 받아 각 특성에 맞게 구현되어 있습니다. ​ 필터의 상속 ​ - 하나의 필터에 대한 모식도 ​ ​ - SecurityFilterChain에서 모식도 ​ ​ - 상속의 이점 ​ 중복되는 코드를 줄이고 각각의 구현부가 자신이 가지는 책임에 대해서만 작업을 수행하면 된다. ​ 가장 상단의 필터 클래스는 필터의 구조적인 역할만, 필터를 상속 받은 구현부는 구현부의 역할만 수행한다. ​ 예를 들어 로그인 필터의 경우 로그인의 종류가 아주 많기 때문에 기본적인 로그인 틀을 구현1로 구현하고 세부적인 로그인 방식을 구현2로 구현하여 등록한다. ​ GenericFilterBean과 OncePerRequestFilter ​ - GenericFilterBean public abstract class GenericFilterBean implements Filter, BeanNameAware, EnvironmentAware, EnvironmentCapable, ServletContextAware, InitializingBean, DisposableBean { } ​ - OncePerRequestFilter public abstract class OncePerRequestFilter extends GenericFilterBean { protected abstract void doFilterInternal( HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException; } ​ 서블릿 기반의 Filter 인터페이스 바로 아래에 내려가면 GenericFilterBean과 OncePerRequestFilter 두가지 추상 클래스가 존재하며 모든 필터는 두 추상 클래스를 기반으로 구현되어 있다. GenericFilterBean 추상 클래스는 자바 서블릿 필터 기반으로 구현되어 있으며 자바 서블릿 영역에서 스프링 영역에 접근할 수 있도록 작성되어 있다. OncePerRequestFilter는 GenericFilterBean을 기반으로 작성된 추상 클래스로 클라이언트의 한 번 요청에 대해 내부적으로 동일한 서블릿 필터를 여러번 거칠 경우 한 번 반응하도록 설계되어 있다. (다음 강에서 설명) 우리는 SecurityFilterChain에 등록할 필터를 GenericFilterBean 또는 OncePerRequestFilter 중 선택하여 구현하면 된다. ​ 필터의 형식 ​ - Filter 코드 public interface Filter { default void init(FilterConfig filterConfig) throws ServletException { } void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException; default void destroy() { } } ​ - 인터페이스 인터페이스로 3가지 메소드를 정의해 두었다. init(), doFilter(), destory() - init() 서블릿 컨테이너 실행시 필터를 생성하고 초기화할 때 사용하는 메소드 - doFilter() 요청에 대한 작업 수행 및 다음 필터를 호출하는 메소드 - destory() 서블릿 컨테이너 종료시 초기화하는 메소드 ​ filterChain에서 다음 필터 호출 ​ public class LogoutFilter extends GenericFilterBean { @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { doFilter((HttpServletRequest) request, (HttpServletResponse) response, chain); } private void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException { //처리할 로직 //System.out.println("before"); //다음 필터 호출 chain.doFilter(request, response); //요청이 돌아서 다시 현재 필터를 통과할 때 처리할 로직 //System.out.println("after"); } } ​ - GenericFilterBean과 OncePerRequestFilter의 로직 수행 메소드 - GenericFilterBean : doFilter() - OncePerRequestFilter : doFilterInternal() ​ 이전 : 6. SecurityContextHolder 다음 : 8. GenericFilterBean, OncePerRequestFilter https://youtu.be/u5pjHhTBUz0 55, 스프링 시큐리티 내부 구조 > 8. GenericFilterBean, OncePerRequestFilter GenericFilterBean vs OncePerRequestFilter ​ SecurityFilterChain에 담겨 있는 필터는 GenericFilterBean 기반으로 구현된 필터가 있고, GenericFilterBean을 상속한 OncePerRequestFilter 기반으로 구현된 필터도 존재한다. 두 방식의 차이점은 무엇일까? 기준은 클라이언트의 한 번의 요청에 대해서다. ​ GenericFilterBean은 내부적으로 동일한 필터를 여러 번 통과하더라도 통과한 수 만큼 내부 로직이 실행된다. OncePerRequestFilter는 내부적으로 동일한 필터를 여러 번 통과하더라도 첫 한 번만 내부 로직이 실행된다. ​ 대부분의 블로그가 잘못 적은 내용 ​ GenericFilterBean은 통과하기만 하면 내부 로직이 실행되기 때문에 크게 고려할 상황은 없다. 하지만 OncePerRequestFilter에 대해서 대부분의 블로그들은 잘못된 내용을 전달하고 있다. 주로 redirect(302 응답)을 주제로 OncePerRequestFilter가 한 번 동작된다고 말하는데 정확하게 틀린 내용이다. 302는 사용자에게 재요청을 보내라고 응답을 주기 때문에 사용자의 요청이 2번 보내지는 것과 동일하다. 즉 OncePerRequestFilter가 의미하는 동작을 이루기 위해서는 redirect 시에는 해당이 안되고 forward 상태만 해당 되는데 많은 블로그들은 302, redirect시 된다고 적혀 있다. ​ 각 상태에 대해서 어떻게 동작이 되는가 ​ - forward 상태 ​ ​ 한 번의 클라이언트 요청에 대해서 동일한 필터를 2번 탔지만 OncePerRequestFilter는 한 번 동작한다. ​ - redirect 상태 ​ ​ redirect는 다른 경로로 재 요청하라는 의미로 실제로 클라이언트가 2번 요청한 것으로 OncePerRequestFilter가 두 번 모두 실행된다. ​ 테스트 ​ - 확인을 위한 OncePerRequestFilter 작성 public class CustomOnceFilter extends OncePerRequestFilter { @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { System.out.println("CustomOnceFilter"); filterChain.doFilter(request, response); } } ​ - 확인을 위한 GenericFilterBean 작성 public class CustomGeneriFilter extends GenericFilterBean { @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { System.out.println("CustomGenericFilter"); chain.doFilter(request, response); } } ​ - SecurityConfig SecurityFilterChain에 등록 @Configuration @EnableWebSecurity public class SecurityConfig { @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http .authorizeHttpRequests((auth) -> auth.anyRequest().permitAll()); http .addFilterAfter(new CustomGeneriFilter(), LogoutFilter.class); http .addFilterAfter(new CustomOnceFilter(), LogoutFilter.class); return http.build(); } } ​ - 테스트 진행을 위한 컨트롤러 작성 @Controller public class MainController { @GetMapping("/testfilterbefore") public String before() { return "forward:/testfilterafter"; } @GetMapping("/testfilterafter") @ResponseBody public String after() { return "hihihi"; } } ​ 이전 : 7. 필터 상속과 요청 전파 다음 : 9. DisableEncodeUrlFilter https://youtu.be/7v6lsEmpeRg 56, 스프링 시큐리티 내부 구조 > 9. DisableEncodeUrlFilter https://docs.spring.io/spring-security/site/docs/current/api/org/springframework/security/web/session/DisableEncodeUrlFilter.html DisableEncodeUrlFilter (spring-security-docs 6.5.2 API) Package org.springframework.security.web.session Class DisableEncodeUrlFilter java.lang.Object org.springframework.web.filter.GenericFilterBean org.springframework.web.filter.OncePerRequestFilter org.springframework.security.web.session.DisableEncodeUrlFilter All Implemented Interfaces: jakarta.serv... docs.spring.io DisableEncodeUrlFilter 목적 ​ 이 필터는 DefaultSecurityFilterChain에 기본적으로 등록되는 필터로 가장 첫 번째에 위치한다. 필터가 등록되는 목적은 URL 파라미터에 세션 id가 인코딩되어 로그로 유출되는 것을 방지하기 위함이다. 커스텀 SecurityFilterChain을 생성해도 등록되며 비활성은 아래와 같이 세션 관리 설정을 disable 하면 된다. ​ http .sessionManagement((manage) -> manage.disable()); ​ DisableEncodeUrlFilter 클래스 ​ - DisableEncodeUrlFilter public class DisableEncodeUrlFilter extends OncePerRequestFilter { @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { filterChain.doFilter(request, new DisableEncodeUrlResponseWrapper(response)); } private static final class DisableEncodeUrlResponseWrapper extends HttpServletResponseWrapper { private DisableEncodeUrlResponseWrapper(HttpServletResponse response) { super(response); } @Override public String encodeRedirectURL(String url) { return url; } @Override public String encodeURL(String url) { return url; } } } ​ 간단하게 두 메소드 encodeRedirectURL(), encodeURL()를 오버라이딩하여 url 값만 리턴하도록 정의되어 있다. 그럼 기존의 response의 encodeRedirectURL(), encodeURL()은 어떤 구조를 가졌기에 세션 id가 파라미터로 노출될 수 있었는지 확인하자. ​ 기존 메소드 ​ HttpServletResponse 인터페이스를 구현한 org.apache.catalina.connector.Response 클래스에 정의되어 있는 encodeRedirectURL(), encodeURL() 메소드는 request.getSessionInternal().getInternal()을 통해 session 값을 꺼내어 인코딩하는 로직을 확인할 수 있다. ​ @Override public String encodeRedirectURL(String url) { if (isEncodeable(toAbsolute(url))) { return toEncoded(url, request.getSessionInternal().getIdInternal()); } else { return url; } } @Override public String encodeURL(String url) { String absolute; try { absolute = toAbsolute(url); } catch (IllegalArgumentException iae) { // Relative URL return url; } if (isEncodeable(absolute)) { // W3c spec clearly said if (url.equalsIgnoreCase("")) { url = absolute; } else if (url.equals(absolute) && !hasPath(url)) { url += '/'; } return toEncoded(url, request.getSessionInternal().getIdInternal()); } else { return url; } } ​ 이전 : 8. GenericFilterBean, OncePerRequestFilter 다음 : 10. WebAsyncManagerIntegrationFilter https://youtu.be/17GLK1ui1Gs 57, 스프링 시큐리티 내부 구조 > 10. WebAsyncManagerIntegrationFilter WebAsyncManagerIntegrationFilter 목적 ​ 이 필터는 DefaultSecurityFilterChain에 기본적으로 등록되는 필터로 두 번째에 위치한다. 필터가 등록되는 목적은 서블릿단에서 비동기 작업을 수행할 때 서블릿 입출력 쓰레드와 작업 쓰레드가 동일한 SecurityContextHolder의 SecurityContext 영역을 참조할 수 있도록 도와준다. 즉, SecurityContextHolder의 ThreadLocal 전략에 따라 동일한 쓰레드에서만 SecurityContext에 접근할 수 있는데, 비동기 방식의 경우 하나의 작업을 2개의 쓰레드로 수행하기 때문에 이 부분을 보완하기 위해 필터가 존재한다. 커스텀 SecurityFilterChain을 생성해도 등록된다. ​ Callable 사용시 쓰레드 ​ @GetMapping("/async") @ResponseBody public Callable asyncPage() { System.out.println("start" + SecurityContextHolder.getContext().getAuthentication().getName()); return () -> { Thread.sleep(4000); System.out.println("end" + SecurityContextHolder.getContext().getAuthentication().getName()); return "async"; }; } ​ 위와 같은 코드는 Callable<> 인터페이스로 감싼 아래 부분을 다른 쓰레드에서 수행하게 된다. ​ return () -> { Thread.sleep(4000); System.out.println("end" + SecurityContextHolder.getContext().getAuthentication().getName()); return "async"; }; ​ 각기 다른 쓰레드에서 수행하지만 ThreadLocal로 관리되는 SecurityContextHolder의 값은 WebAsyncManagerIntegrationFilter와 여타 클래스들을 통해 동일하게 가져올 수 있다. ​ 서블릿단에서 비동기 처리인데 어떻게 필터단에서 판단? ​ ​ 해당 문제를 처리하는 WebAsyncMagagerIntegrationFilter는 필터단에 존재하는데 어떻게 필터단을 통과하고 컨트롤러단에서 발생하는 쓰레드 이동 문제를 처리할 수 있는지 의문점이 생긴다. 그 이유는 WebAsyncManagerIntegrationFilter가 실제로 수행하는 작업과 Callable의 동작 방식에 관련이 있다. ​ WebAsyncManagerIntegrationFilter가 실제로 수행하는 작업 ​ WebAsyncMagerIntegrationFilter는 현재 쓰레드의 SecurityContext를 다룰 수 있는 SecurityContectCallableProcessingInterceptor를 WebAsyncManager에 등록만 진행한다. 이후 서블릿단에서 WebAsyncManager을 통해 새로운 쓰레드에 SecurityContext를 복제한다. ​ public final class WebAsyncManagerIntegrationFilter extends OncePerRequestFilter { private static final Object CALLABLE_INTERCEPTOR_KEY = new Object(); private SecurityContextHolderStrategy securityContextHolderStrategy = SecurityContextHolder .getContextHolderStrategy(); @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request); SecurityContextCallableProcessingInterceptor securityProcessingInterceptor = (SecurityContextCallableProcessingInterceptor) asyncManager .getCallableInterceptor(CALLABLE_INTERCEPTOR_KEY); if (securityProcessingInterceptor == null) { SecurityContextCallableProcessingInterceptor interceptor = new SecurityContextCallableProcessingInterceptor(); interceptor.setSecurityContextHolderStrategy(this.securityContextHolderStrategy); asyncManager.registerCallableInterceptor(CALLABLE_INTERCEPTOR_KEY, interceptor); } filterChain.doFilter(request, response); } public void setSecurityContextHolderStrategy(SecurityContextHolderStrategy securityContextHolderStrategy) { Assert.notNull(securityContextHolderStrategy, "securityContextHolderStrategy cannot be null"); this.securityContextHolderStrategy = securityContextHolderStrategy; } } ​ ​ Callable 동작 방식과 DispatcherServlet ​ 사용자의 요청은 필터단을 모두 거친 후 스프링 컨테이너에서 컨트롤러에 접근하게 된다. 이때 컨트롤러 바로 전에 DispatcherServlet이라는 서블릿이 존재하는데 사용자의 요청과 알맞은 컨트롤러를 찾는 역할을 수행한다. ​ @GetMapping("/async") @ResponseBody public Callable asyncPage() { System.out.println("start" + SecurityContextHolder.getContext().getAuthentication().getName()); return () -> { Thread.sleep(4000); System.out.println("end" + SecurityContextHolder.getContext().getAuthentication().getName()); return "async"; }; } ​ - Callable 수행 과정 1. DispatcherServlet에서 알맞은 Controller를 찾아서 요청 전달 2. Controller에서 요청 수행 후 Callable 부분을 DispatcherServlet으로 리턴 3. DispatcherServlet은 Callable 객체를 WebAsyncManager에게 전달 4. WebAsyncManager가 비동기 부분 새로운 쓰레드에서 수행 후 응답 ​ ​ WebAsyncManager는 WebAsyncManagerIntegrationFilter에 의해 기존 쓰레드가 참조하던 SecurityContext를 전달 받았기 때문에 Callable을 수행할 새로운 쓰레드에게 기존 SecurityContext를 전달할 수 있다. 따라서 쓰레드가 바뀌더라도 SecurityContext에서 동일한 값을 획득할 수 있다. ​ 기타 ​ 시큐리티 설정을 진행하지 않아도 Callable 사용시 알아서 잘 적용 됨. ​ 이전 : 9. DisableEncodeUrlFilter 다음 : 11. SecurityContextHolderFilter https://youtu.be/vGdQ-RJsVSY 58, 스프링 시큐리티 내부 구조 > 11. SecurityContextHolderFilter https://docs.spring.io/spring-security/site/docs/current/api/org/springframework/security/web/context/SecurityContextHolderFilter.html SecurityContextHolderFilter (spring-security-docs 6.5.2 API) Package org.springframework.security.web.context Class SecurityContextHolderFilter java.lang.Object org.springframework.web.filter.GenericFilterBean org.springframework.security.web.context.SecurityContextHolderFilter All Implemented Interfaces: jakarta.servlet.Filter , org.springframework.beans.fac... docs.spring.io SecurityContextHolderFilter 목적 ​ 이 필터는 DefaultSecurityFilterChain에 기본적으로 등록되는 필터로 세 번째에 위치한다. 필터가 등록되는 목적은 이전 요청을 통해 이미 인증한 사용자 정보를 현재 요청의 SecurityContextHolder의 SecurityContext에 할당하는 역할을 수행하고, 현재 요청이 끝나면 SecurityContext를 초기화 한다. ​ ​ 커스텀 SecurityFilterChain을 생성해도 등록되며 아래 구문을 통해 비활성화 시킬 수 있다. ​ @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http .securityContext((context) -> context.disable()); return http.build(); } ​ SecurityContextHolderFilter 클래스 ​ public class SecurityContextHolderFilter extends GenericFilterBean { } ​ - 기본 로직 이전 요청에서 사용자가 로그인을 했고 STATELESS 상태가 아니라면 서버의 세션(메모리) 또는 레디스와 같은 저장 매체에 유저의 정보가 있을 것이다. 해당 저장 매체로 부터 유저 정보를 가져올때 SecurityContextRepository라는 인터페이스의 loadDefferdContext() 메소드를 활용해서 불러온다. (만약 존재하지 않는 경우 빈 객체를 응답한다.) 이후 불러온 유저 정보를 SecurityContextHolder에 setDefferdContext() 메소드를 통해 저장하고 다음 필터로 넘긴다. 응답이 이루어지면 try의 finally 구문을 통해 SecurityContextHolder에 유저 정보를 제거한다. - 위임 ​ 저장 매체로 부터 유저 정보를 가져오는 부분은 SecurityContextRepository 인터페이스를 구현한 클래스에게 맡기고, 불러온 유저 정보도 6강에서 설명한 SecurityContextHolder에 설정한다. ​ SecurityContextRepository 인터페이스와 그 구현들 ​ 서버 세션이나 레디스와 같은 저장 매체로 부터 유저 정보를 불러오는 SecurityContextRepository가 인터페이스로 정의된 이유는 세션, 레디스, 기타 매체별로 구현 방식이 다르기 때문이다. - HttpSessionSecurityContextRepository : 서버 세션 기반 구현체 - NullSecurityContextRepository : 아무 작업을 하지 않을때 (JWT를 사용해서 STATELESS 관리시) - RequestAttributeSecurityContextRepository : HTTP request 저장 기반 구현체 - 기타 : 직접 구현해서 사용하면 된다. ​ https://docs.spring.io/spring-security/reference/servlet/authentication/persistence.html#securitycontextrepository Persisting Authentication :: Spring Security Spring Security / Servlet Applications / Authentication / Persistence Persisting Authentication The first time a user requests a protected resource, they are prompted for credentials . One of the most common ways to prompt for credentials is to redirect the user to a log in page . A summarized HTTP ... docs.spring.io ​ 기본 구현체와 커스텀 등록 방법 ​ 기본 구현체는 HttpSessionSecurityContextRepository로 설정되어 있으며 SecurityFilterChain Bean을 통해 커스텀 등록할 수 있다. ​ @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http .securityContext((context) -> context .securityContextRepository(new RequestAttributeSecurityContextRepository())); return http.build(); } ​ SecurityContextPersistenceFilter와 SecurityContextHolderFilter의 차이 ​ 자료를 찾다보면 비슷한 역할을 수행하는 SecurityContextPersistenceFilter도 확인할 수 있다. SecurityContextHolderFilter가 SecurityContextPersistenceFilter의 후속으로 시큐리티 5.8 버전 부터 내부 구현이 변경되면서 기존 클래스는 deprecated 되었다. - 변경 부분 구현들이 많이 변경되었지만 기능은 거의 동일하다. 다만 주의 깊게 볼 부분은 try문에서 finally에 존재하는 doFilter 응답 부분에 대해서 변경점 저장 로직이다. - SecurityContextPersistenceFilter finally { SecurityContext contextAfterChainExecution = this.securityContextHolderStrategy.getContext(); // Crucial removal of SecurityContextHolder contents before anything else. this.securityContextHolderStrategy.clearContext(); this.repo.saveContext(contextAfterChainExecution, holder.getRequest(), holder.getResponse()); request.removeAttribute(FILTER_APPLIED); this.logger.debug("Cleared SecurityContextHolder to complete request"); } ​ - SecurityContextHolderFilter finally { this.securityContextHolderStrategy.clearContext(); request.removeAttribute(FILTER_APPLIED); } ​ - 쟁점 이전 클래스는 SecurityContext가 변경되면 변경된 부분을 세션이나 레디스와 같은 저장소에 SecurityContextRepository로 저장했지만 현재 클래스는 변경점을 저장하지 않는다. ​ 이전 : 10. WebAsyncManagerIntegrationFilter 다음 : 12. HeaderWriterFilter https://youtu.be/0s48RBmQWeg 59, 스프링 시큐리티 내부 구조 > 12. HeaderWriterFilter https://docs.spring.io/spring-security/site/docs/current/api/org/springframework/security/web/header/HeaderWriterFilter.html HeaderWriterFilter (spring-security-docs 6.5.2 API) Package org.springframework.security.web.header Class HeaderWriterFilter java.lang.Object org.springframework.web.filter.GenericFilterBean org.springframework.web.filter.OncePerRequestFilter org.springframework.security.web.header.HeaderWriterFilter All Implemented Interfaces: jakarta.servlet.Filter... docs.spring.io HeaderWriterFilter 목적 ​ 이 필터는 DefaultSecurityFilterChain에 기본적으로 등록되는 필터로 네 번째에 위치한다. 필터가 등록되는 목적은 HTTP 응답 헤더에 사용자 보호를 위한 시큐리티 관련 헤더를 추가하는 필터이다. 커스텀 SecurityFilterChain을 생성해도 등록되며 아래 구문을 통해 비활성화 시킬 수 있다. ​ http .headers((headers) -> headers.disable()); HeaderWriterFilter 클래스 ​ public class HeaderWriterFilter extends OncePerRequestFilter { } ​ 응답 헤더에 시큐리티 관련 헤더를 추가하는 시점은 설정에 따라 2종류로 현재 필터를 통과하는 순간 또는 서블릿에서 응답을 보내며 다시 이 필터를 통과하는 시점으로 나뉘며, 기본값은 두 번째다. ​ 헤더 목록 ​ - 필터 적용 후 응답 헤더 ​ ​ - 필터 미적용 후 응답 헤더 ​ ​ - HeaderWriterFilter로 디폴트로 추가되는 헤더 ​ Key 설명 X-Content-Type-Options 컨텐츠 스니핑을 막기 위해 nosniff value를 할당해 서버에서 응답하는 Content-Type과 다른 타입일 경우 읽지 못하도록 설정 X-XSS-Protection XSS 공격 감지시 로딩 금지 (0은 비활성화) Cache-Control 이전에 받았던 데이터와 현재 보낼 데이터가 같다면 로딩에 대한 결정 여부 Pragma HTTP/1.0 방식에서 사용하던 Cache-Control Expires 서버에서 보낼 데이터를 브라우저에서 캐싱할 시간 X-Frame-Options 브라우저가 응답 데이터를 iframe, frame, embed, object 태그에서 로딩해도 되는 여부 ​ 커스텀 ​ https://docs.spring.io/spring-security/reference/servlet/exploits/headers.html Security HTTP Response Headers :: Spring Security Spring Security / Servlet Applications / Protection Against Exploits / Security HTTP Response Headers Security HTTP Response Headers You can use Security HTTP Response Headers to increase the security of web applications. This section is dedicated to servlet-based support for Security HTTP Response ... docs.spring.io ​ - frame options ​ http .headers((headers) -> headers .frameOptions(frameOptions -> frameOptions.sameOrigin()) .cacheControl(cache -> cache.disable()) .contentTypeOptions(contentTypeOptions -> contentTypeOptions.disable()) ); ​ 이전 : 11. SecurityContextHolderFilter 다음 : 13. CorsFilter https://youtu.be/BGLz0tj_pvQ 60, 스프링 시큐리티 내부 구조 > 13. CorsFilter 들어가며 ​ API 서버를 구축하여 프론트와 백엔드의 오리진이 다르면 발생하는 CORS 문제를 해결해야 한다. ​ 토이나 실무 모두 문제 해결을 위해 등록되는 SecurityFilterChain의 CorsConfigurationSource 값을 설정하는 것이 더 중요하기 때문에 CorsFilter에 대해서 자세하게 볼 필요는 없다. 하지만 CorsFilter를 한 번쯤 살펴보는 것이 모르는 것보단 좋을 거 같다. (그렇게 중요하진 않지만 잡지식..) ​ https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/filter/CorsFilter.html CorsFilter (Spring Framework 6.2.9 API) Package org.springframework.web.filter Class CorsFilter java.lang.Object org.springframework.web.filter.GenericFilterBean org.springframework.web.filter.OncePerRequestFilter org.springframework.web.filter.CorsFilter All Implemented Interfaces: Filter , Aware , BeanNameAware , DisposableBean , Initia... docs.spring.io CorsFilter 목적 ​ 이 필터는 DefaultSecurityFilterChain에 기본적으로 등록되는 필터로 다섯 번째에 위치한다. 필터가 등록되는 목적은 CorsConfigurationSource에 설정한 값에 따라 필터단에서 응답 헤더를 설정하는 필터이다. 커스텀 SecurityFilterChain을 생성해도 등록되며 아래 구문을 통해 비활성화 시킬 수 있다. ​ http .cors((cors) -> cors.disable()); ​ ​ CorsConfigurationSource 설정 방법 ​ https://docs.spring.io/spring-security/reference/servlet/integrations/cors.html CORS :: Spring Security Spring Security / Servlet Applications / Integrations / Spring’s CORS Support CORS Spring Framework provides first class support for CORS . CORS must be processed before Spring Security, because the pre-flight request does not contain any cookies (that is, the JSESSIONID ). If the request does not c... docs.spring.io ​ @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http .cors(corsCustomizer -> corsCustomizer.configurationSource(new CorsConfigurationSource() { @Override public CorsConfiguration getCorsConfiguration(HttpServletRequest request) { CorsConfiguration configuration = new CorsConfiguration(); configuration.setAllowedOrigins(Collections.singletonList("http://localhost:3000")); configuration.setAllowedMethods(Collections.singletonList("*")); configuration.setAllowCredentials(true); configuration.setAllowedHeaders(Collections.singletonList("*")); configuration.setMaxAge(3600L); configuration.setExposedHeaders(Collections.singletonList("Set-Cookie")); configuration.setExposedHeaders(Collections.singletonList("Authorization")); return configuration; } })); return http.build(); } ​ https://youtu.be/Xiv5KFoEW4w?si=lkW8QRCbillRNnUl ​ https://youtu.be/MGkYFwdabeM?si=Qs4odhBBxL6-Y6fp ​ 이전 : 12. HeaderWriterFilter 다음 : 14. CsrfFilter https://youtu.be/ht8QToxb6JU 61, 스프링 시큐리티 내부 구조 > 14. CsrfFilter https://docs.spring.io/spring-security/site/docs/current/api/org/springframework/security/web/csrf/CsrfFilter.html CsrfFilter (spring-security-docs 6.5.2 API) Package org.springframework.security.web.csrf Class CsrfFilter java.lang.Object org.springframework.web.filter.GenericFilterBean org.springframework.web.filter.OncePerRequestFilter org.springframework.security.web.csrf.CsrfFilter All Implemented Interfaces: jakarta.servlet.Filter , org.springframewo... docs.spring.io CSRF 공격 ​ 사용자의 의지와 무관하게 해커가 강제로 사용자의 브라우저를 통해 서버측으로 특정한 요청을 보내도록 공격하는 방법이다. ​ CsrfFilter 목적 ​ 이 필터는 DefaultSecurityFilterChain에 기본적으로 등록되는 필터로 여섯 번째에 위치한다. 이 필터가 등록되는 목적은 CSRF 공격 방어를 위해 HTTP 메소드 중 GET, HEAD, TRACE, OPTIONS 메소드를 제외한 요청에 대해서 검증을 진행한다. 스프링 시큐리티의 CSRF 검증 방식은 토큰 방식이며 요청시 토큰을 서버 저장소에 저장 후 클라이언트에게도 전송하며, 그 후 해당하는 요청에 대해서 서버에 저장된 토큰과 비교 검증을 진행한다. ​ ​ 커스텀 SecurityFilterChain을 생성해도 등록되며 아래 구문을 통해 비활성화 시킬 수 있다. ​ http .csrf((csrf) -> csrf.disable()); ​ CsrfFilter 클래스 ​ public final class CsrfFilter extends OncePerRequestFilter { } ​ - 주요 로직 : doFilterInternal protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { // 토큰을 토큰 저장소로 부터 불러옴 DeferredCsrfToken deferredCsrfToken = this.tokenRepository.loadDeferredToken(request, response); // 다음 요청을 위해 request에 추가 request.setAttribute(DeferredCsrfToken.class.getName(), deferredCsrfToken); this.requestHandler.handle(request, response, deferredCsrfToken::get); // HTTP 메소드 확인 후 CSRF 검증이 필요 없는 메소드면 다음 필터로 넘김 if (!this.requireCsrfProtectionMatcher.matches(request)) { if (this.logger.isTraceEnabled()) { this.logger.trace("Did not protect against CSRF since request did not match " + this.requireCsrfProtectionMatcher); } filterChain.doFilter(request, response); return; } // 서버 저장 토큰 CsrfToken csrfToken = deferredCsrfToken.get(); // 클라이언트에서 온 토큰 String actualToken = this.requestHandler.resolveCsrfTokenValue(request, csrfToken); // 클라이언트로 부터 온 토큰과 서버 저장소의 토큰을 비교 검증 if (!equalsConstantTime(csrfToken.getToken(), actualToken)) { boolean missingToken = deferredCsrfToken.isGenerated(); this.logger .debug(LogMessage.of(() -> "Invalid CSRF token found for " + UrlUtils.buildFullRequestUrl(request))); AccessDeniedException exception = (!missingToken) ? new InvalidCsrfTokenException(csrfToken, actualToken) : new MissingCsrfTokenException(actualToken); this.accessDeniedHandler.handle(request, response, exception); return; } // 다음 필터로 넘김 filterChain.doFilter(request, response); } ​ CsrfTokenRepository ​ CSRF 토큰의 생성 및 관리는 CsrfTokenRepository라는 인터페이스를 정의하고 그것을 구현한 클래스에게 위임 시킨다. ​ https://docs.spring.io/spring-security/reference/servlet/exploits/csrf.html#csrf-token-repository Cross Site Request Forgery (CSRF) :: Spring Security Spring Security / Servlet Applications / Protection Against Exploits / Cross Site Request Forgery (CSRF) Cross Site Request Forgery (CSRF) In an application where end users can log in , it is important to consider how to protect against Cross Site Request Forgery (CSRF) . Spring Security protects ag... docs.spring.io ​ - HttpSessionCsrfTokenRepository : 서버 세션에 토큰을 저장 관리함 (기본값) - CookieCsrfTokenRepository : 쿠키에 토큰을 저장 관리함 - 직접 구현 가능 ​ CSRF 값 설정 ​ - 토큰 저장소 설정 http .csrf((csrf) -> csrf.csrfTokenRepository(new HttpSessionCsrfTokenRepository())); ​ CSRF 토큰 클라이언트측으로 발급 ​ 기본 동작은 SSR 세션 방식으로 설정되어 있다. (STATELESS REST API에서는 사용할 일이 거의 없기 때문) Controller단에서 VIEW단 응답시 HTML form 영역에 서버에 저장되어 있는 _csrf 토큰 값을 넣어주면 된다. https://youtu.be/l8xjecnAzMw?si=q08lCjggYgYTAFIO ​ CSRF Referer ​ STATELESS한 API 서버를 구축하게 된다면 JSESSION에 대한 서버 세션이 상태를 가지지 않기 때문에 CSRF 공격 위험 자체가 없다. 따라서 csrf 설정을 disable하는 것이 대부분의 구현이다. 하지만 JWT를 쿠키에 저장할 경우 CSRF 공격의 위험이 있을 수 있기 때문에 활성화하는 것이 좋다. 다만 CSRF 토큰을 발급할 VIEW 페이지와 같은 로직이 없기 때문에 토큰 방식이 아닌 Referer 방식을 사용한다. 이 방식은 HTTP Referer 헤더를 통해 요청의 출발점, 이전 URL등을 검증한다. ​ 이전 : 13. CorsFilter 다음 : 15. LogoutFilter https://youtu.be/IHOYDsrTp7g 62, 스프링 시큐리티 내부 구조 > 15. LogoutFilter https://docs.spring.io/spring-security/site/docs/current/api/org/springframework/security/web/authentication/logout/LogoutFilter.html LogoutFilter (spring-security-docs 6.5.2 API) Package org.springframework.security.web.authentication.logout Class LogoutFilter java.lang.Object org.springframework.web.filter.GenericFilterBean org.springframework.security.web.authentication.logout.LogoutFilter All Implemented Interfaces: jakarta.servlet.Filter , org.springframework.beans.facto... docs.spring.io LogoutFilter 목적 ​ 이 필터는 DefaultSecurityFilterChain에 기본적으로 등록되는 필터로 일곱 번째에 위치한다. 이 필터가 등록되는 목적은 인증 후 생성되는 사용자 식별 정보에 대해 로그아웃 핸들러를 돌며 로그아웃을 수행하는 필터이다. 기본적으로 세션 방식에 대한 로그아웃 설정이 되어 있기 때문에 JWT 방식이나 추가할 로직이 많을 경우 커스텀해야 한다. ​ https://docs.spring.io/spring-security/reference/servlet/authentication/logout.html Handling Logouts :: Spring Security Spring Security / Servlet Applications / Authentication / Logout Handling Logouts In an application where end users can login , they should also be able to logout. By default, Spring Security stands up a /logout endpoint, so no additional code is necessary. The rest of this section covers a number o... docs.spring.io ​ 커스텀 SecurityFilterChain을 생성해도 등록되며 아래 구문을 통해 비활성화 시킬 수 있다. ​ http .logout((logout) -> logout.disable()); ​ LogoutFilter 클래스 ​ public class LogoutFilter extends GenericFilterBean { } ​ - 주요 로직 : doFilter private void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException { // 로그아웃 요청인지 확인 if (requiresLogout(request, response)) { Authentication auth = this.securityContextHolderStrategy.getContext().getAuthentication(); if (this.logger.isDebugEnabled()) { this.logger.debug(LogMessage.format("Logging out [%s]", auth)); } // 등록된 로그아웃 핸들러들을 동작 this.handler.logout(request, response, auth); // 로그아웃 핸들러 수행 후 성공 핸들러 동작 this.logoutSuccessHandler.onLogoutSuccess(request, response, auth); // 종료 return; } // 로그아웃 요청이 아니면 다음 필터로 chain.doFilter(request, response); } ​ handler는? ​ CompositeLogoutHandler 클래스에서 등록되어 있는 모든 로그아웃 핸들러는 순회하면서 로그아웃을 수행한다. ​ public final class CompositeLogoutHandler implements LogoutHandler { private final List logoutHandlers; public CompositeLogoutHandler(LogoutHandler... logoutHandlers) { Assert.notEmpty(logoutHandlers, "LogoutHandlers are required"); this.logoutHandlers = Arrays.asList(logoutHandlers); } public CompositeLogoutHandler(List logoutHandlers) { Assert.notEmpty(logoutHandlers, "LogoutHandlers are required"); this.logoutHandlers = logoutHandlers; } @Override public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) { for (LogoutHandler handler : this.logoutHandlers) { handler.logout(request, response, authentication); } } } ​ Logout 핸들러 ​ public interface LogoutHandler { void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication); } ​ 로그아웃 핸들러들은 위와 같은 LogoutHandler 인터페이스를 구현한 구현 클래스들로 이루어져 있으며 커스텀 핸들러 생성시에도 위 인터페이스 기반으로 작성해야 한다. - 기본 제공 핸들러 - SecurityContextLogoutHandler : SecurityContextHolder에 존재하는 SecurityContext 초기화 - CookieClearingLogoutHandler : SecurityFilterChain의 logout 메소드에서 지정한 쿠키 삭제 - HeaderWriterLogoutHandler : 클라이언트에게 반환될 헤더 조작 - LogoutSuccessEventPublishingLogoutHandler : 로그아웃 성공 후 특정 이벤트 실행 ​ - 등록되어 있는 핸들러 ​ ​ 커스텀 Logout 핸들러 ​ 기본적으로 제공하지만 등록되어 있지 않거나, 커스텀해서 만든 핸들러를 등록하는 방법은 아래 메소드를 활용한다. ​ CookieClearingLogoutHandler cookies = new CookieClearingLogoutHandler("our-custom-cookie"); http .logout((logout) -> logout.addLogoutHandler(cookies)); ​ Logout 성공 핸들러 ​ 로그아웃이 성공한 뒤 URL 리디렉션과 같은 특정 작업을 수행하기 위한 핸들러로 위의 Logout 핸들러와 다르다. ​ public interface LogoutSuccessHandler { void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException; } ​ 이전 : 14. CsrfFilter 다음 : 16. UsernamePasswordAuthenticationFilter https://youtu.be/DCnra1pxRw0 63, 스프링 시큐리티 내부 구조 > 16. UsernamePasswordAuthenticationFilter https://docs.spring.io/spring-security/site/docs/current/api/org/springframework/security/web/authentication/UsernamePasswordAuthenticationFilter.html UsernamePasswordAuthenticationFilter (spring-security-docs 6.5.2 API) Package org.springframework.security.web.authentication Class UsernamePasswordAuthenticationFilter java.lang.Object org.springframework.web.filter.GenericFilterBean org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter org.springframework.security.web.authentication.... docs.spring.io UsernamePasswordAuthenticationFilter 목적 ​ 이 필터는 DefaultSecurityFilterChain에 기본적으로 등록되는 필터로 여덟 번째에 위치한다. 이 필터가 등록되는 목적은 POST : “/login” 경로에서 Form 기반 인증을 진행할 수 있도록 multipart/form-data 형태의 username/password 데이터를 받아 인증 클래스에게 값을 넘겨주는 역할을 수행한다. 커스텀 SecurityFilterChain을 생성하면 자동 등록이 안되기 때문에 아래 구문을 통해서 필터를 활성화시켜야 한다. ​ http .formLogin(Customizer.withDefaults()); UsernamePaswordAuthenticationFilter 클래스 ​ public class UsernamePasswordAuthenticationFilter extends AbstractAuthenticationProcessingFilter { } ​ - doFilter가 없다 doFilter는? 앞서 봐왔던 필터들과 다르게 doFilter 메소드가 보이지 않는다 어디 있을까? 바로 부모 클래스인 AbstractAuthenticationProcessingFilter 클래스에 존재한다. - 왜? UsernamePasswordAuthenticationFilter는 Form 로그인 방식에 대한 필터이다. Form 데이터를 받은 후 인증 과정은 어떻게 될까? - 과정 사용자에게 데이터를 받아 인증 → 인증 결과 → 성공/실패 핸들 - 사용자가 보낸 데이터 방식이 다르다고해서 위 과정이 변할까? username/password를 Form, JSON 방식으로 보낸다고해서 위 과정이 변할까? 아니다. 따라서 위 과정에 대한 추상 클래스인 AbstractAuthenticationProcessingFilter를 정의하고 각각의 방식에 따라 필터를 구현해서 사용한다. - 즉 모식화 시키면 ​ ​ AbstractAuthenticationProcessingFilter ​ public abstract class AbstractAuthenticationProcessingFilter extends GenericFilterBean implements ApplicationEventPublisherAware, MessageSourceAware { } ​ - doFilter : 주요 로직 private void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException { // 로그인 경로 요청인지 확인 if (!requiresAuthentication(request, response)) { chain.doFilter(request, response); return; } // 로그인 과정 시도 try { // 사용자로 부터 데이터를 받아 상황에 맞는 인증을 진행 (이 부분을 구현) Authentication authenticationResult = attemptAuthentication(request, response); if (authenticationResult == null) { return; } // 인증 결과가 존재하면 세션 전략에 따라 SecurityContext에 저장 this.sessionStrategy.onAuthentication(authenticationResult, request, response); // 아래 값이 설정되어 있으면 다음 필터로 넘김 if (this.continueChainBeforeSuccessfulAuthentication) { chain.doFilter(request, response); } // 로그인 성공 핸들러 successfulAuthentication(request, response, chain, authenticationResult); } // 로그인 실패 핸들러 catch (InternalAuthenticationServiceException failed) { this.logger.error("An internal error occurred while trying to authenticate the user.", failed); unsuccessfulAuthentication(request, response, failed); } catch (AuthenticationException ex) { unsuccessfulAuthentication(request, response, ex); } } ​ - attemptAuthentication 추상 메소드 public abstract Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException; ​ 위와 같이 데이터를 받아 인증을 진행하는 부분을 추상화하여 상황에 따라 구현할 수 있도록 만들어 두었다. - AbstractAuthenticationProcessingFilter 추상 클래스 - UsernamePasswordAuthenticationFilter - OAuth2LoginAuthenticationFilter - Saml2WebSsoAuthenticationFilter - CasAuthenticationFilter ​ UsernamePasswordAuthenticationFilter에서 attempAuthentication() 메소드 ​ @Override public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException { // 로그인 경로 요청인지 확인 if (this.postOnly && !request.getMethod().equals("POST")) { throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod()); } // 요청으로부터 multipart/form-data로 전송되는 username, password 획득 String username = obtainUsername(request); username = (username != null) ? username.trim() : ""; String password = obtainPassword(request); password = (password != null) ? password : ""; // 인증을 위해 위 데이터를 인증 토큰에 넣음 UsernamePasswordAuthenticationToken authRequest = UsernamePasswordAuthenticationToken.unauthenticated(username, password); // Allow subclasses to set the "details" property setDetails(request, authRequest); // username/password 기반 인증을 진행하는 AuthenticationManager에게 인증을 요청 후 응답 return this.getAuthenticationManager().authenticate(authRequest); } ​ 로그인이 수행되는 과정 ​ 위 attemptAuthentication 메소드에서 유저가 보낸 정보를 받아 AuthenticationManager에게 넘기는데 해당 클래스들은 어떻게 구성되어 있고 어떤 과정을 거쳐서 로그인이 수행될까? username/password 기반으로 국한되어 살펴보면 아래와 같다. ​ ​ 기타 ​ - AuthenticationManager 인터페이스 AuthenticationManager 스프링 시큐리티 공식 API 문서 - ProviderManager 구현 ProviderManager 스프링 시큐리티 공식 API 문서 - AuthenticationProvider 인터페이스 AuthenticationProvider 스프링 시큐리티 공식 API 문서 - DaoAuthenticationProvider 구현 DaoAuthenticationProvider 스프링 시큐리티 공식 API 문서 이전 : 15. LogoutFilter 다음 : 17. DefaultLoginPageGenerationFilter https://youtu.be/DCnra1pxRw0 64, 스프링 시큐리티 내부 구조 > 17. DefaultLoginPageGeneratingFilter https://docs.spring.io/spring-security/site/docs/current/api/org/springframework/security/web/authentication/ui/DefaultLoginPageGeneratingFilter.html DefaultLoginPageGeneratingFilter (spring-security-docs 6.5.2 API) Package org.springframework.security.web.authentication.ui Class DefaultLoginPageGeneratingFilter java.lang.Object org.springframework.web.filter.GenericFilterBean org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter All Implemented Interfaces: jakarta.servlet.Filter ,... docs.spring.io DefaultLoginPageGeneratingFilter 목적 ​ 이 필터는 DefaultSecurityFilterChain에 기본적으로 등록되는 필터로 아홉 번째에 위치한다. 이 필터가 등록되는 목적은 로그인 설정에 대해 GET : “/login” 경로에 기본 로그인 페이지를 응답하는 역할을 수행한다. 이 필터는 여러 로그인 설정에 의존되며 가장 많이 사용하는 formLogin에서는 커스텀 SecurityFilterChain 등록시 아래와 같은 설정을 통해 사용할 수 있으며, 커스텀 로그인 페이지를 사용할 경우 제외된다. ​ // 기본 사용 http .formLogin(Customizer.withDefaults()); // 커스텀 하더라도 아래와 같이 loginPage() 메소드를 다루지 않으면 기본 로그인 페이지 활성 http .formLogin((login) -> login.loginPage("/커스텀경로")); ​ DefaultLoginPageGeneratingFilter 클래스 ​ public class DefaultLoginPageGeneratingFilter extends GenericFilterBean { } ​ - 주요 로직 : doFilter private void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException { // Error 파라미터가 있는 경우 boolean loginError = isErrorPage(request); // 로그아웃 성공시 boolean logoutSuccess = isLogoutSuccess(request); // 조건에 맞으면 로그인 페이지 발생 로직 실행 if (isLoginUrlRequest(request) || loginError || logoutSuccess) { // 로그인 페이지 생성 String loginPageHtml = generateLoginPageHtml(request, loginError, logoutSuccess); // 헤더 값 설정 및 바디 추가 response.setContentType("text/html;charset=UTF-8"); response.setContentLength(loginPageHtml.getBytes(StandardCharsets.UTF_8).length); response.getWriter().write(loginPageHtml); return; } // 조건이 아닌 경우 다음 필터 실행 chain.doFilter(request, response); } ​ - 로그인 설정에 따른 활성화 - form 로그인 - oauth2 로그인 - saml2 로그인 ​ form 로그인 페이지 ​ 기본 설정은 GET : “/login” 경로이다. ​ ​ 왜? 필터단에서 페이지를 응답하는가? ​ 컨트롤러와 같은 프레젠테이션 레이어가 아닌 필터단에서 VIEW를 응답하는 이유는 시큐리티 의존성의 한계 때문이다. ​ 시큐리티 의존성에 의해서 컨트롤러에 디폴트 페이지가 존재한다면 커스텀할 컨트롤러가 디폴트 컨트롤러를 유의하면서 구현하기 쉽지 않기 때문에 필터단에서 구현되어 있다. ​ 이전 : 16. UsernamePasswordAuthenticationFilter 다음 : 18. DefaultLogoutPageGeneratingFilter https://youtu.be/VGAY9ixWn2w 65, 스프링 시큐리티 내부 구조 > 18. DefaultLogoutPageGeneratingFilter https://docs.spring.io/spring-security/site/docs/current/api/org/springframework/security/web/authentication/ui/DefaultLogoutPageGeneratingFilter.html DefaultLogoutPageGeneratingFilter (spring-security-docs 6.5.2 API) Package org.springframework.security.web.authentication.ui Class DefaultLogoutPageGeneratingFilter java.lang.Object org.springframework.web.filter.GenericFilterBean org.springframework.web.filter.OncePerRequestFilter org.springframework.security.web.authentication.ui.DefaultLogoutPageGeneratingFilte... docs.spring.io DefaultLogoutPageGeneratingFilter ​ 이 필터는 DefaultSecurityFilterChain에 기본적으로 등록되는 필터로 열 번째에 위치한다. 이 필터가 등록되는 목적은 GET : “/logout” 경로에 대해 기본 로그아웃 페이지를 응답하는 역할을 수행한다. 이 필터는 여러 로그인 설정에 의존되며 가장 많이 사용하는 formLogin에서는 커스텀 SecurityFilterChain 등록시 아래와 같은 설정을 통해 사용할 수 있다. ​ // 기본 사용 http .formLogin(Customizer.withDefaults()); ​ DefaultLogoutPageGeneratingFilter 클래스 ​ public class DefaultLogoutPageGeneratingFilter extends OncePerRequestFilter { } ​ - 주요 로직 : doFilter​ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { if (this.matcher.matches(request)) { renderLogout(request, response); } else { if (logger.isTraceEnabled()) { logger.trace(LogMessage.format("Did not render default logout page since request did not match [%s]", this.matcher)); } filterChain.doFilter(request, response); } } ​ 로그아웃 페이지 ​ 기본 설정은 GET : “/logout” 경로이다. ​ ​ 기타 : 성능을 올리기 위한 StringBuilder의 사용 모습 ​ private void renderLogout(HttpServletRequest request, HttpServletResponse response) throws IOException { StringBuilder sb = new StringBuilder(); sb.append("\n"); sb.append("\n"); sb.append(" \n"); sb.append(" \n"); sb.append(" \n"); sb.append(" \n"); sb.append(" \n"); sb.append(" Confirm Log Out?\n"); sb.append(" \n"); sb.append(" \n"); sb.append(" \n"); sb.append(" \n"); sb.append("
\n"); sb.append("
\n"); sb.append(" \n"); sb.append(renderHiddenInputs(request) + " \n"); sb.append("
\n"); sb.append("
\n"); sb.append(" \n"); sb.append(""); response.setContentType("text/html;charset=UTF-8"); response.getWriter().write(sb.toString()); } ​ 이전 : 17. DefaultLoginPageGeneratingFilter 다음 : 19. BasicAuthenticationFilter https://youtu.be/-gh0hlNbnf4 66, 스프링 시큐리티 내부 구조 > 19. BasicAuthenticationFilter https://docs.spring.io/spring-security/site/docs/current/api/org/springframework/security/web/authentication/www/BasicAuthenticationFilter.html BasicAuthenticationFilter (spring-security-docs 6.5.2 API) Package org.springframework.security.web.authentication.www Class BasicAuthenticationFilter java.lang.Object org.springframework.web.filter.GenericFilterBean org.springframework.web.filter.OncePerRequestFilter org.springframework.security.web.authentication.www.BasicAuthenticationFilter All Implemen... docs.spring.io BasicAuthenticationFilter 목적 ​ 이 필터는 DefaultSecurityFilterChain에 기본적으로 등록되는 필터로 열한 번째에 위치한다. 이 필터가 등록되는 목적은 Basic 기반의 인증을 수행하기 위해 등록된다. 커스텀 SecurityFilterChain을 생성하면 자동 등록이 안되기 때문에 아래 구문을 통해서 필터를 활성화시켜야 한다. ​ http .httpBasic(Customizer.withDefaults()); Basic 인증이란? ​ Basic 인증을 자세하게 설명하기 위해 Form 인증 방식과 비교하는 것이 괜찮을거 같다. Form 인증 방식은 Form 태그에 username/password를 입력 후 브라우저에서 서버로 전송하면 서버는 상태에 알맞은 세션 또는 JWT를 생성하여 사용자를 기억할 수 있도록 한다. Basic 인증 방식은 브라우저에서 제공하는 입력기에 username/password를 입력하면 브라우저가 매 요청시 BASE64로 인코딩하여 Authorization 헤더에 넣어서 전송한다. 서버는 요청에 대해 username/password만 확인 후 사용자를 기억하지 않기 때문에 매 요청시 Authorization 헤더가 요구된다. 하지만 스프링 시큐리티의 Basic 인증 로직은 매번 재인증을 요구하는 것이 아닌 세션에 값을 저장해서 유저를 기억한다. (하지만 Authorization 헤더는 필요하다.) ​ - 요청 형식 Authorization: Basic BASE64로인코딩한usernamepassword값 ​ BasicAuthenticationFilter 클래스 ​ public class BasicAuthenticationFilter extends OncePerRequestFilter { } ​ - 주요 로직 : doFilterInternal protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException { try { // HTTP Authorization 헤더에서 값을 꺼냄 Authentication authRequest = this.authenticationConverter.convert(request); if (authRequest == null) { this.logger.trace("Did not process authentication request since failed to find " + "username and password in Basic Authorization header"); chain.doFilter(request, response); return; } // username 값을 가져옴 String username = authRequest.getName(); this.logger.trace(LogMessage.format("Found username '%s' in Basic Authorization header", username)); // Security Context에 해당 username이 이미 존재하는지 확인 if (authenticationIsRequired(username)) { // 인증 진행 Authentication authResult = this.authenticationManager.authenticate(authRequest); // 인증 결과를 Security Context에 저장 SecurityContext context = this.securityContextHolderStrategy.createEmptyContext(); context.setAuthentication(authResult); this.securityContextHolderStrategy.setContext(context); if (this.logger.isDebugEnabled()) { this.logger.debug(LogMessage.format("Set SecurityContextHolder to %s", authResult)); } // Remember Me 서비스에 등록 this.rememberMeServices.loginSuccess(request, response, authResult); // Security Context Repository에 저장 this.securityContextRepository.saveContext(context, request, response); // 로그인 성공 핸들러 onSuccessfulAuthentication(request, response, authResult); } } catch (AuthenticationException ex) { this.securityContextHolderStrategy.clearContext(); this.logger.debug("Failed to process authentication request", ex); this.rememberMeServices.loginFail(request, response); onUnsuccessfulAuthentication(request, response, ex); if (this.ignoreFailure) { chain.doFilter(request, response); } else { this.authenticationEntryPoint.commence(request, response, ex); } return; } chain.doFilter(request, response); } ​ 브라우저에서 Basic 인증 진행하기 ​ ​ 브라우저에서 제공하는 기능으로 브라우저별로 다른 화면이 발생한다. ​ 참고 자료 ​ https://docs.spring.io/spring-security/reference/servlet/authentication/passwords/basic.html Basic Authentication :: Spring Security Spring Security / Servlet Applications / Authentication / Username/Password / Reading Username/Password / Basic Basic Authentication This section provides details on how Spring Security provides support for Basic HTTP Authentication for servlet-based applications. This section describes how HTTP Bas... docs.spring.io ​ 이전 : 18. DefaultLogoutPageGenerationFilter 다음 : 20. RequestCacheAwareFilter https://youtu.be/YHNGABc-Nyg 67, 스프링 시큐리티 내부 구조 > 20. RequestCacheAwareFilter RequestCacheAwareFilter 목적 ​ 이 필터는 DefaultSecurityFilterChain에 기본적으로 등록되는 필터로 열두 번째에 위치한다. 이 필터가 등록되는 목적은 이전 HTTP 요청에서 처리할 작업이 있고 현재 요청에서 그 작업을 수행하기 위해 등록된다. 커스텀 SecurityFilterChain에도 기본적으로 등록되기 때문에 아래와 같은 구문을 통해 비활성화 시킬 수 있다. ​ http .requestCache((cache) -> cache.disable()); ​ 동작 예시 ​ 1. 로그인하지 않은 사용자가 권한이 필요한 “/my” 경로에 접근 2. 권한 없음 예외가 발생하고 핸들러에서 “/my” 경로를 기억 후 핸들 작업 수행 3. 스프링 시큐리티가 “/login” 창을 띄움 4. username/password를 입력 후 인증을 진행 5. 로그인 이후 저장되어 있는 “/my” 경로를 불러내서 실행 ​ 핸들 시점 ​ 예외를 처리하는 필터인 ExceptionTranslationFilter에서 ExceptionTranslationFilter 이후에 발생하는 예외들을 모두 받는다. 이때 AccessDeniedException과 같은 몇 몇 예외 발생시 내부 메소드 sendStartAuthentication() 메소드가 실행되는데 여기서 requestCache를 저장한다. ​ protected void sendStartAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, AuthenticationException reason) throws ServletException, IOException { SecurityContext context = this.securityContextHolderStrategy.createEmptyContext(); this.securityContextHolderStrategy.setContext(context); this.requestCache.saveRequest(request, response); this.authenticationEntryPoint.commence(request, response, reason); } ​ ExceptionTranslationFilter 필터는 23강에서 다룬다. ​ RequestCacheAwareFilter 클래스 ​ 저장된 requestCache를 확인 후 현재 요청에 적용 시킨다. ​ public class RequestCacheAwareFilter extends GenericFilterBean { private RequestCache requestCache; public RequestCacheAwareFilter() { this(new HttpSessionRequestCache()); } public RequestCacheAwareFilter(RequestCache requestCache) { Assert.notNull(requestCache, "requestCache cannot be null"); this.requestCache = requestCache; } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { // request 캐시에서 이전 요청에 캐싱해둔 데이터가 있는지 조회 HttpServletRequest wrappedSavedRequest = this.requestCache.getMatchingRequest((HttpServletRequest) request, (HttpServletResponse) response); // 있다면 다음 필터로 넘길때 현재 요청에 덮어 쓰기 chain.doFilter((wrappedSavedRequest != null) ? wrappedSavedRequest : request, response); } } ​ 이전 : 19. BasicAuthenticationFilter 다음 : 21. SecurityContextHolderAwareRequestFilter https://youtu.be/X-2Ro0g2zpw 68, 스프링 시큐리티 내부 구조 > 21. SecurityContextHolderAwareRequestFilter https://docs.spring.io/spring-security/site/docs/current/api/org/springframework/security/web/servletapi/SecurityContextHolderAwareRequestFilter.html SecurityContextHolderAwareRequestFilter (spring-security-docs 6.5.2 API) Package org.springframework.security.web.servletapi Class SecurityContextHolderAwareRequestFilter java.lang.Object org.springframework.web.filter.GenericFilterBean org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter All Implemented Interfaces: jakarta.servlet.Filter ,... docs.spring.io SecurityContextHolderAwareRequestFilter 목적 ​ 이 필터는 DefaultSecurityFilterChain에 기본적으로 등록되는 필터로 열세 번째에 위치한다. 이 필터가 등록되는 목적은 ServletRequest 요청에 스프링 시큐리티 API를 다룰 수 있는 메소드를 추가하기 위해서다. 커스텀 SecurityFilterChain에도 기본적으로 등록된다. ​ SecurityContextHolderAwareRequestFilter 클래스 ​ public class SecurityContextHolderAwareRequestFilter extends GenericFilterBean { } ​ 추가되는 스프링 시큐리티 API 메소드 ​ - authenticate() : 사용자가 인증 여부를 확인하는 메소드 - login() : 사용자가 AuthenticationManager를 활용하여 인증을 진행하는 메소드 - logout() : 사용자가 로그아웃 핸들러를 호출할 수 있는 메소드 - AsyncContext.start() : Callable를 사용하여 비동기 처리를 진행할 때 SecurityContext를 복사하도록 설정하는 메소드 ​ 이전 : 20. RequestCacheAwareFilter 다음 : 22. AnonymousAuthenticationFilter https://youtu.be/QOtbkbN0LUs 69, 스프링 시큐리티 내부 구조 > 22. AnonymousAuthenticationFilter https://docs.spring.io/spring-security/site/docs/current/api/org/springframework/security/web/authentication/AnonymousAuthenticationFilter.html AnonymousAuthenticationFilter (spring-security-docs 6.5.2 API) Package org.springframework.security.web.authentication Class AnonymousAuthenticationFilter java.lang.Object org.springframework.web.filter.GenericFilterBean org.springframework.security.web.authentication.AnonymousAuthenticationFilter All Implemented Interfaces: jakarta.servlet.Filter , org.springf... docs.spring.io AnonymousAuthenticationFilter 목적 ​ 이 필터는 DefaultSecurityFilterChain에 기본적으로 등록되는 필터로 열네 번째에 위치한다. 이 필터가 등록되는 목적은 여러 필터를 거치면서 현재 지점 까지 SecurityContext값이 null 인 경우 Anonymous 값을 넣어주기 위해 사용된다. 커스텀 SecurityFilterChain에도 기본적으로 등록된다. ​ AnonymousAuthenticationFilter 클래스 ​ public class AnonymousAuthenticationFilter extends GenericFilterBean implements InitializingBean { } ​ 미인증 유저 확인 ​ String username = SecurityContextHolder.getContext().getAuthentication().getName(); String role = SecurityContextHolder.getContext().getAuthentication().getAuthorities().toString(); System.out.println(username); System.out.println(role); ​ ​ 이전 : 21. SecurityContextHolderAwareRequestFilter 다음 : 23. ExceptionTranslationFilter​ https://youtu.be/C-SDDpqF234 70, 스프링 시큐리티 내부 구조 > 23. ExceptionTranslationFilter https://docs.spring.io/spring-security/site/docs/current/api/org/springframework/security/web/access/ExceptionTranslationFilter.html ExceptionTranslationFilter (spring-security-docs 6.5.2 API) Package org.springframework.security.web.access Class ExceptionTranslationFilter java.lang.Object org.springframework.web.filter.GenericFilterBean org.springframework.security.web.access.ExceptionTranslationFilter All Implemented Interfaces: jakarta.servlet.Filter , org.springframework.beans.factory... docs.spring.io ExceptionTranslationFilter 목적 ​ 이 필터는 DefaultSecurityFilterChain에 기본적으로 등록되는 필터로 열다섯 번째에 위치한다. 이 필터가 등록되는 목적은 이 필터 이후에 발생하는 인증, 인가 예외를 핸들링하기 위해 사용된다. 커스텀 SecurityFilterChain에도 기본적으로 등록된다. ​ ExceptionTranslationFilter 클래스 ​ public class ExceptionTranslationFilter extends GenericFilterBean implements MessageSourceAware { } - 주요 로직 : doFilter private void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException { try { chain.doFilter(request, response); } catch (IOException ex) { throw ex; } catch (Exception ex) { // Try to extract a SpringSecurityException from the stacktrace Throwable[] causeChain = this.throwableAnalyzer.determineCauseChain(ex); RuntimeException securityException = (AuthenticationException) this.throwableAnalyzer .getFirstThrowableOfType(AuthenticationException.class, causeChain); if (securityException == null) { securityException = (AccessDeniedException) this.throwableAnalyzer .getFirstThrowableOfType(AccessDeniedException.class, causeChain); } if (securityException == null) { rethrow(ex); } if (response.isCommitted()) { throw new ServletException("Unable to handle the Spring Security Exception " + "because the response is already committed.", ex); } handleSpringSecurityException(request, response, chain, securityException); } } ​ - 인증/인가 예외를 핸들 시작점 private void handleSpringSecurityException(HttpServletRequest request, HttpServletResponse response, FilterChain chain, RuntimeException exception) throws IOException, ServletException { if (exception instanceof AuthenticationException) { handleAuthenticationException(request, response, chain, (AuthenticationException) exception); } else if (exception instanceof AccessDeniedException) { handleAccessDeniedException(request, response, chain, (AccessDeniedException) exception); } } ​ - 인증 예외 핸들 private void handleAuthenticationException(HttpServletRequest request, HttpServletResponse response, FilterChain chain, AuthenticationException exception) throws ServletException, IOException { this.logger.trace("Sending to authentication entry point since authentication failed", exception); sendStartAuthentication(request, response, chain, exception); } ​ - 인가 예외 핸들 private void handleAccessDeniedException(HttpServletRequest request, HttpServletResponse response, FilterChain chain, AccessDeniedException exception) throws ServletException, IOException { Authentication authentication = this.securityContextHolderStrategy.getContext().getAuthentication(); boolean isAnonymous = this.authenticationTrustResolver.isAnonymous(authentication); if (isAnonymous || this.authenticationTrustResolver.isRememberMe(authentication)) { if (logger.isTraceEnabled()) { logger.trace(LogMessage.format("Sending %s to authentication entry point since access is denied", authentication), exception); } sendStartAuthentication(request, response, chain, new InsufficientAuthenticationException( this.messages.getMessage("ExceptionTranslationFilter.insufficientAuthentication", "Full authentication is required to access this resource"))); } else { if (logger.isTraceEnabled()) { logger.trace( LogMessage.format("Sending %s to access denied handler since access is denied", authentication), exception); } this.accessDeniedHandler.handle(request, response, exception); } } ​ 중요한 점 ​ ExceptionTranslationFilter 필터 이전에 발생하는 예외의 경우 처리하지 못한다. 예외 처리는 호출한 필터가 진행할 수 있다. ​ 예를 들어 UsernamePasswordAuthenticationFilter는 ExceptionTranslationFilter 보다 앞에 존재하기 때문에 ExceptionTranslationFilter에서 처리할 수 없다. 아래 비슷한 stackoverflow 질문. ​ Spring Security ExceptionTranslationFilter 예외 처리 관련 스택 오버 플로우 문서 Spring Security ExceptionTranslationFilter does't handle thrown in custom filter exception So I have next Spring Security configuration: @Configuration @EnableWebSecurity @EnableMethodSecurity @RequiredArgsConstructor public class SecurityConfig { private final JwtAuthenticationFilter stackoverflow.com ​ 이전 : 22. AnonymousAuthenticationFilter 다음 : 24. AuthorizationFilter https://youtu.be/SpHoeh4DsPA 71, 스프링 시큐리티 내부 구조 > 24. AuthorizationFilter https://docs.spring.io/spring-security/site/docs/current/api/org/springframework/security/web/access/intercept/AuthorizationFilter.html AuthorizationFilter (spring-security-docs 6.5.2 API) Package org.springframework.security.web.access.intercept Class AuthorizationFilter java.lang.Object org.springframework.web.filter.GenericFilterBean org.springframework.security.web.access.intercept.AuthorizationFilter All Implemented Interfaces: jakarta.servlet.Filter , org.springframework.beans.f... docs.spring.io AuthorizationFilter 목적 ​ 이 필터는 DefaultSecurityFilterChain에 기본적으로 등록되는 필터로 마지막에 위치한다. 이 필터가 등록되는 목적은 SecurityFilterChain의 authorizeHttpRequests()를 통해 인가 작업을 진행한 값에 따라 최종적으로 인가를 수행한다. 커스텀 SecurityFilterChain에도 기본적으로 등록되며 인가를 설정하는 방법은 아래와 같다. ​ http .authorizeHttpRequests((auth) -> auth .requestMatchers("/").permitAll() .anyRequest().permitAll()); ​ AuthorizationFilter 클래스 ​ public class AuthorizationFilter extends GenericFilterBean { } ​ - 주요 로직 : doFilter public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws ServletException, IOException { HttpServletRequest request = (HttpServletRequest) servletRequest; HttpServletResponse response = (HttpServletResponse) servletResponse; // 특정 설정이 enable이고 이 필터가 이번 요청에서 이미 사용 되었다면 건너 뜀 if (this.observeOncePerRequest && isApplied(request)) { chain.doFilter(request, response); return; } // 비동기 요청과 같은 특정 상황에서 인가 작업을 건너 뛸지 결정 if (skipDispatch(request)) { chain.doFilter(request, response); return; } // 현재 필터가 이미 사용되었다면 값을 추가 String alreadyFilteredAttributeName = getAlreadyFilteredAttributeName(); request.setAttribute(alreadyFilteredAttributeName, Boolean.TRUE); // 인가 작업 수행 try { // 인가 매니저를 통해 인가 확인 AuthorizationDecision decision = this.authorizationManager.check(this::getAuthentication, request); this.eventPublisher.publishAuthorizationEvent(this::getAuthentication, request, decision); if (decision != null && !decision.isGranted()) { // 인가 권한이 안맞다면 예외 발생 throw new AccessDeniedException("Access Denied"); } chain.doFilter(request, response); } finally { // 최종적으로 모든 작업 처리 후 사용 기록 삭제 request.removeAttribute(alreadyFilteredAttributeName); } } ​ 이전 : 23. ExceptionTranslationFilter 다음 : 25. SessionManagementConfigurer https://youtu.be/U4DyQF_eQVE 72, 스프링 시큐리티 내부 구조 > 25. SessionManagementConfigurer https://docs.spring.io/spring-security/site/docs/current/api/org/springframework/security/config/annotation/web/configurers/SessionManagementConfigurer.html SessionManagementConfigurer (spring-security-docs 6.5.2 API) Package org.springframework.security.config.annotation.web.configurers Class SessionManagementConfigurer> java.lang.Object org.springframework.security.config.annotation.SecurityConfigurerAdapter < DefaultSecurityFilterChain , B> org.springframework.security.config.... docs.spring.io SessionManagementConfigurer 목적 ​ 세션에 관련된 설정 및 초기화(활성화)를 진행하는 Config 클래스이며 설정하는 목록은 아래와 같다. - 시큐리티 필터 - SessionManagementFilter - ConcurrentSessionFilter - 저장 및 공유 객체 - RequestCache - SecurityContextRepository - InvalidSessionStrategy - AuthenticationTrustResolver 기본 설정 값 및 사용자가 SecurityConfig의 SecurityFilterChain에서 커스텀한 값을 기반으로 위 클래스들을 설정한다. ​ 이번 강에서 다룰 내용 예시 및 요소 : 세션 설정에 따른 SecurityContextRepository ​ SessionManagementConfigurer 클래스의 경우 다양한 세션 관련 설정을 수행한다. 이번 시간에는 스프링 어플리케이션의 SecurityContext와 서버 세션에 저장된 사용자의 정보를 동기화 시키는 SecurityContextRepository에 대해 알아보려고 한다. 조금더 자세하게 설명하면 SecurityContextRepository 인터페이스의 기본 구현체는 사용자가 접근하면 서버 세션으로 부터 SecurityContext로 유저 정보를 불러오고, 로그인을 진행하면 SecurityContext의 값을 서버 세션에 저장한다. 따라서 SecurityContextRepository 인터페이스 구현체는 다양한 필터에서 사용하기 때문에 그 구현체가 초기화되는 부분과 왜 초기화 부분이 중요한지 알아둘 필요가 중요하다. ​ https://cafe.naver.com/xxxjjhhh/58 스프링 시큐리티 내부 구조 > 11. SecurityContextHolderFilter 스프링 시큐리티 내부 구조 > 11. SecurityContextHolderFilter https://docs.spring.io/spring-security/site/docs... cafe.naver.com ​ 11강에서 살펴본 내용과 같이 세션 방식에서는 위의 과정이 알맞지만, STATELESS 설정시에는 세션이 필요 없기 때문에 SecurityContextRepository 인터페이스에 대해 다양한 구현체가 존재한다. 기본 구현체는 HttpSessionSecurityContextRepository이지만 STATELESS 상태에서는 NullSecurityContextRepository가 사용된다. 이렇게 개발자의 설정에 따라 알맞은 구현체가 선정되는 위치가 SessionManagementConfigurer 클래스의 내부 메소드다. ​ SessionManagementConfigurer 클래스 ​ public final class SessionManagementConfigurer> extends AbstractHttpConfigurer, H> { } ​ - 주요 로직 : init public void init(H http) { SecurityContextRepository securityContextRepository = http.getSharedObject(SecurityContextRepository.class); boolean stateless = isStateless(); if (securityContextRepository == null) { // 만약 STATELESS 상태라면 if (stateless) { http.setSharedObject(SecurityContextRepository.class, new RequestAttributeSecurityContextRepository()); // NullSecurityContextRepository로 초기화 this.sessionManagementSecurityContextRepository = new NullSecurityContextRepository(); } else { // 세션 STATE 상태라면 HttpSessionSecurityContextRepository httpSecurityRepository = new HttpSessionSecurityContextRepository(); httpSecurityRepository.setDisableUrlRewriting(!this.enableSessionUrlRewriting); httpSecurityRepository.setAllowSessionCreation(isAllowSessionCreation()); AuthenticationTrustResolver trustResolver = http.getSharedObject(AuthenticationTrustResolver.class); if (trustResolver != null) { httpSecurityRepository.setTrustResolver(trustResolver); } this.sessionManagementSecurityContextRepository = httpSecurityRepository; DelegatingSecurityContextRepository defaultRepository = new DelegatingSecurityContextRepository( httpSecurityRepository, new RequestAttributeSecurityContextRepository()); http.setSharedObject(SecurityContextRepository.class, defaultRepository); } } else { this.sessionManagementSecurityContextRepository = securityContextRepository; } RequestCache requestCache = http.getSharedObject(RequestCache.class); if (requestCache == null) { if (stateless) { http.setSharedObject(RequestCache.class, new NullRequestCache()); } } http.setSharedObject(SessionAuthenticationStrategy.class, getSessionAuthenticationStrategy(http)); http.setSharedObject(InvalidSessionStrategy.class, getInvalidSessionStrategy()); } ​ SecurityContextRepository가 사용되는 지점 ​ - SecurityContextHolderFilter 사용자의 요청이 서버에 도달한 후 쓰레드의 SecurityContext에 서버 세션 메모리의 값을 할당하는 필터 - 각종 로그인 필터 각각의 로그인 필터에서 로그인이 처리된 후 SecurityContextRepository를 통해 저장하는 구문이 존재 이전 : 24. AuthorizationFilter ​ 73, 유튜브 구독자 10,000명을 위한 계획 목차 1. 커뮤니티 이동 2. Prepare Spring Security 7 : 스프링 시큐리티 7 시리즈 3. 스프링 시큐리티 : RESTful + React.js 따라하기 프로젝트 4. 아파치 카프카 5. MSA 환경에서 스프링 시큐리티 6. ChatGPT 클론 코딩 1. 커뮤니티 이동 ​ 기존 https://www.devyummi.com -> 신규 https://cafe.naver.com/xxxjjhhh ​ - 사유 사설 홈페이지 관리, 비용, 기능 추가가 너무 귀찮습니다. AWS 프리티어가 끝났기 때문에 비용도 발생하고, 보안 문제, 커뮤니티 기능 등등 여러 사항으로 이주합니다. ​ - Docs 기존의 Docs 자료들은 차차 옮겨질 예정입니다. ​ - 가입, 공개 범위 Docs 시리즈는 가입하지 않으셔도 방문 가능합니다. 가입 하신다면 QnA 게시판에 코드를 올려서 질문이 가능하고, 저 뿐만 아니라 아무나 질문에 대한 답변을 나누시면 좋을거 같습니다. ​ 2. Prepare Spring Security 7 : 스프링 시큐리티 7 시리즈 ​ 스프링 시큐리티 7 스냅샷이 나왔습니다. https://spring.io/blog/2025/07/21/spring-security-7-0-0-M1-available-now Spring Security 7.0.0-M1 available now Level up your Java code and explore what Spring can do for you. spring.io https://docs.spring.io/spring-security/reference/migration-7/index.html Preparing for 7.0 :: Spring Security Edit this Page GitHub Project Stack Overflow Spring Security / Preparing for 7.0 Preparing for 7.0 While Spring Security 7.0 does not have a release date yet, it is important to start preparing for it now. This preparation guide is designed to summarize the biggest changes in Spring Security 7.0 and... docs.spring.io ​ - 아직 다 확인하진 않았지만 6 버전이랑 비슷합니다. - 6.0 ~ 6.3 -> 7 : 조금 다름 - 6.3~ -> 7 : 거의 비슷 ​ - "스프링 시큐리티" 시리즈 리뉴얼 ​ 제 채널의 "스프링 시큐리티" 시리즈를 2년전에 촬영 했습니다. (버전은 대략 6.1이었고) ​ 채널 초기에 촬영하다 보니 디테일적인 부분이 없어 재 촬영을 할 예정입니다. 다만 기존 6을 가지고 촬영하기는 애매해서 7.0.0이 정식 출시되면 진행할 예정입니다. (시리즈 구성 자체는 초보자를 위해 기존 "스프링 시큐리티" 시리즈와 크게 달라지지 않을거 같습니다.) ​ 3. 스프링 시큐리티 : RESTful + React.js 따라하기 프로젝트 ​ 수요가 조금 있을거 같고, 많은 프로젝트에서 사용되는 CSR 프론트 까지 합쳐진 인증/인가 따라하기 프로젝트도 준비할 예정입니다. ​ 제 채널의 시리즈가 파편화 되어 있고, 심지어 SSR이 아니라면 프론트는 다루지도 않습니다. "스프링 시큐리티", "스프링 시큐리티 JWT", "스프링 OAuth2 관련 ...", "스프링 JWT 심화" 이 때문에 위에서 얻은 지식을 개인 프로젝트에 붙이는데 어려움이 있으신 분들이 있어 아래 목표를 가지고 진행할 예정입니다. ​ - 대략적인 목표 - 스프링 부트 + 리액트 - 자체 로그인 / 소셜 로그인 - Access 토큰 / Refresh 토큰 - DB Refresh 저장으로 whitelist - 프론트 로컬 스토리지 및 Access 만료시 갱신 ​ 4. 아파치 카프카 ​ 공부하고 있습니다. 어렵습니다... (시간 내기가 힘드네요.) 준비하는데 오래 걸릴 거 같습니다. ​ 5. MSA 환경에서 스프링 시큐리티 ​ SCG, Spring OAuth2 Authorization Server, Netflix Passport, etc 많은걸 공부하며 잔뼈가 굵어졌습니다. MSA 게이트웨이 단에서 JWT 검증하고 뒤에 있는 MS에게 검증 결과주는 형태의 아키텍처 시리즈도 만들어 볼까 합니다. ​ (이것도 오래 걸릴듯~) ​ 6. ChatGPT 클론 코딩 ​ 저번에 잠깐 보여드렸던 프로젝트도 공개 예정입니다. (클론 코딩) ​ https://youtu.be/wFzRQ_Na_-8?si=_SRpP99EeI2jqXyi 74, Resilience4J는 MSA를 구성하는 마이크로 서비스가 겪을 수 있는 장애 상황을 대비하기 위해 설계된 자바용 내결함성 라이브러리입니다. ​ Resilience4J ​ 1. MSA 장애 대응 2. 모듈별 역할 및 동작 3. 의존성 추가 및 프로젝트 시작 4. 호출용 API 서버 구축 5. 슬라이딩 윈도우 기법 6. circuit breaker 구현 7. retry 구현 8. bulk head 구현 9. actuactor 서킷 상태 확인 ​ 75, Resilience4J > 1. MSA 장애 대응 MSA 장애 상황과 대응 ​ MSA는 여러개의 마이크로 서비스가 서로 호출을 하며 하나의 시스템을 이룬다. 이때 각각의 MS는 무응답, 지연, 실패와 같은 상황을 발생할 수 있습니다. 위 상황이 발생할때 해당 부분 MS에 circuit을 open하여 일시적으로 다른 작업을 처리하도록하는 MSA 장애 대응을 진행해야 한다. 스프링 프레임워크 기반으로 MSA를 구축할때 위와 같이 서킷 방식의 장애 대응 솔루션을 제공하는 프레임워크는 Netflix Hystrix와 Resilience4J가 존재한다. ​ Resilience4J ​ Netflix Hystrix의 지원이 중단되면서 Spring Cloud에서 Hystrix를 계승한 Resilience4J 서킷 브레이크 프레임워크를 제공한다. Resilience4J는 자바용 내결함성 라이브러리로 하나의 서비스에서 발생할 수 있는 장애 상황에서 그것을 대처할 수 있는 여러 솔루션을 제공한다. ​ https://resilience4j.readme.io/ resilience4j Jump to Content Guides GitHub Log In Resilience4j is a fault tolerance library for Java™ Resilience4j is a lightweight fault tolerance library inspired by Netflix Hystrix, but designed for functional programming. Resilience4j provides higher-order functions (decorators) to enhance any functional int... resilience4j.readme.io ​ 예시 ​ - 장애 상황이란? - 실패 : 요청 했는데 응답이 안옴 (health check로 금방 알 수 있음) - 지연 : 요청 했는데 평소보다 늦게 응답이 옴 (응답이 왔기 때문에 파악하기 힘듬) ​ ​ 다음 : 2. 모듈별 역할 및 동작 https://youtu.be/UpwJOImeYcA?si=tG3U7TKMrdbORD24 76, Resilience4J > 2. 모듈별 역할 및 동작 참조 ​ https://docs.spring.io/spring-cloud-circuitbreaker/reference/index.html Spring Cloud Circuit Breaker :: Spring Cloud Circuitbreaker Edit this Page GitHub Project Stack Overflow Spring-Cloud-CircuitBreaker / Introduction Spring Cloud Circuit Breaker 3.3.0 # Usage Documentation The Spring Cloud CircuitBreaker project contains implementations for Resilience4J and Spring Retry. The APIs implemented in Spring Cloud CircuitBreaker liv... docs.spring.io ​ https://resilience4j.readme.io/docs/getting-started Introduction Resilience4j is a lightweight fault tolerance library designed for functional programming. Resilience4j provides higher-order functions (decorators) to enhance any functional interface, lambda expression or method reference with a Circuit Breaker, Rate Limiter, Retry or Bulkhead. You can stack more ... resilience4j.readme.io ​ Resilience4J 제공 모듈 ​ - circuit-breaker : 회로 차단기 - 실패 - 지연 - fall-back : 실패시 동작 - retry : 자동 재시도 - bulk-head : 동시 실행 제한 - rate-limiter : 속도(성능) 제한 - time-limiter : 시간 초과 제한 - cache : 결과 캐싱 ​ 2강 ​ 각 모듈의 자세한 정보, 내부 메소드, 구현 방법을 알기 전 대략적으로 알아보는 단계. ​ circuit-breaker ​ Resilience4J의 핵심 모듈로 장애 또는 지연 상황에서 circuit을 일시적으로 오픈하는 기능을 제공한다. 서킷을 오픈하는 조건은 아래와 같다. - 실패 : 호출 후 특정 비율 이상 실패 - 지연 : 호출 후 특정 비율 이상 지연 서킷은 아래와 같은 유한 상태를 가진다. ​ (service2가 service1을 호출하는 상황이라고 가정하고) ​ ​ - CLOSED : 평상시 상태 - OPEN : 평상시 상태에서 사용자가 설정한 임계치 이상의 지연율 및 실패율이 달성되면 회로를 끊어버린 상태 - HALP_OPEN : OPEN 상태에서 설정한 시간이 지난 후 HALF_OPEN 상태로 전환된다. HALF_OPEN 상태는 CLOSED 또는 OPEN 상태로 전환을 판단한다. ​ fall-back ​ circuit-breaker가 실패 또는 지연 상황 발생으로 circuit을 open 할 경우 대비책으로 동작할 메소드 설정. retry ​ 실패한 요청을 일정 시간 이후에 재시도하는 모듈. ​ bulk-head ​ 병렬 실행 제한을 위한 모듈. ​ rate-limiter ​ 마이크로 서비스 내부 실행 중 일정 비율 이상의 부하를 막기 위한 속도 제한 모듈. ​ time-limiter ​ 마이크로 서비스 내부 실행 중 일정 시간 이상의 지연을 막기 위한 시간 제한 모듈. ​ cache ​ 요청에 대한 결과 저장(캐싱)을 위한 모듈. ​ 읽어보면 좋을 자료 ​ circuit-breaker와 fall-back 관련해서 읽어보면 좋을 자료를 준비했습니다. - 올리브영 테크블로그의 Circuitbreaker를 사용한 장애 전파 방지 https://oliveyoung.tech/2023-08-31/circuitbreaker-inventory-squad/ Circuitbreaker를 사용한 장애 전파 방지 | 올리브영 테크블로그 Circuitbreaker와 Resilience4j A to Z oliveyoung.tech ​ - G마켓 기술 블로그의 Fault Tolerance https://dev.gmarket.com/86 API 메시업과 Fault Tolerance 문제 해결 전략 안녕하세요. Shopping Service Backend팀 안재열입니다.저희 팀에서는 여러 팀에서 생성하고 관리한 상품과 관련된 데이터를 적절하게 가공하여 상품 목록 정보를 제공하는 API를 개발하는 업무를 담당하고 있습니다. 이 과정에서 다양한 팀에서 제공하는 다수의 API를 사용하여 한데 묶어주는 메시업(Mashup) 작업활동을 수행하게 됩니다. 그런데 다양한 곳의 API를 엮다보면 예기치 못한 문제가 발생하기도 합니다.이번 글에서는 API 메시업 활동 중에 만나게 되는 문제점과 해결 방안에 관해서 살펴보겠습니다.API 메시업(... dev.gmarket.com ​ 이전 : 1. MSA 장애 대응 다음 : 3. 의존성 추가 및 프로젝트 시작 https://youtu.be/EL2XEh6l_Rc?si=c6zvdFaxcLVfEKTN 77, Resilience4J > 3. 의존성 추가 및 프로젝트 시작 버전 ​ - 스프링 부트 버전 : 3.2.0 - 언어 : Java - 의존성 관리 도구 : gradle (groovy) ​ 기본 모듈 : build.gradle ​ - spring web - lombok - resilience4j - build.gradle plugins { id 'java' id 'org.springframework.boot' version '3.2.0' id 'io.spring.dependency-management' version '1.1.4' } group = 'com.example' version = '0.0.1-SNAPSHOT' java { sourceCompatibility = '17' } configurations { compileOnly { extendsFrom annotationProcessor } } repositories { mavenCentral() } ext { set('springCloudVersion', "2023.0.0") } dependencies { implementation 'org.springframework.boot:spring-boot-starter-web' implementation 'org.springframework.cloud:spring-cloud-starter-circuitbreaker-resilience4j' compileOnly 'org.projectlombok:lombok' annotationProcessor 'org.projectlombok:lombok' testImplementation 'org.springframework.boot:spring-boot-starter-test' } dependencyManagement { imports { mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}" } } tasks.named('test') { useJUnitPlatform() } ​ 추가 모듈 : build.gradle : dependencies ​ dependencies { implementation 'org.springframework.boot:spring-boot-starter-aop' implementation 'io.github.resilience4j:resilience4j-all' } ​ 구조 ​ ​ 컨트롤러 생성 ​ - MainController @Controller @ResponseBody public class MainController { private Rest1Comp rest1Comp; @Autowired public MainController(Rest1Comp rest1Comp) { this.rest1Comp = rest1Comp; } @GetMapping("/") public String mainP() { return rest1Comp.restTemplate1().getForObject("/data", String.class); } } ​ RestTemplate 생성 : 다른 서비스 호출을 위한 API Client ​ @Component public class Rest1Comp { @Bean public RestTemplate restTemplate1() { return new RestTemplateBuilder().rootUri("http://localhost:9000") .build(); } } ​ 이전 : 2. 모듈별 역할 및 동작 다음 : 4. 호출용 API 서버 구축 ​ https://youtu.be/f7-t8o9NbFI 78, Resilience4J > 4. 호출용 API 서버 구축 구조 ​ ​ Service1 API 서버 구축 ​ - Spring Boot 3.2.0 ​ DataController ​ @Controller @ResponseBody public class DataController { @GetMapping("/data") public String dataP() { String nowTime = String.valueOf(LocalDateTime.now()); try { Thread.sleep(10000); } catch (InterruptedException e) { throw new RuntimeException(e); } return nowTime; } } ​ application.properties ​ server.port=9000 ​ 이전 : 3. 의존성 추가 및 프로젝트 시작 다음 : 5. 슬라이딩 윈도우 기법 https://youtu.be/mN8RtsKAaBI 79, Resilience4J > 5. 슬라이딩 윈도우 기법 https://ko.wikipedia.org/wiki/%EC%8A%AC%EB%9D%BC%EC%9D%B4%EB%94%A9_%EC%9C%88%EB%8F%84 슬라이딩 윈도 - 위키백과, 우리 모두의 백과사전 슬라이딩 윈도 (Sliding window)는 두 개의 네트워크 호스트간의 패킷 의 흐름을 제어하기 위한 방법이다. TCP 와 같이 데이터의 전달을 보증하는 프로토콜 에서는 패킷 하나 하나가 정상적으로 전달되었음을 알리는 확인 신호(acknowledgement, 이하 ACK )를 받아야하며, 만약 패킷이 중도에 잘못되었거나 분실되어 확인받지 못하는 경우, 해당 패킷을 재전송해야하는 필요가 있다. 슬라이딩 윈도는 일단 '윈도( 메모리 버퍼 의 일정 영역)'에 포함되는 모든 패킷을 전송하고, 그 패킷들의 전달이 확인되는대로 이 윈도를 ... ko.wikipedia.org 슬라이딩 윈도우 기법 ​ 슬라이딩 윈도우 기법을 통해 지정해둔 사이즈의 슬라이딩 윈도우 터널을 생성하고 내부에서 실패 및 지연 개수를 측정한다. ​ ​ 이전 : 4. 호출용 API 서버 구축 다음 : 6. circuit breaker 구현 https://youtu.be/vfDXRZqrzSs 80, Resilience4J > 6. circuit breaker 구현 구조 ​ ​ Service2에서 Service1을 호출하는 상황에서 Service2에 circuit을 open할 Resilience4J의 circuit breaker를 구현하는 방법 ​ 특정 함수에 circuit breaker 패턴 적용 ​ 마이크로서비스의 내부 로직 중 지연 또는 실패가 발생할 수 있는 Controller, Service단에 circuit breaker를 적용하여 해당 상황이 발생하였을때 대응할 수 있도록 구성한다. - circuit breaker 어노테이션 방식 적용 @CircuitBreaker(name = "특정할이름", fallbackMethod = "실패시수행할메소드이름") ​ - 예시 @CircuitBreaker(name = "특정할이름", fallbackMethod = "실패시수행할메소드이름") @GetMapping("/") public String mainP() { return rest1Comp.restTemplate1().getForObject("/data", String.class); } ​ name에 대한 circuit breaker 설정 ​ circuit breaker를 적용할 특정 name 메소드에 대해 circuit breaker 설정을 적용하는 방법 - application.properties resilience4j.circuitbreaker.instances.특정할이름.base-config=설정셋 ​ circuit breaker 설정 ​ application.properties에 circuit breaker 모듈이 제공하는 메소드 설정을 진행한다. 이때 특정한 이름에 대해서 변수 설정을 진행해 인스턴스 별로 다른 circuit breaker 패턴을 지정할 수 있다. - 변수에 대한 특정한 이름 설정 resilience4j.circuitbreaker.configs.설정셋.메소드들=값 #예시 resilience4j.circuitbreaker.configs.default.failure-rate-threshold=10 ​ - 슬라이딩 윈도우 공통 사항 #실패 및 지연을 체크할 슬라이딩 윈도우 타입 resilience4j.circuitbreaker.configs.default.sliding-window-type=count_based #슬라이딩 윈도우 크기 resilience4j.circuitbreaker.configs.default.sliding-window-size=5 ​ - 실패에 대한 설정 #서킷을 오픈할 실패 비율 (실패 수 / 슬라이딩 윈도우 크기) resilience4j.circuitbreaker.configs.default.failure-rate-threshold=10 #서킷을 오픈하기 위해 최소 실패 수 (슬라이딩 윈도우를 다 채우지 못했지만 최소값을 설정 가능) resilience4j.circuitbreaker.configs.default.minimum-number-of-calls=5 ​ - 지연에 대한 설정 #서킷을 오픈할 지연 비율 (지연 수 / 슬라이딩 윈도우 크기) resilience4j.circuitbreaker.configs.default.slow-call-rate-threshold=10 #지연으로 판단할 시간 resilience4j.circuitbreaker.configs.default.slow-call-duration-threshold=3000ms ​ - half open 상태 설정 #half open 상태에서 다른 상태로 전환하기 위한 판단 수 resilience4j.circuitbreaker.configs.default.permitted-number-of-calls-in-half-open-state=10 #half open 상태 유지 시간 (만약 0이면 위에서 설정한 값 만큼 수행 후 다음 상태로 전환) resilience4j.circuitbreaker.configs.default.max-wait-duration-in-half-open-state=0 #open 상태에서 half open으로 전환까지 기다리는 시간 resilience4j.circuitbreaker.configs.default.wait-duration-in-open-state=600000ms #open 상태에서 half open 으로 자동 전환 (true시 일정 시간이 지난 후 자동 전환) resilience4j.circuitbreaker.configs.default.automatic-transition-from-open-to-half-open-enabled=true #상태 체크 표시 (actuator용) resilience4j.circuitbreaker.configs.default.register-health-indicator=true ​ - 예외 처리 (아래 예외 또한 실패로 받아드리기 때문에 처리하지 않으면 실패수에 포함 됨) resilience4j.circuitbreaker.configs.default.ignore-exceptions[0]=java.io.IOException resilience4j.circuitbreaker.configs.default.ignore-exceptions[1]=java.util.concurrent.TimeoutException resilience4j.circuitbreaker.configs.default.ignore-exceptions[2]=org.springframework.web.client.HttpServerErrorException ​ fallback 메소드 설정 ​ @CircuitBreaker(name = "특정할이름", fallbackMethod = "실패시수행할메소드이름") @GetMapping("/") public String mainP() { return rest1Comp.restTemplate1().getForObject("/data", String.class); } private String 실패시수행할메소드이름(Throwable throwable) { return throwable.getMessage(); } ​ fallback 메소드는 circuit breaker가 적용된 메소드가 가지는 인자를 필수적으로 가져야 합니다. ​ 이전 : 5. 슬라이딩 윈도우 기법 다음 : 7. retry 구현 https://youtu.be/U28Q3kDwcg4 81, Resilience4J > 7. retry 구현 retry ​ Resilience4J의 retry 모듈은 실패한 요청을 재시도하는 기능을 가지고 있다. retry의 기본적인 우선 순위는 circuit breaker가 실행된 이후 실행되기 때문에 fallbackmethod를 등록한 서킷의 경우 처리하지 않아야 하며 만약 fallbackmethod 동작전 retry를 실행시키고 싶은 경우 내부 config 설정을 통해 우선 순위(Order)를 변경하면 된다. ​ 특정 함수에 retry 패턴 적용 ​ 실패가 발생하고 그것을 필수적으로 재시도해야하는 Controller, Service단의 메소드 상단에 retry 어노테이션 선언을 통해 실패 상황을 재시도 할 수 있다. - retry 어노테이션 방식 적용 @Retry(name = "특정할이름", fallbackMethod = "실패시수행할메소드이름") ​ - 예시 @Retry(name = "MainControllerMethod1", fallbackMethod = "실패시수행할메소드이름") @GetMapping("/") public String mainP() { return rest1Comp.restTemplate1().getForObject("/data", String.class); } ​ name에 대한 retry 설정 ​ retry를 적용할 특정 name 메소드에 대해 retry 설정을 적용하는 방법 -application.properties resilience4j.retry.instances.특정할이름.base-config=설정셋 ​ retry 설정 ​ application.properties에 retry 모듈이 제공하는 메소드 설정을 진행한다. 이때 특정한 이름에 대해서 변수 설정을 진행해 인스턴스 별로 다른 retry 패턴을 지정할 수 있다. - 변수에 대한 특정한 이름 설정 resilience4j.retry.configs.설정셋.메소드들=값 #예시 resilience4j.retry.configs.default.max-attempts=10 ​ - 재요청 설정 #재요청 시도 횟수 resilience4j.retry.configs.default.max-attempts=3 #재요청 간격 resilience4j.retry.configs.default.wait-duration=3000ms ​ - 예외 처리 (retry에 포함) (만약 ignore에도 포함되어 있는 경우 ignore 우선) resilience4j.retry.configs.default.retry-exceptions[0]=java.io.IOException ​ - 예외 처리 (retry에 포함 안함) resilience4j.retry.configs.default.ignore-exceptions[0]=java.io.IOException ​ fallbackmethod 설정 ​ fallbackmethod는 설정한 재시도 최대 횟수가 초과된 이후 실행할 메소드로 어노테이션 인자를 통해 설정할 수 있다. ​ @Retry(name = "MainControllerMethod1", fallbackMethod = "실패시수행할메소드이름") @GetMapping("/") public String mainP() { return rest1Comp.restTemplate1().getForObject("/data", String.class); } private String 실패시수행할메소드이름(Throwable throwable) { return throwable.getMessage(); } ​ 이전 : 6. circuit breaker 구현 다음 : 8. bulk head 구현 https://youtu.be/klfx8Xq-cq4 82, Resilience4J > 8. bulk head 구현 주의 ​ bulk head 구현은 토이 프로젝트로 진행되었으며 간단한 테스만 진행하였기 때문에 직접 실무에 사용하실 경우 자체 검증을 진행하신 후 사용하시길 바랍니다. (간단한 테스만 진행, 공식 문서 및 여러 외국 자료를 통해 현재 문서를 작성하였습니다.) ​ bulk head ​ Resilience4J가 제공하는 bulk head 모듈은 동시 요청을 제한하는 기능을 가진다. 이때 bulk head 모듈은 두가지 타입을 제공하며 아래와 같다. - bulkhead (semaphore) 세마포어 알고리즘을 통해 공유 자원 접근을 제한하는 방식 - thread-pool-bulkhead (fixed thread pool) 고정된 사이즈의 스레드를 지정하는 방식 하나의 메소드에 대해 위의 두 bulkhead 타입 중 하나를 선택하여 구현해야 한다. ​ 각 타입이 존재하는 이유 ​ @Async 어노테이션이 선언된 비동기 메소드와 bulkhead(semaphore) 방식의 자원 제한을 사용할 경우 요청에 의해 생성된 스레드는 재사용되지 않고 계속적으로 증가하는 결과를 가진다고 합니다. (세마포어 카운터가 0이 되어도 새로운 스레드를 생성하기 때문에 bulk head 기능을 못 함) 따라서 비동기 메소드의 경우 해당 메소드에 대해 전체 스레드 개수를 제한하는 thread-pool-bulkhead 방식을 사용하는 것이 좋다고 합니다. Bulkhead 패턴 : 세마포어 vs 쓰레드풀 방식에 따른 블로거 추천 게시글 바로가기 ​ 특정 함수에 bulk head 패턴 적용 ​ 동시 요청 제한을 진행해야하는 메소드에 - bulkhead (semaphore) 방식 @Bulkhead(name = "특정할이름", type = Bulkhead.Type.SEMAPHORE, fallbackMethod = "실패시수행할메소드이름") @GetMapping("/") public String mainP() { return rest1Comp.restTemplate1().getForObject("/data", String.class); } ​ - thread-pool-bulkhead (fixed thread pool) @Bulkhead(name = "특정할이름", type = Bulkhead.Type.THREADPOOL, fallbackMethod = "실패시수행할메소드이름") @GetMapping("/") public String mainP() { return rest1Comp.restTemplate1().getForObject("/data", String.class); } ​ name에 대한 bulk head 설정 ​ application.properties에서 설정 - bulkhead (semaphore) 방식 resilience4j.bulkhead.instances.특정할이름.base-config=설정셋 ​ - thread-pool-bulkhead (fixed thread pool) resilience4j.thread-pool-bulkhead.instances.특정할이름.base-config=설정셋 ​ bulk head 설정 ​ application.properties에서 설정 - bulkhead (semaphore) 방식 #동시 요청 세마포어 카운터 수 resilience4j.bulkhead.configs.default.max-concurrent-calls=1 #동시 요청 초과시 웨이팅 시간 (초과되면 exception 발생) resilience4j.bulkhead.configs.deafult.max-wait-duration=1000ms ​ - thread-pool-bulkhead (fixed thread pool) #최대 스레드 풀 resilience4j.thread-pool-bulkhead.configs.defatul.max-thread-pool-size=10 #기본 스레드 풀 resilience4j.thread-pool-bulkhead.configs.default.core-thread-pool-size=5 #스레드풀 초과시 요청이 기다릴 대기큐 크기 resilience4j.thread-pool-bulkhead.configs.default.queue-capacity=50 ​ thread-pool-bulkhead 오류에 대한 GitHub Issue ​ “errorThreadPool bulkhead is only applicable for completable futures” 깃허브 resilience4j 이슈 826 : 쓰레드풀 벌크헤드 이슈 바로가기 ​ fallbackmethod ​ @Bulkhead(name = "특정할이름", type = Bulkhead.Type.SEMAPHORE, fallbackMethod = "실패시수행할메소드이름") @GetMapping("/") public String mainP() { return rest1Comp.restTemplate1().getForObject("/data", String.class); } private String 실패시수행할메소드이름(Throwable throwable) { return throwable.getMessage(); } ​ 이전 : 7. retry 구현 다음 : 9. actuactor 서킷 상태 확인 https://youtu.be/11VlEZcvZ-g 83, Resilience4J > 9. actuator 서킷 상태 확인 actuator를 통한 Resilience4J 서킷 상태 확인 ​ Spring Boot Actuator를 통한 Resilience4J가 적용된 마이크로서비스의 서킷 상태를 확인할 수 있다. actuator 의존성 추가 ​ - build.gradle dependencies { implementation 'org.springframework.boot:spring-boot-starter-actuator' } ​ actuator 엔드포인트 활성화 ​ application.properties에서 설정을 진행한다. - actuator 관련 management.endpoints.web.exposure.include=* management.endpoint.health.show-details=always management.health.circuitbreakers.enabled=true ​ - resilience4j circuit breaker 관련 resilience4j.circuitbreaker.configs.default.register-health-indicator=true ​ actuator 엔드포인트 ​ /actuator/health ​ 이전 : 8. bulk head 구현 https://youtu.be/mQb6exPfnHk 84, 스프링 부트 환경에서 apache poi 모듈을 통해 엑셀(.xlsx)을 다루는 방법 ​ 스프링 부트 xlsx ​ 1. 프로젝트 생성 및 poi 모듈 추가 2. 엑셀 다운로드 환경 구축 3. 엑셀 내부 데이터 생성 4. 셀 조정 및 디자인 5. 엑셀 업로드 환경 구축 6. 소규모 데이터 읽기 7. 대규모 데이터 읽기 SAX ​ 85, 스프링 부트 엑셀 > 1. 프로젝트 생성 및 poi 모듈 추가 스프링 부트 엑셀 ​ 많은 서비스는 엑셀을 활용해 데이터 입출력을하는 경우가 있습니다. ​ 따라서 DB의 데이터를 엑셀로 다운로드하기, 엑셀의 데이터를 DB로 올리는 과정들을 알아보겠습니다. (시리즈의 간소성을 위해 DB 없이, 서비스단에서 가짜 List<> 데이터를 활용하겠습니다.) - 예상 목차 - 엑셀 다운로드 - 엑셀 업로드 프로젝트 생성 ​ - build.gralde > 의존성 추가 dependencies { implementation 'org.springframework.boot:spring-boot-starter-mustache' implementation 'org.springframework.boot:spring-boot-starter-web' compileOnly 'org.projectlombok:lombok' annotationProcessor 'org.projectlombok:lombok' testImplementation 'org.springframework.boot:spring-boot-starter-test' testRuntimeOnly 'org.junit.platform:junit-platform-launcher' } ​ apache poi 모듈 추가 ​ 자바 진영에서는 주로 apache poi라는 모듈을 통해 엑셀을 다루게 됩니다. ​ https://mvnrepository.com/artifact/org.apache.poi/poi ​ - 의존성 추가 implementation 'org.apache.poi:poi-ooxml:5.4.0' ​ 구 버전의 경우 취약점이 많아 사용을 지양해야 합니다. (많은 블로그들이 레거시 코드를 참조하여 구 버전을 사용하고 있습니다.) ​ 다음 : 2. 엑셀 다운로드 환경 구축 https://youtu.be/YUTmzGlv4H4 86, 스프링 부트 엑셀 > 2. 엑셀 다운로드 환경 구축 Service 클래스 ​ 엑셀 다운로드를 위해 사용할 서비스단의 대략적인 틀을 만들어 두겠습니다. domain > download > service > DownloadService.java @Service public class DownloadService { public byte[] downloadXlsx() { return null; } } ​ Controller 클래스 ​ 다운로드 엔드포인트를 통해 다운로드 버튼을 누르면 자동 다운로드 되도록 설정하는 방법을 알아보겠습니다. ​ - api > DownloadController.java import org.example.xl.domain.download.service.DownloadService; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import java.nio.charset.StandardCharsets; @Controller public class DownloadController { private final DownloadService downloadService; public DownloadController(DownloadService downloadService) { this.downloadService = downloadService; } @GetMapping("/download") public ResponseEntity downloadProcess() { // 엑셀 데이터는 byte[]로 받음 byte[] excelBytes = downloadService.downloadXlsx(); // 응답할 파일명, 인코딩 후 공백은 %20으로 치환 String fileName = "엑셀파일.xlsx"; String encodedFileName = java.net.URLEncoder.encode(fileName, StandardCharsets.UTF_8).replaceAll("\\+", "%20"); // 응답 헤더 (엑셀 파일로) HttpHeaders headers = new HttpHeaders(); headers.add("Content-Disposition", "attachment; filename=\"" + encodedFileName + "\""); headers.add("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); // 응답 return new ResponseEntity<>(excelBytes, headers, HttpStatus.OK); } } ​ 예외 처리 ​ 파일을 다루기 때문에 controller에서 try/catch로 예외처리를 해야할 수 있습니다. 이전 : 1. 프로젝트 생성 및 poi 모듈 추가 다음 : 3. 엑셀 내부 데이터 생성 https://youtu.be/YICVrU8H3xM?si=DwC80Mlhptpx3IFI 87, 스프링 부트 엑셀 > 3. 엑셀 내부 데이터 생성 엑셀 객체(파일) 생성 ​ Service 단에서 poi 모듈로 엑셀 byte 객체를 만들겠습니다. - 엑셀 객체 종류 (xlsx) - XSSFWorkBook() : 읽기/쓰기 가능, 1만 행 이하의 적당한 데이터를 모두 메모리 위에 올려서 처리함 - SXSSFWorkBook() : 쓰기만 가능, 1만 행 이상의 많은 데이터가 있을 경우 OOM 발생을 피하기 위해 영구 디스크와 협업하여 페이징 처리함 - domain > download > DownloadService.java : 객체 생성 및 리턴 public byte[] downloadXlsx() throws IOException { // 엑셀 Workbook 객체 생성 Workbook workbook = new XSSFWorkbook(); // 출력 스트림화 ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); workbook.write(outputStream); workbook.close(); // 응답 return outputStream.toByteArray(); } throws IOException 추가로 Controller try/catch도 추가해야 합니다. ​ - 기타 : SXSSF 사용시 처리 단위 설정 요구 됨 Workbook workbook = new SXSSFWorkbook(100); ​ - 기타 : SXSSF 및 poi 5.2 미만 버전 dispose 처리 요구 됨 ​ 시트 생성 ​ 엑셀 파일 객체 내부에 데이터를 담을 시트를 채워보겠습니다. - domain > download > DownloadService.java // 시트 추가 Sheet sheet1 = workbook.createSheet("Sheet1"); Sheet sheet2 = workbook.createSheet("Sheet2"); Sheet sheet3 = workbook.createSheet("Sheet3"); ​ 시트에 데이터 넣기 ​ - domain > download > DownloadService.java Row sheet1_row0 = sheet1.createRow(0); sheet1_row0.createCell(0).setCellValue("안녕1"); sheet1_row0.createCell(1).setCellValue("안녕2"); for (int i = 1; i < 11; i++) { Row sheet1_row = sheet1.createRow(i); sheet1_row.createCell(0).setCellValue("데이터1"); sheet1_row.createCell(1).setCellValue("데이터2"); } ​ 대용량 데이터 문제 : 시간, 메모리 ​ - 시간적 문제 DB 데이터를 엑셀로 다운로드하는 로직에서 다운로드 시간에 대해 가장 큰 loss는 대부분 DB 조회입니다. 따라서 JPA의 1+N 문제나 쿼리 설계만 잘 하시면 시간적인 문제는 거의 해결됩니다. - 메모리적 문제 DB의 많은 데이터를 엑셀 파일로 만드는 과정에서 메모리가 사용됩니다. 이때 SXSSFWorkbook() 클래스만 사용하면 해당 문제가 해결됩니다. XSSFWorkbook()은 적은 용량에서는 SXSSFWorkbook() 대비 빠른 속도를 보이지만 OOM 문제가 발생할 수 있습니다. - 기타 개인적으로 외주한 프로젝트에서 약 2만건의 DB 데이터를 (JOIN이 많이 걸림) 엑셀로 내려 받는데, XSSFWorkbook()를 사용해도 OOM이 발생하지 않습니다. (EC2 t3.micro, RAM 1GB) 다운로드시 초반 잘못된 JPA 쿼리로 약 13초 가량 소요되었지만, 수정 후 3초 안으로 다운로드 됩니다. (결국 SQL 쿼리가 가장 중요 요소입니다.) ​ 주의 ​ apache poi는 하나의 workbook에 대해 멀티 쓰레드 환경을 제공하지 않으며 thread-safe하지 않습니다. 따라서 메소드 내부에서 병렬 처리를 진행하시면 안됩니다. ​ 이전 : 2. 엑셀 다운로드 환경 구축 다음 : 4. 셀 조정 및 디자인 https://youtu.be/x5-6HwwwcxY 88, 스프링 부트 엑셀 > 4. 셀 조정 및 디자인 셀 조정 및 디자인 ​ 시트 내부의 셀들을 병합하거나, 디자인적인 요소를 추가하는 메소드를 알아보겠습니다. ​ 셀 병합 ​ 시트.addMergedRegion(new CellRangeAddress(시작행, 시작열, 끝행, 끝열)); sheet2.addMergedRegion(new CellRangeAddress(0, 0, 1, 1)); ​ 셀 디자인 ​ - 스타일 객체 생성 CellStyle style1 = workbook.createCellStyle(); ​ - 스타일 객체에 스타일 요소들 추가 // 배경색 style1.setFillForegroundColor(IndexedColors.LIGHT_YELLOW.getIndex()); style1.setFillPattern(FillPatternType.SOLID_FOREGROUND); // 테두리 스타일 style1.setBorderTop(BorderStyle.THICK); style1.setBorderBottom(BorderStyle.THICK); style1.setBorderLeft(BorderStyle.THICK); style1.setBorderRight(BorderStyle.THICK); // 테두리 색상 style1.setTopBorderColor(IndexedColors.RED.getIndex()); style1.setBottomBorderColor(IndexedColors.BLUE.getIndex()); style1.setLeftBorderColor(IndexedColors.GREEN.getIndex()); style1.setRightBorderColor(IndexedColors.PINK.getIndex()); ​ - 특정 셀에 지정 (여러 셀이면 반복 수행) Row sheet2_row1 = sheet2.createRow(1); Cell sheet2_row1_cell0 = sheet2_row1.createCell(0); sheet2_row1_cell0.setCellValue("데이터"); sheet2_row1_cell0.setCellStyle(style1); ​ 글자 디자인 ​ - 스타일 객체 생성 CellStyle style1 = workbook.createCellStyle(); ​ - 스타일 객체에 스타일 요소들 추가 // 폰트 설정 Font font = workbook.createFont(); font.setFontHeightInPoints((short)14); // 폰트 크기 font.setBold(true); // 굵게 font.setItalic(true); // 이탤릭 font.setColor(IndexedColors.BLUE.getIndex()); // 폰트 색상 style1.setFont(font); // 글자 정렬 style1.setAlignment(HorizontalAlignment.CENTER); // 가로 정렬 style1.setVerticalAlignment(VerticalAlignment.CENTER); // 세로 정렬 ​ - 특정 셀에 지정 (여러 셀이면 반복 수행) Row sheet2_row1 = sheet2.createRow(1); Cell sheet2_row1_cell0 = sheet2_row1.createCell(0); sheet2_row1_cell0.setCellValue("데이터"); sheet2_row1_cell0.setCellStyle(style1); ​ 필터 : 자동 필터 ​ 시트.setAutoFilter(new CellRangeAddress(시작행, 시작열, 끝행, 끝열)); sheet3.setAutoFilter(new CellRangeAddress(0, 0, 1, 1)); ​ 기타 ​ ChatGPT가 전문적으로 알려줍니다. ​ 이전 : 3. 엑셀 내부 데이터 생성 다음 : 5. 엑셀 업로드 환경 구축 https://youtu.be/hZhym7kLCK4 89, 스프링 부트 엑셀 > 5. 엑셀 업로드 환경 구축 Service 클래스 ​ 엑셀 업로드 후 값들을 읽을 서비스단의 대략적인 틀을 만들어 두겠습니다. - domain > download > service > UploadService.java @Service public class UploadService { public void uploadXlsx(MultipartFile file) throws IOException { } } ​ Controller 클래스 ​ 파일을 업로드할 VIEW단과 파일을 받을 엔드포인트 매핑 생성하겠습니다. - upload.mustache
​ - api > UploadController.java @Controller public class UploadController { private final UploadService uploadService; public UploadController(UploadService uploadService) { this.uploadService = uploadService; } @GetMapping("/upload") public String uploadPage() { return "upload"; } @PostMapping("/upload") public String uploadProcess(@RequestParam("file") MultipartFile file) throws IOException { uploadService.uploadXlsx(file); return "redirect:/upload"; } } ​ 파일 업로드 MB 설정 ​ 업로드 파일 허용 용량을 설정하셔야 대용량 파일도 업로드할 수 있습니다. - application.properties spring.servlet.multipart.max-file-size=25MB spring.servlet.multipart.max-request-size=25MB ​ 각각 "단일 파일"/ "전체 파일(2개 이상 업로드시 총합)" ​ 이전 : 4. 셀 조정 및 디자인 다음 : 6. 소규모 데이터 읽기 https://youtu.be/c7p1QwChonU 90, 스프링 부트 엑셀 > 6. 소규모 데이터 읽기 읽기 스트림 객체 생성 ​ - domain > upload > UploadService.java public void uploadXlsx(MultipartFile file) throws IOException { InputStream inputStream = file.getInputStream(); // 엑셀 파일 객체 읽기 Workbook workbook = new XSSFWorkbook(inputStream); } ​ 시트 읽기 ​ - domain > upload > UploadService.java // 시트 정보 int sheetCount = workbook.getNumberOfSheets(); // 시트 개수 for (int i = 0; i < workbook.getNumberOfSheets(); ++i) { // 시트 이름 출력 Sheet sheet = workbook.getSheetAt(i); System.out.println(sheet.getSheetName()); } // 특정 시트 선택 Sheet sheet = workbook.getSheetAt(0); ​ 시트별 데이터 읽기 : 반복문 ​ - domain > upload > UploadService.java // 시트 읽기 (시트 개수만큼 반복문으로 개수 만큼 돌려서 처리하는 케이스 많음) Sheet sheet = workbook.getSheetAt(0); // 시트별 데이터 처리 for (Row row : sheet) { for (Cell cell : row) { System.out.println(cell); } System.out.println(); } ​ 문제는 : XSSFWorkbook ​ 앞서 다운로드 영상에서 말씀드린 부분으로 XSSFWorkbook 객체에서 데이터가 많으면 OOM이 발생합니다. 이 때문에 간편하게 사용할 수 있는 XSSFWorkbook을 대용량 데이터에서는 사용할 수 없습니다. ​ 해결책으로 JAVA의 Simple API for XML(SAX)를 활용해야 합니다. ​ 이전 : 5. 엑셀 업로드 환경 구축 다음 : 7. 대규모 데이터 읽기 SAX https://youtu.be/6rIboFI3-ug 91, 스프링 부트 엑셀 > 7. 대규모 데이터 읽기 SAX Simple API for XML ​ SAX는 XML 문서를 읽고 처리하기 위한 이벤트 기반 XML 파서입니다. 엑셀 파일을 다루는데 갑작스럽게 XML이 등장하는데, 이는 엑셀 파일도 XML 기반이기 때문입니다. XML이 압축된 xlsx을 XSSFWorkbook은 압축 해제 후 모두 메모리에 적재하지만, SAX 방식은 한줄씩 처리하게 됩니다. 구현은 ZIP을 읽는 OPC 부분, 시트를 읽는 SAX 핸들러 부분 2가지로 진행합니다. OPC로 zip 읽기 ​ - domain > upload > service > UploadService.java OPCPackage pkg = OPCPackage.open(file.getInputStream()); XSSFReader xssfReader = new XSSFReader(pkg); ​ 시트 정보 출력 ​ - domain > upload > service > UploadService.java List sheetNames = getSheetNames(pkg); System.out.println(sheetNames.size()); for (String name : sheetNames) { System.out.println(name); } ​ - 필드 메소드 private List getSheetNames(OPCPackage pkg) throws Exception { List names = new ArrayList<>(); InputStream workbookXml = pkg.getPartsByName(Pattern.compile("/xl/workbook.xml")).get(0).getInputStream(); XMLReader parser = SAXParserFactory.newInstance().newSAXParser().getXMLReader(); parser.setContentHandler(new DefaultHandler() { @Override public void startElement(String uri, String localName, String name, Attributes attributes) { if ("sheet".equals(name)) { names.add(attributes.getValue("name")); } } }); parser.parse(new InputSource(workbookXml)); return names; } ​ 시트 객체 받기 ​ iter로 각각의 Sheet가 담겨 있기 때문에 next()로 순회해야 합니다. 그리고 공통 문자열 데이터도 가져옵니다. - domain > upload > service > UploadService.java // 첫 번째 시트 가져오기 (iter라서 next로 다음 다음 가져오면 됨) InputStream sheetStream = xssfReader.getSheetsData().next(); // 공통 문자열 테이블 가져오기 (공통 문자열을 위의 개별 시트에 저장하지 않고 공통으로 저장) SharedStrings sst = xssfReader.getSharedStringsTable(); SharedStringsTable sstTable = (SharedStringsTable) sst; ​ SAX 파싱 단계를 위한 SAX 핸들러 추가 ​ 이제 각 시트를 SAX 방식으로 파싱합니다. XML을 한 줄 씩 읽으며 태그가 찾아질때 이벤트로 핸들러를 호출합니다. - domain > upload > service > UploadService.java XMLReader parser = SAXParserFactory.newInstance().newSAXParser().getXMLReader(); parser.setContentHandler(new SheetHandler(sstTable)); ​ 호출할 핸들러 지정, SheetHandler()는 작성해야 합니다. - domain > upload > service > SheetHandler.java import org.apache.poi.xssf.model.SharedStringsTable; import org.xml.sax.Attributes; import org.xml.sax.helpers.DefaultHandler; public class SheetHandler extends DefaultHandler { private final SharedStringsTable sst; private String lastContents = ""; private boolean isString = false; public SheetHandler(SharedStringsTable sst) { this.sst = sst; } @Override public void startElement(String uri, String localName, String name, Attributes attributes) { if ("c".equals(name)) { String type = attributes.getValue("t"); isString = "s".equals(type); } lastContents = ""; } @Override public void characters(char[] ch, int start, int length) { lastContents += new String(ch, start, length); } @Override public void endElement(String uri, String localName, String name) { if ("v".equals(name)) { if (isString) { int idx = Integer.parseInt(lastContents); lastContents = sst.getItemAt(idx).getString(); } System.out.print(lastContents + "\t"); } if ("row".equals(name)) { System.out.println(); } } } ​ - domain > upload > service > UploadService.java : 파싱 시작 parser.parse(new InputSource(sheetStream)); ​ 기타 : 메소드 전체 ​ - domain > upload > service > UploadService.java > uploadXlsx() public void uploadXlsx(MultipartFile file) throws Exception { OPCPackage pkg = OPCPackage.open(file.getInputStream()); XSSFReader xssfReader = new XSSFReader(pkg); // 시트 정보 (개수, 이름) List sheetNames = getSheetNames(pkg); System.out.println(sheetNames.size()); for (String name : sheetNames) { System.out.println(name); } // 첫 번째 시트 가져오기 (iter라서 next로 다음 다음 가져오면 됨) InputStream sheetStream = xssfReader.getSheetsData().next(); // 공통 문자열 테이블 가져오기 (공통 문자열을 위의 개별 시트에 저장하지 않고 공통으로 저장) SharedStrings sst = xssfReader.getSharedStringsTable(); SharedStringsTable sstTable = (SharedStringsTable) sst; // SAX 파서 설정 XMLReader parser = SAXParserFactory.newInstance().newSAXParser().getXMLReader(); parser.setContentHandler(new SheetHandler(sstTable)); // 파싱 시작 parser.parse(new InputSource(sheetStream)); } ​ 기타 : 출력이 아니라 return으로 데이터 받기 ​ - domain > upload > service > SheetHandler.java public class SheetHandler extends DefaultHandler { private final SharedStringsTable sst; private String lastContents = ""; private boolean isString = false; private List currentRow = new ArrayList<>(); private final List> allRows = new ArrayList<>(); public SheetHandler(SharedStringsTable sst) { this.sst = sst; } public List> getRows() { return allRows; } @Override public void startElement(String uri, String localName, String name, Attributes attributes) { if ("c".equals(name)) { String type = attributes.getValue("t"); isString = "s".equals(type); } lastContents = ""; } @Override public void characters(char[] ch, int start, int length) { lastContents += new String(ch, start, length); } @Override public void endElement(String uri, String localName, String name) { if ("v".equals(name)) { if (isString) { int idx = Integer.parseInt(lastContents); lastContents = sst.getItemAt(idx).getString(); } currentRow.add(lastContents); } else if ("row".equals(name)) { allRows.add(new ArrayList<>(currentRow)); currentRow.clear(); } } } ​ - domain > upload > service > UploadService.java > uploadXlsx() : 호출 부분 // 파서 및 핸들러 등록 XMLReader parser = SAXParserFactory.newInstance().newSAXParser().getXMLReader(); SheetHandler handler = new SheetHandler(sstTable); parser.setContentHandler(handler); parser.parse(new InputSource(sheetStream)); List> rows = handler.getRows(); for (List row : rows) { System.out.println(row); } ​ 이전 : 6. 소규모 데이터 읽기 https://youtu.be/VP_HlWPD8JQ 92, 스프링 부트에 세션 방식의 스프링 시큐리티를 적용하고 인증/인가를 구현하는 방법 ​ 스프링 시큐리티 6 ​ 1. 실습 목표 및 간단한 동작 원리 2. 프로젝트 생성 3. Security Config 클래스 기타. 시큐리티 버전별 구현 방법 4. 커스텀 로그인 5. BCrypt 암호화 메소드 6. DB 연결 7. 회원 가입 로직 기타. 회원 중복 검증 및 처리 로직 8. DB기반 로그인 검증 로직 9. 세션 정보 10. 세션 설정 11. CSRF 설정 12. InMemory 유저 정보 저장 13. HttpBasic 인증 14. Role Hierarchy ​ deprecated 대처 ​ Role Hierarchy 6.3.x 이후 버전 Deprecated ​ ​ 93, 스프링 시큐리티 6 > Role Hierarchy 6.3.x Deprecated 대처 이슈 ​ Role Hierarchy의 구현 방식이 스프링 시큐리티 6.3.x 버전대에서 변경되었습니다. 기존 영상에서는 아래와 같은 구현을 예시로 올려두었지만, 현재는 Deprecated 표시가 발생합니다. - 6.3.x 이후 버전에서 사용 불가능한 구현 @Bean public RoleHierarchy roleHierarchy() { RoleHierarchyImpl hierarchy = new RoleHierarchyImpl(); hierarchy.setHierarchy("ROLE_C > ROLE_B\n" + "ROLE_B > ROLE_A"); return hierarchy; } ​ ​ 해결 ​ 기존 new로 생성해야 하는 부분이 static으로 변경되어 있다. 아래 공식 코드를 통해 확인 가능. ​ https://github.com/spring-projects/spring-security/blob/main/core/src/main/java/org/springframework/security/access/hierarchicalroles/RoleHierarchyImpl.java spring-security/core/src/main/java/org/springframework/security/access/hierarchicalroles/RoleHierarchyImpl.java at main · spring-projects/spring-security Spring Security. Contribute to spring-projects/spring-security development by creating an account on GitHub. github.com ​ - 변경된 RoleHierarchyImpl() 방식 사용 : fromHierarchy 메소드 활용 @Bean public RoleHierarchy roleHierarchy() { return RoleHierarchyImpl.fromHierarchy(""" ROLE_C > ROLE_B ROLE_B > ROLE_A """); } - 메소드 형식 : 명시적으로 접두사 작성 @Bean public RoleHierarchy roleHierarchy() { return RoleHierarchyImpl.withRolePrefix("접두사_") .role("C").implies("B") .role("B").implies("A") .build(); } ​ - 메소드 형식 : 자동으로 ROLE_ 접두사 붙임 @Bean public RoleHierarchy roleHierarchy() { return RoleHierarchyImpl.withDefaultRolePrefix() .role("C").implies("B") .role("B").implies("A") .build(); } ​ - 테스트 2024.07.26 : 스프링 부트 3.3.1 (시큐리티 6.3.1) 기준 올바르게 동작 ​ https://youtu.be/3nmmMKZHhUs 94, 스프링 시큐리티 6 > 1. 실습 목표 및 간단한 동작 원리 실습 목표 ​ 스프링 시큐리티 6 프레임워크를 활용하여 인증/인가를 구현하고 회원 정보 저장(영속성)은 MySQL 데이터베이스를 활용하여 구현한다. ​ 구현 ​ - 인증 : 로그인 - 인가 : 경로별 접근 권한 - 회원가입 ​ 시큐리티 동작 원리 ​ (모식화 시킨 그림으로 완벽하게 동작 원리와 동일하지 않습니다. 정확한 동작 원리를 위해서는 “스프링 시큐리티 내부 구조” 시리즈를 참조 부탁드립니다.) ​ “스프링 시큐리티 내부 구조” 시리즈 바로가기 스프링 시큐리티 내부 구조 스프링 시큐리티 내부 동작 원리와 구조를 학습하는 시리즈입니다. www.youtube.com ​ 버전 ​ - Spring Boot 3.1.5 - Security 6.1.5 - Spring Data JPA - MySQL - mustache - IntelliJ Ultimate ​ 다음 : 2. 프로젝트 생성 https://youtu.be/y0PXQgrkb90 95, 스프링 시큐리티 6 > 2. 프로젝트 생성 의존성 ​ https://start.spring.io/ {"_links":{"gradle-project":{"href":"https://start.spring.io/starter.zip?type=gradle-project{&dependencies,packaging,javaVersion,language,bootVersion,groupId,artifactId,version,name,description,packageName}","templated":true},"gradle-project-kotlin":{"href":"https://start.spring.io/starter.zip?type=... start.spring.io ​ - 필수 의존성 - Spring Web - Lombok - Mustache - Spring Security - Spring Data JPA - MySQL Driver ​ 데이터베이스 의존성 ​ 임시로 주석처리 ​ main 페이지 ​ - MainController package com.example.testsecurity.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; @Controller public class MainController { @GetMapping("/") public String mainP() { return "main"; } } - main.mustache Main Page main page ​ 이전 : 1. 실습 목표 및 간단한 동작 원리 다음 : 3. Security Config 클래스 https://youtu.be/qnDdx8XdKwY 96, 스프링 시큐리티 6 > 3. Security Config 클래스 ​ 인가 ​ 특정한 경로에 요청이 오면 Controller 클래스에 도달하기 전 필터에서 Spring Security가 검증을 함 1. 해당 경로의 접근은 누구에게 열려 있는지 2. 로그인이 완료된 사용자인지 3. 해당되는 role을 가지고 있는지 ​ Security Configuration ​ 인가 설정을 진행하는 클래스 ​ (엄밀하게 정의하면 SecurityFilterChain 설정을 진행함) ​ 시큐리티 Config 클래스 작성 ​ 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.web.SecurityFilterChain; @Configuration @EnableWebSecurity public class SecurityConfig { @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception{ http .authorizeHttpRequests((auth) -> auth .requestMatchers("/", "/login").permitAll() .requestMatchers("/admin").hasRole("ADMIN") .requestMatchers("/my/**").hasAnyRole("ADMIN", "USER") .anyRequest().authenticated() ); return http.build(); } } ​ 추가 페이지 생성 ​ - 어드민 ​ 이전 : 2. 프로젝트 생성 다음 : 4. 커스텀 로그인 https://youtu.be/ov84EoU0KAE 97, 스프링 시큐리티 6 > 기타. 시큐리티 버전별 구현 방법 시큐리티 버전별 특성 ​ 스프링은 버전에 따라 구현 방식이 변경되는데 시큐리티의 경우 특히 세부 버전별로 구현 방법이 많이 다르기 때문에 버전 마다 구현 특징을 확인해야 한다. 새로운 버전이 출시될 때마다 GitHub의 Spring 리포지토리에서 Security의 Release 항목을 통해 변경된 점을 확인할 수 있다. 스프링 시큐리티 GitHub 릴리즈 노트 바로가기 ​ 주요 버전별 구현 ​ - 스프링 부트 2.X.X ~ 2.6.X (스프링 5.X.X ~ 5.6.X) public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/").authenticated() .anyRequest().permitAll(); } } ​ - 스프링 부트 2.7.X ~ 3.0.X (스프링 5.7.X M2 ~ 6.0.X) public class SpringSecurityConfig { @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http .authorizeHttpRequests() .requestMatchers("/admin").hasRole("ADMIN") .anyRequest().authenticated(); return http.build(); } } ​ - 스프링 부트 3.1.X ~ (스프링 6.1.X ~ ) public class SpringSecurityConfig { @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http .authorizeHttpRequests((auth) -> auth .requestMatchers("/login", "/join").permitAll() .anyRequest().authenticated() ); return http.build(); } } ​ 3.1.X 버전 부터 람다형식 표현 필수 ​ https://youtu.be/NdRVhOccuOs 98, 스프링 시큐리티 6 > 4. 커스텀 로그인 Config 설정 후 로그인 페이지 ​ 스프링 시큐리티 Config 클래스 설정 후 특정 경로에 대한 접근 권한이 없는 경우 자동으로 로그인 페이지로 리다이렉팅 되지 않고 오류 페이지가 발생한다. 위 문제를 해결하기 위해 Config 클래스를 설정하면 로그인 페이지 설정도 진행해야 한다. ​ 커스텀 로그인 페이지 : mustache ​ - login.mustache Document login page
​ - 로그인 : 아이디, 비밀번호 POST 요청 경로 ​ LoginController ​ import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; @Controller public class LoginController { @GetMapping("/login") public String loginP() { return "login"; } } ​ Security Config 로그인 페이지 설정 및 로그인 경로 ​ 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.web.SecurityFilterChain; @Configuration @EnableWebSecurity public class SecurityConfig { @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception{ http .authorizeHttpRequests((auth) -> auth .requestMatchers("/", "/login", "/loginProc").permitAll() .requestMatchers("/admin").hasRole("ADMIN") .requestMatchers("/my/**").hasAnyRole("ADMIN", "USER") .anyRequest().authenticated() ); http .formLogin((auth) -> auth.loginPage("/login") .loginProcessingUrl("/loginProc") .permitAll() ); http .csrf((auth) -> auth.disable()); return http.build(); } } ​ 이전 : 3. Security Config 클래스 다음 : 5. BCrypt 암호화 메소드 https://youtu.be/eEkV0zir9mQ 99, 스프링 시큐리티 6 > 5. BCrypt 암호화 메소드 시큐리티 암호화 ​ 스프링 시큐리티는 사용자 인증(로그인)시 비밀번호에 대해 단방향 해시 암호화를 진행하여 저장되어 있는 비밀번호와 대조한다. ​ 따라서 회원가입시 비밀번호 항목에 대해서 암호화를 진행해야 한다. 스프링 시큐리티는 암호화를 위해 BCrypt Password Encoder를 제공하고 권장한다. 따라서 해당 클래스를 return하는 메소드를 만들어 @Bean으로 등록하여 사용하면 된다. ​ 단방향 해시 암호화 ​ - 양방향 - 대칭키 - 비대칭키 - 단방향 - 해시 ​ Security Config 암호화 Bean 추가 ​ @Bean public BCryptPasswordEncoder bCryptPasswordEncoder() { return new BCryptPasswordEncoder(); } ​ 이전 : 4. 커스텀 로그인 다음 : 6. DB 연결 https://youtu.be/B03OoUVgVIA 100, 스프링 시큐리티 6 > 6. DB 연결 데이터베이스 종류와 ORM ​ 회원 정보를 저장하기 위한 데이터베이스는 MySQL 엔진의 데이터베이스를 사용한다. 그리고 접근은 Spring Data JPA를 사용한다. ​ 데이터베이스 의존성 ​ - build.gradle dependencies { implementation 'org.springframework.boot:spring-boot-starter-data-jpa' runtimeOnly 'com.mysql:mysql-connector-j' } ​ 변수 설정 ​ - application.properties spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver spring.datasource.url=jdbc:mysql://아이피:3306/데이터베이스?useSSL=false&useUnicode=true&serverTimezone=Asia/Seoul&allowPublicKeyRetrieval=true spring.datasource.username=아이디 spring.datasource.password=비밀번호 ​ DB 연결에 대한 자세한 설명 스프링 부트 데이터베이스 2 : MySQL RDB 단일 연결 유튜브 영상 바로가기 ​ 이전 : 5. BCrypt 암호화 메소드 다음 : 7. 회원 가입 로직 https://youtu.be/dIFq8Fbmx0w 101, 스프링 시큐리티 6 > 7. 회원 가입 로직 회원가입 로직 ​ 회원정보를 통해 인증 인가 작업을 진행하기 때문에 사용자로 부터 회원 가입을 진행한 뒤 데이터베이스에 회원 정보를 저장해야 한다. ​ 회원 가입 모식도 ​ ​ 회원가입 페이지 : mustache ​ - join.mustache
​ JoinDTO ​ import lombok.Getter; import lombok.Setter; @Setter @Getter public class JoinDTO { private String username; private String password; } ​ JoinController ​ import com.example.testsecurity.dto.JoinDTO; import com.example.testsecurity.service.JoinService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; @Controller public class JoinController { @Autowired private JoinService joinService; @GetMapping("/join") public String joinP() { return "join"; } @PostMapping("/joinProc") public String joinProcess(JoinDTO joinDTO) { System.out.println(joinDTO.getUsername()); joinService.joinProcess(joinDTO); return "redirect:/login"; } } ​ JoinService ​ import com.example.testsecurity.dto.JoinDTO; import com.example.testsecurity.entity.UserEntity; import com.example.testsecurity.repository.UserRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.stereotype.Service; @Service public class JoinService { @Autowired private UserRepository userRepository; @Autowired private BCryptPasswordEncoder bCryptPasswordEncoder; public void joinProcess(JoinDTO joinDTO) { //db에 이미 동일한 username을 가진 회원이 존재하는지? UserEntity data = new UserEntity(); data.setUsername(joinDTO.getUsername()); data.setPassword(bCryptPasswordEncoder.encode(joinDTO.getPassword())); data.setRole("ROLE_USER"); userRepository.save(data); } } ​ UserEntity ​ import jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; import jakarta.persistence.GenerationType; import jakarta.persistence.Id; import lombok.Getter; import lombok.Setter; @Entity @Setter @Getter public class UserEntity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; private String username; private String password; private String role; } ​ Table 생성 : Hibernate ddl 설정 ​ - application.properties spring.jpa.hibernate.ddl-auto=none spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl ​ UserRepository ​ import com.example.testsecurity.entity.UserEntity; import org.springframework.data.jpa.repository.JpaRepository; public interface UserRepository extends JpaRepository { } ​ SecurityConfig 접근 권한 ​ http .authorizeHttpRequests((auth) -> auth .requestMatchers("/", "/login", "/loginProc", "/join", "/joinProc").permitAll() .requestMatchers("/admin").hasRole("ADMIN") .requestMatchers("/my/**").hasAnyRole("ADMIN", "USER") .anyRequest().authenticated() ); ​ 이전 : 6. DB 연결 다음 : 8. DB기반 로그인 검증 로직 https://youtu.be/m9lsS36QGCk 102, 스프링 시큐리티 6 > 기타. 회원 중복 검증 및 처리 로직 회원 중복 검증 ​ username에 대해서 중복된 가입이 발생하면 서비스에서 아주 치명적인 문제가 발생하기 때문에 백엔드단에서 중복 검증과 중복 방지 로직을 작성해야 한다. ​ UserEntity Unique 설정 ​ import jakarta.persistence.*; import lombok.Getter; import lombok.Setter; @Entity @Setter @Getter public class UserEntity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; @Column(unique = true) private String username; private String password; private String role; } ​ JoinService 중복 검증 ​ - UserRepository import com.example.testsecurity.entity.UserEntity; import org.springframework.data.jpa.repository.JpaRepository; public interface UserRepository extends JpaRepository { boolean existsByUsername(String username); } ​ - JoinService import com.example.testsecurity.dto.JoinDTO; import com.example.testsecurity.entity.UserEntity; import com.example.testsecurity.repository.UserRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.stereotype.Service; @Service public class JoinService { @Autowired private UserRepository userRepository; @Autowired private BCryptPasswordEncoder bCryptPasswordEncoder; public void joinProcess(JoinDTO joinDTO) { //db에 이미 동일한 username을 가진 회원이 존재하는지? boolean isUser = userRepository.existsByUsername(joinDTO.getUsername()); if (isUser) { return; } UserEntity data = new UserEntity(); data.setUsername(joinDTO.getUsername()); data.setPassword(bCryptPasswordEncoder.encode(joinDTO.getPassword())); data.setRole("ROLE_USER"); userRepository.save(data); } } ​ join.mustache ​ 프론트단에서도 회원가입 아이디 중복 확인 로직을 추가해야 한다. httpXMLRequest 메소드를 통해 백엔드에 미리 구현해둔 API에 이미 존재하는 username인지 검증하는 로직을 추가해야 한다. 가입 불가 문자 정규식 처리 ​ 아이디, 비밀번호에 대한 정규식 처리도 필요하다. - 아이디의 자리수 - 아이디의 특수문자 포함 불가 - admin과 같은 아이디 사용 불가 - 비밀번호 자리수 - 비밀번호 특수문자 포함 필수 ​ https://youtu.be/MebrJCxjc6s 103, 스프링 시큐리티 6 > 8. DB기반 로그인 검증 로직 ​ 인증 ​ 시큐리티를 통해 인증을 진행하는 방법은 사용자가 Login 페이지를 통해 아이디, 비밀번호를 POST 요청시 스프링 시큐리티가 데이터베이스에 저장된 회원 정보를 조회 후 비밀번호를 검증하고 서버 세션 저장소에 해당 아이디에 대한 세션을 저장한다. ​ UserDetailsService ​ import com.example.testsecurity.dto.CustomUserDetails; import com.example.testsecurity.entity.UserEntity; import com.example.testsecurity.repository.UserRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Service; @Service public class CustomUserDetailsService implements UserDetailsService { @Autowired private UserRepository userRepository; @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { UserEntity userData = userRepository.findByUsername(username); if (userData != null) { return new CustomUserDetails(userData); } return null; } } ​ UserRepository ​ import com.example.testsecurity.entity.UserEntity; import org.springframework.data.jpa.repository.JpaRepository; public interface UserRepository extends JpaRepository { boolean existsByUsername(String username); UserEntity findByUsername(String username); } ​ UserDetails ​ import com.example.testsecurity.entity.UserEntity; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; import java.util.ArrayList; import java.util.Collection; public class CustomUserDetails implements UserDetails { private UserEntity userEntity; public CustomUserDetails(UserEntity userEntity) { this.userEntity = userEntity; } @Override public Collection getAuthorities() { Collection collection = new ArrayList<>(); collection.add(new GrantedAuthority() { @Override public String getAuthority() { return userEntity.getRole(); } }); return collection; } @Override public String getPassword() { return userEntity.getPassword(); } @Override public String getUsername() { return userEntity.getUsername(); } @Override public boolean isAccountNonExpired() { return true; } @Override public boolean isAccountNonLocked() { return true; } @Override public boolean isCredentialsNonExpired() { return true; } @Override public boolean isEnabled() { return true; } } ​ 이전 : 7. 회원 가입 로직 다음 : 9. 세션 정보 https://youtu.be/U3Jkuy5Hc00 104, 스프링 시큐리티 6 > 9. 세션 정보 세션 현재 사용자 아이디 ​ SecurityContextHolder.getContext().getAuthentication().getName(); ​ 세션 현재 사용자 role ​ Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); Collection authorities = authentication.getAuthorities(); Iterator iter = authorities.iterator(); GrantedAuthority auth = iter.next(); String role = auth.getAuthority(); ​ 이전 : 8. DB기반 로그인 검증 로직 다음 : 10. 세션 설정 https://youtu.be/t-TsjyBmHcQ 105, 스프링 시큐리티 6 > 10. 세션 설정 로그인 정보 ​ 사용자가 로그인을 진행한 뒤 사용자 정보는 SecurityContextHolder에 의해서 서버 세션에 관리된다. ​ 이때 세션에 관해 세션의 소멸 시간, 아이디당 세션 생성 개수를 설정하는 방법에 대해서 알아보자. ​ 세션 소멸 시간 설정 ​ 세션 타임아웃 설정을 통해 로그인 이후 세션이 유지되고 소멸하는 시간을 설정할 수 있다. 세션 소멸 시점은 서버에 마지막 특정 요청을 수행한 뒤 설정한 시간 만큼 유지된다. (기본 시간 1800초) - application.properties //초 기반 server.servlet.session.timeout=1800 //분 기반 server.servlet.session.timeout=90m ​ 다중 로그인 설정 ​ Authentication Persistence and Session Management 스프링 공식 문서 바로가기 동일한 아이디로 다중 로그인을 진행할 경우에 대한 설정 방법은 세션 통제를 통해 진행한다. ​ @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception{ http .sessionManagement((auth) -> auth .maximumSessions(1) .maxSessionsPreventsLogin(true)); return http.build(); } ​ sessionManagement() 메소드를 통한 설정을 진행한다. maximumSession(정수) : 하나의 아이디에 대한 다중 로그인 허용 개수 maxSessionPreventsLogin(불린) : 다중 로그인 개수를 초과하였을 경우 처리 방법 - true : 초과시 새로운 로그인 차단 - false : 초과시 기존 세션 하나 삭제 세션 고정 보호 ​ ​ 세션 고정 공격을 보호하기 위한 로그인 성공시 세션 설정 방법은 sessionManagement() 메소드의 sessionFixation() 메소드를 통해서 설정할 수 있다. - sessionManagement().sessionFixation().none() : 로그인 시 세션 정보 변경 안함 - sessionManagement().sessionFixation().newSession() : 로그인 시 세션 새로 생성 - sessionManagement().sessionFixation().changeSessionId() : 로그인 시 동일한 세션에 대한 id 변경 - 공식 문서 코드 @Bean public SecurityFilterChain filterChain(HttpSecurity http) { http .sessionManagement((session) - session .sessionFixation((sessionFixation) -> sessionFixation .newSession() ) ); return http.build(); } ​ - 구현 코드 @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception{ http .sessionManagement((auth) -> auth .sessionFixation().changeSessionId()); return http.build(); } ​ 이전 : 9. 세션 정보 다음 : 11. CSRF 설정 https://youtu.be/SsdDnI3bHcI 106, 스프링 시큐리티 6 > 11. CSRF 설정 CSRF란? ​ CSRF(Cross-Site Request Forgery)는 요청을 위조하여 사용자가 원하지 않아도 서버측으로 특정 요청을 강제로 보내는 방식이다. (회원 정보 변경, 게시글 CRUD를 사용자 모르게 요청) ​ 개발 환경에서 csrf disable() ​ 개발 환경에서는 Security Config 클래스를 통해 csrf 설정을 disable 설정하였다. 배포 환경에서는 csrf 공격 방지를 위해 csrf disable 설정을 제거하고 추가적인 설정을 진행해야 한다. - csrf disable 설정 구문을 추가해둔 security config 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.web.SecurityFilterChain; @Configuration @EnableWebSecurity public class SecurityConfig { @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception{ http .csrf((auth) -> auth.disable()); return http.build(); } } ​ 배포 환경에서 진행 사항 ​ security config 클래스에서 csrf.disable() 설정을 진행하지 않으면 자동으로 enable 설정이 진행된다. enable 설정시 스프링 시큐리티는 CsrfFilter를 통해 POST, PUT, DELETE 요청에 대해서 토큰 검증을 진행한다. - Security Config 클래스 설정 csrf.disable() 구문 삭제 - POST 요청에서 설정 방법 (mustache 기준)
​ - ajax 요청시 HTML 구획에 아래 요소 추가 ​ ajax 요청시 위의 content 값을 가져온 후 함께 요청 XMLHttpRequest 요청시 setRequestHeader를 통해 _csrf, _csrf_header Key에 대한 토큰 값 넣어 요청 - GET 방식 로그아웃을 진행할 경우 설정 방법 csrf 설정시 POST 요청으로 로그아웃을 진행해야 하지만 아래 방식을 통해 GET 방식으로 진행할 수 있다. - security config 클래스 로그아웃 설정 @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception{ http .logout((auth) -> auth.logoutUrl("/logout") .logoutSuccessUrl("/")); return http.build(); } ​ - LogoutController @Controller public class logoutController { @GetMapping("/logout") public String logout(HttpServletRequest request, HttpServletResponse response) throws Exception { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); if(authentication != null) { new SecurityContextLogoutHandler().logout(request, response, authentication); } return "redirect:/"; } } ​ 오류 발생시 ​ mustache에서 csrf 토큰 변수 오류 발생시 아래 구문을 변수 설정 파일에 추가 - application.properties spring.mustache.servlet.expose-request-attributes=true ​ API 서버의 경우 csrf.disable() ? ​ 앱에서 사용하는 API 서버의 경우 보통 세션을 STATELESS로 관리하기 때문에 스프링 시큐리티 csrf enable 설정을 진행하지 않아도 된다. ​ 이전 : 10. 세션 설정 다음 : 12. InMemory 유저 정보 저장 https://youtu.be/l8xjecnAzMw 107, 스프링 시큐리티 6 > 12. InMemory 유저 정보 저장 소수의 유저를 저장할 좋은 방법 ​ 토이 프로젝트를 진행하는 경우 또는 시큐리티 로그인 환경이 필요하지만 소수의 회원 정보만 가지며 데이터베이스라는 자원을 투자하기 힘든 경우는 회원가입 없는 InMemory 방식으로 유저를 저장하면 된다. ​ 이 경우 InMemoryUserDetailsManager 클래스를 통해 유저를 등록하면 된다. ​ InMemoryUserDetailsManager ​ https://docs.spring.io/spring-security/reference/servlet/authentication/passwords/in-memory.html In-Memory Authentication :: Spring Security Spring Security / Servlet Applications / Authentication / Username/Password / Password Storage / In Memory In-Memory Authentication Spring Security’s InMemoryUserDetailsManager implements UserDetailsService to provide support for username/password based authentication that is stored in memory. InMem... docs.spring.io ​ InMemory 방식 유저 저장 ​ 1~5강까지 내용 코드를 기반으로 InMemory 방식의 코들 작성한다. ​ @Configuration @EnableWebSecurity public class SecurityConfig { @Bean public UserDetailsService userDetailsService() { UserDetails user1 = User.builder() .username("user1") .password(bCryptPasswordEncoder().encode("1234")) .roles("ADMIN") .build(); UserDetails user2 = User.builder() .username("user2") .password(bCryptPasswordEncoder().encode("1234")) .roles("USER") .build(); return new InMemoryUserDetailsManager(user1, user2); } } ​ 이전 : 11. CSRF 설정 다음 : 13. HttpBasic 인증 https://youtu.be/GbTOoJ0Y5eA 108, 스프링 시큐리티 6 > 13. HttpBasic 인증 로그인 방식 ​ - formLogin - httpBasic ​ Http Basic 인증 방식 ​ Http Basic 인증 방식은 아이디와 비밀번호를 Base64 방식으로 인코딩한 뒤 HTTP 인증 헤더에 부착하여 서버측으로 요청을 보내는 방식이다. ​ 참조 ​ https://docs.spring.io/spring-security/reference/servlet/authentication/passwords/basic.html Basic Authentication :: Spring Security Spring Security / Servlet Applications / Authentication / Username/Password / Reading Username/Password / Basic Basic Authentication This section provides details on how Spring Security provides support for Basic HTTP Authentication for servlet-based applications. This section describes how HTTP Bas... docs.spring.io ​ HttpBasic 방식 인증을 위한 Config 클래스 설정 ​ formLogin() 메소드 제거 후 httpBasic() 메소드를 통해 설정 ​ @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception{ http .httpBasic(Customizer.withDefaults()); return http.build(); } ​ 이전 : 12. InMemory 유저 정보 저장 다음 : 14. Role Hierarchy https://youtu.be/7gEqj2_pcto 109, 스프링 시큐리티 6 > 14. Role Hierarchy 좋은 주제 제안 감사드립니다. ​ ​ 6.3.1 deprecated ​ 스프링 시큐리티 6.3.x 버전대로 업데이트되면서 RoleHierarchyImpl가 deprecated되며 아래 구현으로는 사용이 불가능합니다. ​ ​ https://docs.spring.io/spring-security/site/docs/current/api/org/springframework/security/access/hierarchicalroles/RoleHierarchyImpl.html#fromHierarchy(java.lang.String RoleHierarchyImpl (spring-security-docs 6.5.2 API) Package org.springframework.security.access.hierarchicalroles Class RoleHierarchyImpl java.lang.Object org.springframework.security.access.hierarchicalroles.RoleHierarchyImpl All Implemented Interfaces: RoleHierarchy public class RoleHierarchyImpl extends Object implements RoleHierarchy This class d... docs.spring.io ​ 6.3.x 이후 버전 해결 방법 ​ 자료 ​ Authorization Architecture 스프링 시큐리티 공식 문서 바로가기 ​ 계층 권한 : Role Hierarchy ​ 권한 A, 권한 B, 권한 C가 존재하고 권한의 계층은 “A < B < C”라고 설정을 진행하고 싶은 경우 RoleHierarchy 설정을 진행할 수 있다. - 기존 방식 @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception{ http .csrf((auth) -> auth.disable()); http .authorizeHttpRequests((auth) -> auth .requestMatchers("/login").permitAll() .requestMatchers("/").hasAnyRole("A", "B", "C") .requestMatchers("/manager").hasAnyRole("B", "C") .requestMatchers("/admin").hasAnyRole("C") .anyRequest().authenticated() ); http .formLogin((auth) -> auth.loginPage("/login") .loginProcessingUrl("/loginProc") .permitAll() ); return http.build(); } ​ - 계층 권한 메소드 등록 @Bean public RoleHierarchy roleHierarchy() { RoleHierarchyImpl hierarchy = new RoleHierarchyImpl(); hierarchy.setHierarchy("ROLE_C > ROLE_B\n" + "ROLE_B > ROLE_A"); return hierarchy; } ​ - 메소드 적용을 통한 ROLE 적용 @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception{ http .csrf((auth) -> auth.disable()); http .authorizeHttpRequests((auth) -> auth .requestMatchers("/login").permitAll() .requestMatchers("/").hasAnyRole("A") .requestMatchers("/manager").hasAnyRole("B") .requestMatchers("/admin").hasAnyRole("C") .anyRequest().authenticated() ); http .formLogin((auth) -> auth.loginPage("/login") .loginProcessingUrl("/loginProc") .permitAll() ); return http.build(); } ​ 이전 : 13. HttpBasic 인증 https://youtu.be/RnuSJBttJUo 111, 스프링 부트를 네이티브로 빌드하는 과정에 대해 알아보겠습니다. ​ 스프링 네이티브 GraalVM ​ 1. 시리즈 목표 2. 실습 환경 및 시연 3. 윈도우즈 환경 WSL 설치 4. gradle 네이티브 컴파일 방법 ​ 코드 ​ https://github.com/xxxjjhhh/spring_native GitHub - xxxjjhhh/spring_native: 개발자 유미 : 스프링 네이티브 개발자 유미 : 스프링 네이티브. Contribute to xxxjjhhh/spring_native development by creating an account on GitHub. github.com ​ 기타 ​ 한국 오라클 GraalVM 설명 영상 113, 스프링 네이티브 GraalVM > 1. 시리즈 목표 이번 시리즈는? ​ 스프링 네이티브는 최근 출시된 기능 (스프링 부트3 ~)으로 MSA 시대를 맞이하여 준비한다면 하나의 솔루션으로 사용하기 좋은 기능입니다. 꼭 MSA 환경이 아니라도 구성 및 동작은 가능하기 때문에 실습 정도는 좋을거 같습니다. (스프링 네이티브 도구는 음정이 없는 타악기 같은 존재로 그 자체로도 공연이 가능하지만 기타 현악기나 건반악기와 어울리면 더 좋은 화합을 낼 수 있는 그런 친구입니다.) 이번 시리즈는 약 4개의 영상이 업로드 될 예정이며, 실습 환경 구성이 매우 까다롭습니다. 따라서 상황에 따라 단계별 역량에 대해 끝까지 안가셔도 무방합니다. ​ 1. 단순하게 스프링 네이티브가 뭔지 알기 2. GraalVM과 native-image란? 3. 환경 구성 방법 4. 네이티브 실행 파일 생성 5. 네이티브 컨테이너 이미지 생성 ​ Spring Native란? ​ 쉽게 말해 스프링을 실행 파일로 배포해 JVM 환경 없이 바로 실행 시킬 수 있도록 만드는 방법입니다. AOT, JIT 여러가지 아키텍처를 알아야 하는 부분이 많은데 결과적으론 jar 파일 대비 실행 시간이 기하급수적으로 줄어듭니다. ​ jar 파일은 아이들까지 20초 걸리는 상황이라면 실행 파일은 1초만에 배포되기 때문에 빠른 배포가 불가능하지만 네이티브는 가능하기 때문에 아래와 같은 이점이 있습니다. ​ 스프링 네이티브로 가져올 수 있는 이점 ​ MSA를 구성하면서 보통 하나의 도메인에 대한 컨테이너 이미지를 만들고 트래픽의 크기에 따른 오토스케일링을 진행합니다. ​ ​ 급격하게 많은 트래픽이 쏟아질 경우 컨테이너 이미지를 통해 추가 인스턴스를 열어야하는데 jar기반 컨테이너의 경우 아이들까지의 실행시간이 존재하기 때문에 네이티브 기반 컨테이너로 교체할 경우 급격한 트래픽을 받아 서비스를 안전하게 운용할 수 있습니다. ​ 스프링 네이티브 단점 ​ 추후에 알려드릴 AOT, JIT이라는 컴파일러 개념이 있습니다. 기존의 경우 JIT 방식으로 런타임에서 코드 최적화를 통한 컴파일을 수행하는 방식인데 네이티브 이미지의 경우 이 방식이 불가능하기 때문에 동적과 관련된 여러 라이브러리 사용이 불가능합니다. ​ 다음 : 2. 실습 환경 및 시연 https://youtu.be/E451K6Q0Ygw 114, 스프링 네이티브 GraalVM > 2. 실습 환경 및 시연 제가 3주간 테스트하고 reflect-config.json도 다 뜯었는데, 안되는 케이스가 너무 많습니다. 되도록 사용하지 않는 것을 추천드립니다. 의존성 ​ https://start.spring.io/ {"_links":{"gradle-project":{"href":"https://start.spring.io/starter.zip?type=gradle-project{&dependencies,packaging,javaVersion,language,bootVersion,groupId,artifactId,version,name,description,packageName}","templated":true},"gradle-project-kotlin":{"href":"https://start.spring.io/starter.zip?type=... start.spring.io ​ - 자바 버전 - 17 - 빌드 도구 - Gradle - 필수 의존성 - GraalVM Native Support - 선택 의존성 - Lombok - Spring Web - Spring Security - Spring Data JPA - MySQL Driver ​ GraalVM 환경 ​ 자바 프로그램을 가동하기 위해선 JVM 환경이 요구됩니다. JVM을 제공하는 여러 기업이 있지만 그 중 Oracle에서 Oracle JDK와 별개로 신기술을 적용한 JVM인 GraalVM을 제공하고 있습니다. 네이티브 환경의 스프링을 배포하기 위해선 GraalVM 환경이 필수적으로 요구되기 때문에 GraalVM 환경을 구성하셔야 합니다. 개발 환경의 경우 필수가 아니지만 네이티브로 빌드하기 위한 환경은 필수적으로 요구 됩니다. 이번 시리즈 빌드용 GraalVM 버전은 아래와 같습니다. ​ graalvm 22.0.2 ​ 프로젝트 작성과 주의점 ​ https://docs.spring.io/spring-boot/reference/packaging/native-image/introducing-graalvm-native-images.html Introducing GraalVM Native Images :: Spring Boot Spring Boot / Reference / Packaging Spring Boot Applications / GraalVM Native Images / Introducing GraalVM Native Images Introducing GraalVM Native Images GraalVM Native Images provide a new way to deploy and run Java applications. Compared to the Java Virtual Machine, native images can run with a s... docs.spring.io ​ 기존 JDK 환경에서 동작하던 스프링의 모든 의존성과 구현이 네이티브 빌딩 과정에서는 안되는 경우가 있습니다. 네이티브 빌드를 위해 특정 설정이 필요한데 현재 스프링의 메이저한 의존성들은 자동 설정이 되지만 마이너한 의존성의 경우 안되는 경우가 많고, @Profile과 같은 어노테이션 사용이 불가능합니다. ​ 네이티브 빌드 방법 ​ Gradle 빌드 환경에서 네이티브로 빌드 할 수 있는 방법은 2가지가 존재합니다. - nativeCompile 실행 파일로 빌드하는 방법 - bootBuildImage 실행 파일을 포함한 도커 이미지로 빌드하는 방법 ​ 이전 : 1. 시리즈 목표 다음 : 3. 윈도우즈 환경 WSL 설치 https://youtu.be/6A6cOvoydaM 115, 스프링 네이티브 GraalVM > 3. 윈도우즈 환경 WSL 설치 네이티브 빌드 스펙 ​ 스프링을 네이티브로 빌드하기 위해선 까다로운 스펙이 요구됩니다. - 소프트웨어 스펙 ​ 우선 윈도우즈 환경은 구성 가능하지만 설정할 부분이 매우 많고 안돌아가는 경우도 많기 때문에 리눅스 환경을 99% 추천 드립니다. 이번 시리즈에서는 우분투 22.04 환경을 사용하도록 하겠습니다. (버전은 크게 상관 없습니다.) - 하드웨어 스펙 ​ AWS EC2 환경을 체택하려 했으나 t2.micro ~ t3.large 환경까지 테스트한 결과 CPU 부하로 인해 빌드가 모두 실패했습니다. ​ I7-13세대 환경에서도 CPU 부하율이 1분간 100%를 차지하기 때문에 상당히 좋은 수준의 CPU가 요구됩니다. 대략적인 테스트 결과 램은 최소 8GB 이상, CPU는 I3-13세대 이상의 성능을 추천드립니다. (매우 안좋은 최적화 상태를 보입니다.) ​ WSL 필요 ​ 대부분의 시청자분들은 윈도우즈 환경을 사용하실거라 예상합니다. 빌드를 위해 리눅스를 준비해야하는데 클라우드 환경은 실패하는 경우가 많기 때문에 윈도우즈 환경 위에 가상화 리눅스를 올리는 WSL을 통해 우분투 22.04를 설치하도록 하겠습니다. 성능 좋은 리눅스나 맥 환경을 소유하신 시청자분들은 WSL 설치 과정이 필요 없습니다. !!!! 무조건 윈도우즈 프로 버전이 필요합니다, 홈 에디션 설치 불가!!!! ​ 윈도우즈 기본 설정 ​ - Hyper-V 활성화 확인 : 가상화 : 사용 ​ ​ - Linux용 Windows 하위 시스템 활성 1. 윈도우즈 검색에서 : "Windows 기능 켜기/끄기" 검색 2. 제어판 → 프로그램 → "Windows 기능 켜기/끄기" ​ ​ WSL 설치 ​ - POWERSHELL 관리자 모드 실행 - 설치 명령어 입력 wsl --install ​ WSL 명령어 안먹는 경우 ​ 지옥이 시작됩니다. - CMD 관리자 권한 실행 dism.exe /online /enable-feature /featurename:Microsoft-Windows-Subsystem-Linux /all /norestart dism.exe /online /enable-feature /featurename:VirtualMachinePlatform /all /norestart ​ - 재부팅 - POWERSHELL 관리자 권한 실행 Enable-WindowsOptionalFeature -Online -FeatureName Microsoft-Windows-Subsystem-Linux 시간 어느정도 소요 ​ ​ - 재부팅 ​ WSL에 우분투 설치 ​ - 리눅스 목록 확인 wsl --list --online ​ - 우분투 22.04 버전 설치 wsl --install Ubuntu-22.04 ​ - 아이디 입력 - 비밀번호 2회 입력 (없으면 엔터키) ​ 접속 ​ - 설치된 목록 확인 wsl -l -v ​ - 접속 wsl -d Ubuntu-22.04 ​ 설치된 리눅스 제거 ​ wsl --unregister Ubuntu-22.04 ​ 이전 : 2. 실습 환경 및 시연 다음 : 4. gradle 네이티브 컴파일 방법 https://youtu.be/5tDddRjFNeo 116, 스프링 네이티브 GraalVM > 4. gradle 네이티브 컴파일 방법 프로젝트 작성 완료 ​ GraalVM Native Support 의존성을 추가한 뒤 스프링 프로젝트를 만드셨다면, 네이티브로 빌드를 진행할 수 있습니다. ​ 네이티브 빌드 방식 ​ 2강 영상에 설명드린 내용처럼 2가지 방법으로 빌드할 수 있고 각 방식의 과정과 결과는 아래와 같습니다. - nativeCompile 실행 파일로 빌드하는 방식 - bootBuildImage 실행 파일을 포함한 도커 이미지로 빌드하는 방식 두 방법에 대해서 기본적인 리눅스 빌드 환경을 구성하는 방식은 거의 동일하며 bootBuildImage의 경우에만 후반부에 추가적으로 build.gradle 및 docker 설정 부분이 요구됩니다. ​ 프로젝트를 리눅스 환경으로 이동 ​ 방법1 : git repository에 업로드 후 다운로드 방식 방법2 : scp 명령어를 통한 전송 이후 바로 빌드 명령어인 아래 명령을 입력하면 환경 구성이 없기 때문에 실행되지 않습니다. ​ ./gradlew nativeCompile ./gradlew bootBuildImage 리눅스 빌드 환경 구성 ​ 초반부는 natvieCompile과 bootBuildImage가 동일합니다. - apt 업데이트 및 기본적인 gcc 설치 sudo apt update sudo apt install build-essential zlib1g-dev unzip -y ​ - graalVM 환경 설치 https://www.graalvm.org/downloads/# Download GraalVM Download Oracle GraalVM Java 24 Choose a platform Download GitHub Actions Container Images SDKMAN! Script-friendly URLs Paketo Buildpack sdk install java 24.0.2-graal # coming soon SDKMAN! is a popular tool that helps you install and switch between JDKs, including GraalVM . Oracle GraalVM is free t... www.graalvm.org wget https://download.oracle.com/graalvm/22/latest/graalvm-jdk-22_linux-x64_bin.tar.gz sudo tar -xzf graalvm-jdk-22_linux-x64_bin.tar.gz sudo mv graalvm-jdk-22.0.2+9.1 /usr/lib/graalvm 1. wget 또는 curl로 다운로드 2. 다운로드한 파일 tar로 압축 해제 3. 압축해제한 폴더를 /usr/lib/ 경로로 이동 ​ - Java 환경 변수 설정 ​ java 명령어를 사용하여 graalVM을 부를 수 있도록 환경 변수 설정 (상단에서 3번에 이동한 경로로 설정 진행) export GRAALVM_HOME=/usr/lib/graalvm export JAVA_HOME=$GRAALVM_HOME export PATH=$JAVA_HOME/bin:$PATH java -version native-image --version ​ (우리는 native-image를 통해 스프링 프로젝트를 네이티브 빌드하기 때문에 같이 설치가 되었는지 꼭 확인이 필요합니다. 과거 버전이 경우는 gu라는 JDK 설치 도구를 통해 추가 설치를 해야하지만 현재는 포함되어 있습니다.) ./gradlew nativeCompile ​ 실행 파일로 구성하는 방법 우리의 스프링 프로젝트 경로로 진입 후 gradlew 파일이 존재하는 곳에서 - 빌드 진행 ./gradlew nativeCompile ​ ​ ​ - 결과 프로젝트 내부 아래 경로에서 확인 가능 ​ /build/native/nativeCompile ​ ./gradlew bootBuildImage ​ 실행 파일을 포함한 도커 이미지로 구성하는 방법 여기서는 추가로 build.gradle 값 추가와 우분투에 Docker 환경을 설치하셔야 합니다. - build.gradle 명령어 추가 bootBuildImage { imageName = 'nativetest' } 소문자만 지원되며 빌드 후 도커 이미지 이름 값으로 부여됩니다. ​ - Docker 설치 sudo apt install apt-transport-https ca-certificates curl software-properties-common curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add - sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable" sudo apt update sudo apt install docker-ce sudo systemctl status docker ​ - Docker 소켓에 권한 부여 (gradlew에서 접근을 위함) sudo chmod 777 /var/run/docker.sock ​ - 빌드 진행 ./gradlew bootBuildImage ​ ​ ​ - 결과 docker images ​ 이전 : 3. 윈도우즈 환경 WSL 설치 https://youtu.be/yncBMm85sa4 117, 스프링 부트 (Spring Boot) 3와 리액트 (React.js) 19 환경에서 인증/인가 (자체/소셜 로그인, 다중 JWT) 환경을 구현하는 프로젝트 ​ 스프링 + 리액트 로그인 ​ 1. 목표 및 환경 구축 2. 백엔드 : 구조 설명 및 DB 연결 3. 백엔드 : User 도메인용 Entity 4. 백엔드 : UserService 메소드 작성 1 5. 백엔드 : 자체 로그인 설정 6. 백엔드 : JWT Util 클래스 등록 7. 백엔드 : Jwt 도메인용 Entity 8. 백엔드 : JwtService 메소드 작성 1 9. 백엔드 : 자체 로그인 성공 핸들러 10. 백엔드 : User API 작성 및 로그인 11. 백엔드 : 소셜 로그인 설정 12. 백엔드 : UserService 메소드 작성 2 13. 백엔드 : JWTFilter 14. 백엔드 : JwtService 메소드 작성 2 15. 백엔드 : CORS 및 기타 설정 16. 프론트 : 프로젝트 정리 17. 프론트 : 로그인 페이지 18. 프론트 : 소셜 로그인 페이지 19. 프론트 : 유저 정보 페이지 20. ​ ​ 코드 ​ https://github.com/xxxjjhhh/spring_react_login 118, 스프링 + 리액트 로그인 > 1. 목표 및 환경 구축 시리즈 목표 ​ 개발자 유미 채널에는 스프링 시큐리티 관련 시리즈가 많습니다. "스프링 시큐리티", "스프링 시큐리티 JWT", "스프링 OAuth2", "스프링 JWT 심화" 하지만 각각을 시청하신 후 이것을 응용하여 토이 프로젝트에 진입하기는 매우 어렵습니다. 따라서 스프링 + 리액트 환경에서 아래 목표를 가지고 로그인 시스템 토이 프로젝트를 구현하겠습니다. ​ - 목표 - 스프링 부트 3 기반 RESTful 서버 구축 (STATELESS) - 리액트 19 기반 LocalStorage JWT 저장 - 자체/소셜(네이버, 구글) 로그인 - Access/Refresh 토큰 ​ 스프링 부트 프로젝트 생성 ​ 몇 가지 의존성을 추가하여 스프링 부트 3 기반 프로젝트를 생성하겠습니다. ​ ​ ​ React.js 프로젝트 생성 ​ Node.js/npm 환경이 구축되어 있어야 합니다. ​ - npm으로 vite 기반 React.js 프로젝트 생성 npm create vite@latest frontend -- --template react ​ - 생성한 frontend 경로로 이동 cd frontend ​ - 패키지 설치 npm install ​ - 실행 npm run dev ​ 다음 : 2. 백엔드 : 구조 설명 및 DB 연결 https://youtu.be/nMSFHreQdbU 122, 스프링 + 리액트 로그인 > 2. 백엔드 : 구조 설명 및 DB 연결 진행 ​ 백엔드 설계를 우선적으로 진행하면서 프론트로 넘어가겠습니다. ​ 기능 : 예상되는 API ​ - 회원 - C : 회원 가입 - R : 유저 정보 조회 - R : 로그인 - 자체 - 소셜 - U : 유저 정보 수정 - D : 유저 삭제 - JWT - Refresh Rotate - OAuth2 cookie -> header 구조 설명 : 모식도 ​ ​ DB 연결 : application.properties ​ 설계는 가장 뒤쪽 부터 진행하는게 좋습니다. 데이터베이스를 우선적으로 구성하고 스프링 부트에 연결하겠습니다. ​ - MySQL 데이터베이스 빌리기 https://youtu.be/QQjZ3oOIHJM?si=UhIE6SL85iMxWcJD ​ ​ - application.properties # MySQL DB connection spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver spring.datasource.url=jdbc:mysql://:3306/디비명?useSSL=false&useUnicode=true&serverTimezone=Asia/Seoul&allowPublicKeyRetrieval=true spring.datasource.username=root spring.datasource.password= # JPA ddl, Naming and log spring.jpa.hibernate.ddl-auto=update spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl spring.jpa.show-sql=true ​ 이전 : 1. 목표 및 환경 구축 다음 : 3. 백엔드 : User 도메인용 Entity https://youtu.be/qNs9N8vaO3U 123, 스프링 + 리액트 로그인 > 3. 백엔드 : User 도메인용 Entity User 도메인 데이터 저장 ​ 설계할 User 도메인의 행위 요소들을 나열하면, "회원 가입 (소셜/일반)", "회원 정보 조회", "회원 탈퇴", 등이 존재합니다. 이 행위를 하기 위해선 결국 저장소가 필요합니다. 따라서 UserEntity를 생성하겠습니다. ​ UserEntity ​ - domain > user > entity > UserEntity.java import jakarta.persistence.*; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Getter; import lombok.NoArgsConstructor; import org.springframework.data.annotation.CreatedDate; import org.springframework.data.annotation.LastModifiedDate; import org.springframework.data.jpa.domain.support.AuditingEntityListener; import java.time.LocalDateTime; @Entity @EntityListeners(AuditingEntityListener.class) @Table(name = "user_user_entity") @Getter @Builder @NoArgsConstructor @AllArgsConstructor public class UserEntity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(name = "username", unique = true, nullable = false, updatable = false) private String username; @Column(name = "password", nullable = false) private String password; @Column(name = "is_lock", nullable = false) private Boolean isLock; @Column(name = "is_social", nullable = false) private Boolean isSocial; @Enumerated(EnumType.STRING) @Column(name = "social_provider_type") private SocialProviderType socialProviderType; @Enumerated(EnumType.STRING) @Column(name = "role_type", nullable = false) private UserRoleType roleType; @Column(name = "nickname") private String nickname; @Column(name = "email") private String email; @CreatedDate @Column(name = "created_date", updatable = false) private LocalDateTime createdDate; @LastModifiedDate @Column(name = "updated_date") private LocalDateTime updatedDate; } ​ - domain > user > entity > SocialProviderType.java import lombok.Getter; @Getter public enum SocialProviderType { NAVER("네이버"), GOOGLE("구글"); private final String description; SocialProviderType(String description) { this.description = description; } } ​ - domain > user > entity > UserRoleType.java public enum UserRoleType { USER, ADMIN } ​ UserRepository ​ - domain > user > repository > UserRepository.java import org.example.backend.domain.user.entity.UserEntity; import org.springframework.data.jpa.repository.JpaRepository; public interface UserRepository extends JpaRepository { } Auditing을 위한 Config 등록 ​ Entity의 CreatedDate, LastModifiedDate를 위한 Config를 등록해야 합니다. ​ - config > JpaAuditingConfig.java import org.springframework.context.annotation.Configuration; import org.springframework.data.jpa.repository.config.EnableJpaAuditing; @Configuration @EnableJpaAuditing public class JpaAuditingConfig { } ​ 이전 : 2. 백엔드 : 구조 설명 및 DB 연결 다음 : 4. 백엔드 : UserService 메소드 작성 1 https://youtu.be/dfaAP7d7KzQ?si=WHEG8jdmElc82fKK 124, 스프링 + 리액트 로그인 > 4. 백엔드 : UserService 메소드 작성 1 UserService 구현 시작 ​ User 도메인에서 행위를 수행할 Service단 CRUD 메소드를 작성하겠습니다. 작성하기 전 대략적으로 아래 메소드가 있을 것으로 판단됩니다. ​ - domain > user > service > UserService.java import org.example.backend.domain.user.repository.UserRepository; import org.springframework.stereotype.Service; @Service public class UserService { private final UserRepository userRepository; public UserService(UserRepository userRepository) { this.userRepository = userRepository; } // 자체 로그인 회원 가입 (존재 여부) // 자체 로그인 회원 가입 // 자체 로그인 // 자체 로그인 회원 정보 수정 // 자체/소셜 로그인 회원 탈퇴 // 소셜 로그인 (매 로그인시 : 신규 = 가입, 기존 = 업데이트) // 자체/소셜 유저 정보 조회 } ​ 자체 로그인 : 회원 가입시 유저 존재 여부 ​ 회원 가입시 이미 username이 존재하는지 "중복 검증"을 진행합니다. 여기에 대해 확인용 메소드를 추가하겠습니다. ​ - domain > user > repository > UserRepository.java : 메소드 추가 Boolean existsByUsername(String username); ​ - domain > user > service > UserService.java : 메소드 추가 @Transactional(readOnly = true) public Boolean existUser(UserRequestDTO dto) { return userRepository.existsByUsername(dto.getUsername()); } - domain > user > dto > UserRequestDTO.java : DTO 추가 import lombok.Getter; import lombok.Setter; @Getter @Setter public class UserRequestDTO { private String username; } ​ 위, DTO는 User 도메인에서 자주 사용할 예정입니다. ​ PasswordEncoder 등록 : SecurityConfig ​ 다음 자체 회원 가입 메소드를 작성하기 전, 비밀번호를 암호화 시키기 위한 PasswordEncoder Bean을 등록하여 다른곳에서 주입 받아 사용할 수 있도록 하겠습니다. ​ - config > SecurityConfig.java import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; @Configuration @EnableWebSecurity public class SecurityConfig { // 비밀번호 단방향(BCrypt) 암호화용 Bean @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } } ​ 자체 로그인 : 회원 가입 ​ 회원 가입 로직도 추가합니다. ​ - domain > user > service > UserService.java : 메소드 추가 private final PasswordEncoder passwordEncoder; private final UserRepository userRepository; public UserService(PasswordEncoder passwordEncoder, UserRepository userRepository) { this.passwordEncoder = passwordEncoder; this.userRepository = userRepository; } @Transactional public Long addUser(UserRequestDTO dto) { if (userRepository.existsByUsername(dto.getUsername())) { throw new IllegalArgumentException("이미 유저가 존재합니다."); } UserEntity entity = UserEntity.builder() .username(dto.getUsername()) .password(passwordEncoder.encode(dto.getPassword())) .isLock(false) .isSocial(false) .roleType(UserRoleType.USER) // 우선 일반 유저로 가입 .nickname(dto.getNickname()) .email(dto.getEmail()) .build(); return userRepository.save(entity).getId(); } ​ - domain > user > dto > UserRequestDTO.java : DTO 수정 (필드 추가) import lombok.Getter; import lombok.Setter; @Getter @Setter public class UserRequestDTO { private String username; private String password; private String nickname; private String email; } ​ 자체 로그인 : 회원 정보 수정 ​ 회원 정보 수정시 자체 로그인 여부, 잠김 여부를 확인해야 합니다. ​ - domain > user > repository > UserRepository.java : 메소드 추가 Optional findByUsernameAndIsLockAndIsSocial(String username, Boolean isLock, Boolean isSocial); ​ - domain > user > service > UserService.java : 메소드 추가 @Transactional public Long updateUser(UserRequestDTO dto) throws AccessDeniedException { // 본인만 수정 가능 검증 String sessionUsername = SecurityContextHolder.getContext().getAuthentication().getName(); if (!sessionUsername.equals(dto.getUsername())) { throw new AccessDeniedException("본인 계정만 수정 가능"); } // 조회 UserEntity entity = userRepository.findByUsernameAndIsLockAndIsSocial(dto.getUsername(), false, false) .orElseThrow(() -> new UsernameNotFoundException(dto.getUsername())); // 회원 정보 수정 entity.updateUser(dto); return userRepository.save(entity).getId(); } ​ Entity 또한 @Setter가 없기 때문에 수정 메소드를 만들어야 합니다. ​ - domain > user > entity > UserEntity.java : 메소드 추가 public void updateUser(UserRequestDTO dto) { this.email = dto.getEmail(); this.nickname = dto.getNickname(); } ​ 이전 : 3. 백엔드 : User 도메인용 Entity 다음 : 5. 백엔드 : 자체 로그인 설정 https://youtu.be/0QSczASWcMA 125, 스프링 + 리액트 로그인 > 5. 백엔드 : 자체 로그인 설정 자체 로그인 설정 ​ 자체 로그인을 위한 SecurityConfig SecurityFilterChain 및 Service단 메소드 설정을 진행하겠습니다. 여타 다른 메소드와 달리 시큐리티 의존성의 규칙을 많이 따라주어야 합니다. ​ ​ SecurityConfig SecurityFilterChain Bean 등록 ​ - config > SecurityConfig.java : 메소드 추가 // SecurityFilterChain @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { // CSRF 보안 필터 disable http .csrf(AbstractHttpConfigurer::disable); // CORS 설정 // 기본 Form 기반 인증 필터들 disable http .formLogin(AbstractHttpConfigurer::disable); // 기본 Basic 인증 필터 disable http .httpBasic(AbstractHttpConfigurer::disable); // 인가 http .authorizeHttpRequests(auth -> auth .anyRequest().permitAll()); // 예외 처리 http .exceptionHandling(e -> e .authenticationEntryPoint((request, response, authException) -> { response.sendError(HttpServletResponse.SC_UNAUTHORIZED); // 401 응답 }) .accessDeniedHandler((request, response, authException) -> { response.sendError(HttpServletResponse.SC_FORBIDDEN); // 403 응답 }) ); // 세션 필터 설정 (STATELESS) http .sessionManagement(session -> session .sessionCreationPolicy(SessionCreationPolicy.STATELESS)); return http.build(); } ​ 기본 로그인 필터인 UsernamePasswordAuthenticationFilter는 multipart-form 기반이며, formLogin 활성화시 VIEW 페이지까지 활성화 되기 때문에 disable 후 직접 LoginFilter를 등록하도록 하겠습니다. ​ LoginFilter 직접 작성 후 등록 ​ JSON 기반으로 로그인을 수행하는 로그인 필터를 직접 작성하겠습니다. 기본적으로 자체 로그인시 등록되던 UsernamePasswordAuthenticationFilter.java를 최대한 참조하여 작성합니다. ​ https://github.com/spring-projects/spring-security/blob/main/web/src/main/java/org/springframework/security/web/authentication/UsernamePasswordAuthenticationFilter.java spring-security/web/src/main/java/org/springframework/security/web/authentication/UsernamePasswordAuthenticationFilter.java at main · spring-projects/spring-security Spring Security. Contribute to spring-projects/spring-security development by creating an account on GitHub. github.com ​ - 요청 JSON Body 예상 { "username": "xxxjjhhh", "password": "1234" } ​ - filter > LoginFilter.java import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import jakarta.servlet.FilterChain; import jakarta.servlet.ServletException; import jakarta.servlet.ServletInputStream; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.springframework.http.HttpMethod; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.AuthenticationServiceException; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter; import org.springframework.security.web.servlet.util.matcher.PathPatternRequestMatcher; import org.springframework.security.web.util.matcher.RequestMatcher; import org.springframework.util.StreamUtils; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.Map; public class LoginFilter extends AbstractAuthenticationProcessingFilter { public static final String SPRING_SECURITY_FORM_USERNAME_KEY = "username"; public static final String SPRING_SECURITY_FORM_PASSWORD_KEY = "password"; private static final RequestMatcher DEFAULT_ANT_PATH_REQUEST_MATCHER = PathPatternRequestMatcher.withDefaults() .matcher(HttpMethod.POST, "/login"); private String usernameParameter = SPRING_SECURITY_FORM_USERNAME_KEY; private String passwordParameter = SPRING_SECURITY_FORM_PASSWORD_KEY; public LoginFilter(AuthenticationManager authenticationManager) { super(DEFAULT_ANT_PATH_REQUEST_MATCHER, authenticationManager); } @Override public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException { if (!request.getMethod().equals("POST")) { throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod()); } Map loginMap; try { ObjectMapper objectMapper = new ObjectMapper(); ServletInputStream inputStream = request.getInputStream(); String messageBody = StreamUtils.copyToString(inputStream, StandardCharsets.UTF_8); loginMap = objectMapper.readValue(messageBody, new TypeReference<>() { }); } catch (IOException e) { throw new RuntimeException(e); } String username = loginMap.get(usernameParameter); username = (username != null) ? username.trim() : ""; String password = loginMap.get(passwordParameter); password = (password != null) ? password : ""; UsernamePasswordAuthenticationToken authRequest = UsernamePasswordAuthenticationToken.unauthenticated(username, password); setDetails(request, authRequest); return this.getAuthenticationManager().authenticate(authRequest); } protected void setDetails(HttpServletRequest request, UsernamePasswordAuthenticationToken authRequest) { authRequest.setDetails(this.authenticationDetailsSource.buildDetails(request)); } } ​ 직접 작성한 LoginFilter를 SecurityFilterChain에 등록합니다. ​ - config > SecurityConfig.java : SecurityFilterChain Filter 추가 // 커스텀 필터 추가 http .addFilterBefore(new LoginFilter(authenticationManager(authenticationConfiguration)), UsernamePasswordAuthenticationFilter.class); ​ 이때, 인증을 수행하는 AuthenticationManager을 직접 넣어주어야 합니다. ​ - config > SecurityConfig.java : AuthenticationManager Bean 등록 // 커스텀 자체 로그인 필터를 위한 AuthenticationManager Bean 수동 등록 @Bean public AuthenticationManager authenticationManager(AuthenticationConfiguration configuration) throws Exception { return configuration.getAuthenticationManager(); } private final AuthenticationConfiguration authenticationConfiguration; public SecurityConfig(AuthenticationConfiguration authenticationConfiguration) { this.authenticationConfiguration = authenticationConfiguration; } ​ DB 기반 로그인을 수행하기 위한 UserDetailsService 구현 ​ ​ LoginFilter ~ DaoAuthenticationProvider 까지 등록은 완료되었습니다. 이제 앞쪽에서 받은 username/password를 기반으로 비교 검증을 위한 우리 DB에 저장된 username/password를 가져오는 UserDetailsService를 구현합니다. ​ - domain > user > service > UserService.java : implements public class UserService implements UserDetailsService ​ - domain > user > service > UserService.java : 관련 메소드 override // 자체 로그인 @Transactional(readOnly = true) @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { UserEntity entity = userRepository.findByUsernameAndIsLockAndIsSocial(username, false, false) .orElseThrow(() -> new UsernameNotFoundException(username)); return User.builder() .username(entity.getUsername()) .password(entity.getPassword()) .roles(entity.getRoleType().name()) .accountLocked(entity.getIsLock()) .build(); } ​ 기타 ​ 스프링 시큐리티 로그인에 대한 구조 설명 추천 영상 ​ https://youtu.be/DCnra1pxRw0 ​ 이전 : 4. 백엔드 : UserService 메소드 작성 1 다음 : 6. 백엔드 : JWT Util 클래스 등록 https://youtu.be/0h6QxtPsla8 126, Elasticsearch8 환경에서 커스텀 플러그인 개발 (개인 공부 시리즈) ​ ​ 1. Elasticsearch 플러그인 개발 환경 2. 초성 토큰 필터 ​ ​ 코드 ​ https://github.com/xxxjjhhh/esplugin 127, 엘라스틱서치 플러그인 개발 > 1. Elasticsearch 플러그인 개발 환경 Elasticsearch 커스텀 플러그인 개발 ​ Elasticsearch 8.17.6 버전을 기준으로, Gradle 빌드, 커스텀 플러그인 개발을 진행합니다. 이번 시리즈는 개인적으로 커스텀 플러그인 개발 과정을 기록하기 위해 진행합니다. ​ 자바 프로젝트 생성 : Gradle 기반 ​ Elasticsearch 8 은 JDK 19 이상 버전을 사용해야 합니다. ​ ​ build.gradle 작성 ​ 자바 프로젝트에 Elasticsearch 플러그인 개발 환경을 만들기 위해 build.gradle을 수정합니다. ​ 플러그인 개발은 elasticsearch build-tools를 기반으로 진행되며, 버전을 맞춰서 적용해야 합니다. ​ https://mvnrepository.com/artifact/org.elasticsearch.gradle/build-tools ​ - build.gradle buildscript { repositories { mavenLocal() mavenCentral() } dependencies { classpath "org.elasticsearch.gradle:build-tools:8.17.6" } } group = 'org.example' version = '1.0-SNAPSHOT' repositories { mavenCentral() } apply plugin: 'elasticsearch.esplugin' esplugin { name 'devyummi-analyzer' description 'devyummi demo plugin' classname 'com.devyummi.plugin.DevyummiAnalyzerPlugin' } dependencies { implementation group: 'org.elasticsearch', name: 'elasticsearch', version: '8.17.6' testImplementation platform('org.junit:junit-bom:5.10.0') testImplementation 'org.junit.jupiter:junit-jupiter' } test { useJUnitPlatform() } ​ 플러그인 클래스 등록 ​ - DevyummiAnalyzerPlugin.java import org.elasticsearch.plugins.AnalysisPlugin; import org.elasticsearch.plugins.Plugin; public class DevyummiAnalyzerPlugin extends Plugin implements AnalysisPlugin { } ​ 플러그인 클래스 분석기 @Override ​ - DevyummiAnalyzerPlugin.java import org.elasticsearch.index.analysis.CharFilterFactory; import org.elasticsearch.index.analysis.TokenFilterFactory; import org.elasticsearch.index.analysis.TokenizerFactory; import org.elasticsearch.indices.analysis.AnalysisModule; import org.elasticsearch.plugins.AnalysisPlugin; import org.elasticsearch.plugins.Plugin; import java.util.Collections; import java.util.Map; public class DevyummiAnalyzerPlugin extends Plugin implements AnalysisPlugin { @Override public Map> getCharFilters() { return Collections.emptyMap(); } @Override public Map> getTokenizers() { return Collections.emptyMap(); } @Override public Map> getTokenFilters() { return Collections.emptyMap(); } } ​ 다음 : 2. 초성 토큰 필터 https://youtu.be/_XKZiFcJAGk?si=TArk_QGRDeKMenDc 129, 엘라스틱서치 플러그인 개발 > 2. 초성 토큰 필터 초성 토큰 필터 ​ 초성 검색을 위한 초성 토큰화 필터를 만들어 보겠습니다. 원리는 다음과 같습니다. ​ - 필터 통과 자연어 : 유튜브 필터 통과 후 : ㅇㅌㅂ ​ "ㅇㅌㅂ"라는 토큰을 인덱스에 넣어서 사용자가 ㅇㅌㅂ라고 검색하면 관련된 문서를 찾음. ​ 위 필터를 활용하여 초성 검색에 대한 자동 완성도 생성 가능. ​ 매커니즘 ​ 단어를 초성만 남기기 위한 매커니즘은 아래와 같습니다. ​ - 키포인트 - 유니코드에서 한글 글자는 총 (19 X 21 X 28 = 11,172)개 (초성 X 중성 X 종성)로 가, 각, 갂, 갃, ~, 힣 - 시작하는 "가"의 유니코드는 0xAC00 - 가 ~ 깋 -> ㄱ 으로 - 나 ~ 닣 -> ㄴ 으로 - 그럼 0xAC00 부터 시작해서 21 X 28개 기준으로 모두 초성화 시키면 됨 ​ - 과정 1. 우선 한글 초성 리스트를 구축 2. "가~힣"는 19 X (21 X 28) 개 3. "가~깋" -> 0으로, 나~힣 -> 1로 치환해야 함 4. 일단 "가"가 0xAC00부터 시작이라 0부터 시작하도록 0xAC00을 "가~힣"에 대해 다 빼버림 5. "가~깋"은 0xAC00만큼이 빠졌으니 "0~587"의 값을 가지는 중 6. 각 값을 588로 나누고 몫의 값만 가져오면? -> 인덱스의 값이 나옴 ​ ChosungTokenFilter ​ - token_filter > chosung > ChosungTokenFilter.java package com.devyummi.plugin.token_filter.chosung; import org.apache.lucene.analysis.TokenFilter; import org.apache.lucene.analysis.TokenStream; import org.apache.lucene.analysis.tokenattributes.CharTermAttribute; import java.io.IOException; public class ChosungTokenFilter extends TokenFilter { // 초성 판단 // // 한글 유니코드 (가, 0xAC00) 를 시작으로 가, 까, 나, 다는 각 21 * 28 개의 유니코드 단위로 넘어감 // 이유는 초성 "ㄱ" 에 대한 중성 X 종성 이 588개임 // // 초성 리스트를 만듬 ㄱ~ㅎ "ㄱ" 은 인덱스 0 // // 사용자로 부터 한글 단어를 받음 "난" // 이후 기본 한글 스타트 값인 "가"로 빼줌 "난 - 가" // 그 값에 대해 유닛 값인 21*28로 나눔 (난 - 가) / 21*28 // 그럼 인덱스 값이 2 인 "ㄴ"이 나옴 private final CharTermAttribute termAttr = addAttribute(CharTermAttribute.class); private static final char[] CHOSUNG = { 'ㄱ','ㄲ','ㄴ','ㄷ','ㄸ','ㄹ','ㅁ','ㅂ','ㅃ','ㅅ', 'ㅆ','ㅇ','ㅈ','ㅉ','ㅊ','ㅋ','ㅌ','ㅍ','ㅎ' }; private static final int HANGUL_BASE = 0xAC00; private static final int CHOSUNG_UNIT = 21 * 28; public ChosungTokenFilter(TokenStream input) { super(input); } @Override public boolean incrementToken() throws IOException { if (!input.incrementToken()) return false; char[] buffer = termAttr.buffer(); int length = termAttr.length(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < length; i++) { char c = buffer[i]; if (isCompleteHangul(c)) { int sIndex = c - HANGUL_BASE; int chosungIndex = sIndex / CHOSUNG_UNIT; if (chosungIndex >= 0 && chosungIndex < CHOSUNG.length) { sb.append(CHOSUNG[chosungIndex]); } else { sb.append(c); } } else if (isChosung(c)) { sb.append(c); } else { sb.append(c); } } String newTerm = sb.toString(); termAttr.setEmpty(); termAttr.append(newTerm); return true; } // 한글인지 판단 private boolean isCompleteHangul(char c) { return c >= 0xAC00 && c <= 0xD7A3; } // 이미 초성인 경우 판단 private boolean isChosung(char c) { for (char ch : CHOSUNG) { if (ch == c) return true; } return false; } } ​ ChosungTokenFilterFactory ​ - token_filter > chosung > ChosungTokenFilterFactory.java package com.devyummi.plugin.token_filter.chosung; import org.apache.lucene.analysis.TokenStream; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.env.Environment; import org.elasticsearch.index.IndexSettings; import org.elasticsearch.index.analysis.AbstractTokenFilterFactory; public class ChosungTokenFilterFactory extends AbstractTokenFilterFactory { public ChosungTokenFilterFactory(IndexSettings indexSettings, Environment environment, String name, Settings settings ) { super(name, settings); } @Override public TokenStream create(TokenStream tokenStream) { return new ChosungTokenFilter(tokenStream); } } ​ 플러그인 등록 ​ - DevyummiAnalyzerPlugin.java public class DevyummiAnalyzerPlugin extends Plugin implements AnalysisPlugin { @Override public Map> getCharFilters() { return Collections.emptyMap(); } @Override public Map> getTokenizers() { return Collections.emptyMap(); } @Override public Map> getTokenFilters() { Map> list = new HashMap<>(); list.put("chosung_token_filter", ChosungTokenFilterFactory::new); return list; } } ​ 빌드 후 테스트 ​ - 인덱스 { "mappings": { "properties": { "id": { "type": "long", "index": false }, "title": { "type": "text", "analyzer": "my_custom_analyzer" } } }, "settings": { "analysis": { "analyzer": { "my_custom_analyzer": { "type": "custom", "char_filter": [], "tokenizer": "my_nori_tokenizer", "filter": [ "chosung_token_filter" ] } }, "char_filter": {}, "tokenizer": { "my_nori_tokenizer": { "type": "nori_tokenizer", "decompound_mode": "mixed", "discard_punctuation": "true", "lenient": true } } } } } ​ - 테스트 환경 - Char_Filter : 없음 - Tokenizer : Nori - Token_Filter : 초성 ​ 이전 : 1. Elasticsearch 플러그인 개발 환경 다음 : 3. 130, 스프링 + 리액트 로그인 > 6. 백엔드 : JWT Util 클래스 등록 JWT 영역 ​ 아직 User 도메인과 로그인 시스템에 대한 구현이 완료되지 않았지만, 로그인 이후의 JWT 발급이 필요하기 때문에 일시적으로 JWT 도메인 구현을 수행하겠습니다. ​ JWTUtil ​ JWT 영역에서는 JWT 관리도 중요하지만, 발급과 검증이 요구됩니다. 따라서 JWT를 발급하고 검증할 수 있는 Util 클래스를 먼저 등록하겠습니다. ​ 그 전에 JWT를 자바 환경에서 생성하고 관리하는 의존성을 추가해야 합니다. ​ https://mvnrepository.com/artifact/io.jsonwebtoken/jjwt ​ - build.gradle > dependencies implementation 'io.jsonwebtoken:jjwt-api:0.12.6' implementation 'io.jsonwebtoken:jjwt-impl:0.12.6' implementation 'io.jsonwebtoken:jjwt-jackson:0.12.6' ​ - util > JWTUtil import io.jsonwebtoken.Claims; import io.jsonwebtoken.JwtException; import io.jsonwebtoken.Jwts; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; import java.nio.charset.StandardCharsets; import java.util.Date; public class JWTUtil { private static final SecretKey secretKey; private static final Long accessTokenExpiresIn; private static final Long refreshTokenExpiresIn; static { String secretKeyString = "himynameiskimjihunmyyoutubechann"; secretKey = new SecretKeySpec(secretKeyString.getBytes(StandardCharsets.UTF_8), Jwts.SIG.HS256.key().build().getAlgorithm()); accessTokenExpiresIn = 3600L * 1000; // 1시간 refreshTokenExpiresIn = 604800L * 1000; // 7일 } // JWT 클레임 username 파싱 public static String getUsername(String token) { return Jwts.parser().verifyWith(secretKey).build().parseSignedClaims(token).getPayload().get("sub", String.class); } // JWT 클레임 role 파싱 public static String getRole(String token) { return Jwts.parser().verifyWith(secretKey).build().parseSignedClaims(token).getPayload().get("role", String.class); } // JWT 유효 여부 (위조, 시간, Access/Refresh 여부) public static Boolean isValid(String token, Boolean isAccess) { try { Claims claims = Jwts.parser() .verifyWith(secretKey) .build() .parseSignedClaims(token) .getPayload(); String type = claims.get("type", String.class); if (type == null) return false; if (isAccess && !type.equals("access")) return false; if (!isAccess && !type.equals("refresh")) return false; return true; } catch (JwtException | IllegalArgumentException e) { return false; } } // JWT(Access/Refresh) 생성 public static String createJWT(String username, String role, Boolean isAccess) { long now = System.currentTimeMillis(); long expiry = isAccess ? accessTokenExpiresIn : refreshTokenExpiresIn; String type = isAccess ? "access" : "refresh"; return Jwts.builder() .claim("sub", username) .claim("role", role) .claim("type", type) .issuedAt(new Date(now)) .expiration(new Date(now + expiry)) .signWith(secretKey) .compact(); } } ​ 이전 : 5. 백엔드 : 자체 로그인 설정 다음 : 7. 백엔드 : Jwt 도메인용 Entity https://youtu.be/H7OvMOGXRS0 131, OpenAI gpt-oss ​ 2025년 8월 6일 OpenAI에서 오픈 웨이트 모델을 공개했습니다. huggingface를 통해 확인 가능합니다. ​ https://openai.com/ko-KR/index/introducing-gpt-oss/ gpt-oss를 소개합니다 오픈 웨이트 추론 모델의 경계를 확장하는 gpt-oss-120b와 gpt-oss-20b openai.com ​ 모델은 총 2종류로 (20b, 120b) 아파치 2.0 라이선스를 가지고 있기 때문에 상업용으로도 배포가 가능합니다. ​ OpenAI 측에서 말하는 성능은 아래와 같습니다. - 120b 모델 : o4-mini와 동일한 성능, VRAM이 80GB인 GPU를 통해 운용 - 20b 모델 : o3-mini와 동일한 성능, VRAM이 16GB인 GPU를 통해 운용 ​ API 호출은 OpenAI 모델들과 동일하며, 에이전트 기능도 사용가능합니다. MoE 구조의 모델입니다. ​ HuggingFace ​ https://huggingface.co/openai/gpt-oss-20b openai/gpt-oss-20b · Hugging Face Try gpt-oss · Guides · Model card · OpenAI blog Welcome to the gpt-oss series, OpenAI’s open-weight models designed for powerful reasoning, agentic tasks, and versatile developer use cases. We’re releasing two flavors of these open models: gpt-oss-120b — for production, general purpose, high reasoni... huggingface.co ​ https://huggingface.co/openai/gpt-oss-120b openai/gpt-oss-120b · Hugging Face Try gpt-oss · Guides · Model card · OpenAI blog Welcome to the gpt-oss series, OpenAI’s open-weight models designed for powerful reasoning, agentic tasks, and versatile developer use cases. We’re releasing two flavors of these open models: gpt-oss-120b — for production, general purpose, high reasoni... huggingface.co ​ vLLM을 통한 LLM 서빙 ​ https://cookbook.openai.com/articles/gpt-oss/run-vllm How to run gpt-oss with vLLM | OpenAI Cookbook vLLM is an open-source, high-throughput inference engine designed to efficiently serve large language models (LLMs) by optimizing memory... cookbook.openai.com ​ - vllm ~/.local/bin/vllm serve openai/gpt-oss-120b --port 8080 --max-model-len 4096 --tensor-parallel-size 4 --gpu-memory-utilization 0.92 --swap-space 16 --host 0.0.0.0 ​ Use the API ​ - 파이썬 from openai import OpenAI client = OpenAI( base_url="http://localhost:8000/v1", api_key="EMPTY" ) result = client.chat.completions.create( model="openai/gpt-oss-20b", messages=[ {"role": "system", "content": "You are a helpful assistant."}, {"role": "user", "content": "Explain what MXFP4 quantization is."} ] ) print(result.choices[0].message.content) response = client.responses.create( model="openai/gpt-oss-120b", instructions="You are a helfpul assistant.", input="Explain what MXFP4 quantization is." ) print(response.output_text) ​ MXFP4 문제 ​ vLLM이 gpt-oss 모델의 MXFP4 양자화 방식을 지원하지 못해 실행 오류가 발생하는 경우가 있습니다. 이를 해결하기 위해 신규 방식의 vLLM을 설치해야 합니다. ​ https://blog.vllm.ai/2025/08/05/gpt-oss.html vLLM Now Supports gpt-oss We’re thrilled to announce that vLLM now supports gpt-oss on NVIDIA Blackwell and Hopper GPUs, as well as AMD MI300x and MI355x GPUs. In this blog post, we’ll explore the efficient model architecture of gpt-oss and how vLLM supports it. blog.vllm.ai ​ pip3 uninstall vllm pip3 install --pre vllm==0.10.1+gptoss \ --extra-index-url https://wheels.vllm.ai/gpt-oss/ \ --extra-index-url https://download.pytorch.org/whl/nightly/cu128 (파이썬 3.12~3.13만 지원) cudnn 문제 ​ 설치 ​ https://developer.nvidia.com/cudnn CUDA Deep Neural Network cuDNN provides researchers and developers with high-performance GPU acceleration. developer.nvidia.com ​ pip install nvidia-pyindex pip install nvidia-cudnn ​ 132, 스프링 + 리액트 로그인 > 7. 백엔드 : Jwt 도메인용 Entity 모식도 ​ ​ Jwt 도메인 데이터 저장 ​ 설계할 Jwt 도메인의 행위 요소들을 나열하면, "Refresh 토큰 발급시 저장", "Refresh 토큰 화이트 리스트 조회", 등이 존재합니다. Refresh 토큰의 경우 생명주기가 길기 때문에 백엔드측에서 토큰들을 리스트화 시켜두고 Access 재발급시 검증하거나 로그아웃시 무효 처리를 진행하고 있습니다. ​ 이 행위를 하기 위해선 결국 저장소가 필요합니다. 따라서 RefreshEntity를 생성하겠습니다. ​ RefreshEntity ​ - domain > jwt > entity > RefreshEntity.java import jakarta.persistence.*; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Getter; import lombok.NoArgsConstructor; import org.springframework.data.annotation.CreatedDate; import org.springframework.data.jpa.domain.support.AuditingEntityListener; import java.time.LocalDateTime; @Entity @EntityListeners(AuditingEntityListener.class) @Table(name = "jwt_refresh_entity") @Getter @Builder @NoArgsConstructor @AllArgsConstructor public class RefreshEntity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(name = "username", nullable = false) private String username; @Column(name = "refresh", nullable = false, length = 512) private String refresh; @CreatedDate @Column(name = "created_date", updatable = false) private LocalDateTime createdDate; } ​ RefreshRepository ​ - domain > jwt > repository > RefreshRepository.java import org.example.backend.domain.jwt.entity.RefreshEntity; import org.springframework.data.jpa.repository.JpaRepository; public interface RefreshRepository extends JpaRepository { } ​ 이전 : 6. 백엔드 : JWT Util 클래스 등록 다음 : 8. 백엔드 : JwtService 메소드 작성 1 https://youtu.be/iMw7ysv0K4A 133, 스프링 + 리액트 로그인 > 8. 백엔드 : JwtService 메소드 작성 1 JwtService 구현 시작 ​ Jwt 도메인에서 행위를 수행할 Service단 CRUD 메소드를 작성하겠습니다. 작성하기 전 대략적으로 아래 메소드가 있을 것으로 판단됩니다. ​ - domain > jwt > service > JwtService.java import org.example.backend.domain.jwt.repository.RefreshRepository; import org.springframework.stereotype.Service; @Service public class JwtService { private final RefreshRepository refreshRepository; public JwtService(RefreshRepository refreshRepository) { this.refreshRepository = refreshRepository; } // 소셜 로그인 성공 후 쿠키(Refresh) -> 헤더 방식으로 응답 <-- 이건 추후에 작성 // Refresh 토큰으로 Access 토큰 재발급 로직 (Rotate 포함) <-- 이건 추후에 작성 // JWT Refresh 토큰 발급 후 저장 메소드 // JWT Refresh 존재 확인 메소드 // JWT Refresh 토큰 삭제 메소드 // 특정 유저 Refresh 토큰 모두 삭제 (탈퇴) } ​ JWT Refresh 토큰 발급 후 저장 메소드 ​ Refresh 토큰 발급시 백엔드에도 저장할 메소드를 생성합니다. ​ - domain > jwt > service > JwtService.java : 메소드 추가 @Transactional public void addRefresh(String username, String refreshToken) { RefreshEntity entity = RefreshEntity.builder() .username(username) .refresh(refreshToken) .build(); refreshRepository.save(entity); } ​ JWT Refresh 토큰 기반 존재 확인 메소드 ​ - domain > jwt > repository > RefreshRepository.java : 메소드 추가 Boolean existsByRefresh(String refreshToken); ​ - domain > jwt > service > JwtService.java : 메소드 추가 @Transactional(readOnly = true) public Boolean existsRefresh(String refreshToken) { return refreshRepository.existsByRefresh(refreshToken); } ​ JWT Refresh 토큰 기반 삭제 메소드 ​ - domain > jwt > repository > RefreshRepository.java : 메소드 추가 @Transactional void deleteByRefresh(String refresh); ​ - domain > jwt > service > JwtService.java : 메소드 추가 public void removeRefresh(String refreshToken) { refreshRepository.deleteByRefresh(refreshToken); } ​ JWT 발급 username 기반 삭제 메소드 (탈퇴시) ​ - domain > jwt > repository > RefreshRepository.java : 메소드 추가 @Transactional void deleteByUsername(String username); ​ - domain > jwt > service > JwtService.java : 메소드 추가 public void removeRefreshUser(String username) { refreshRepository.deleteByUsername(username); } ​ 이전 : 7. 백엔드 : Jwt 도메인용 Entity 다음 : 9. 백엔드 : 자체 로그인 성공 핸들러 134, 스프링 + 리액트 로그인 > 9. 백엔드 : 자체 로그인 성공 핸들러 로그인 성공 이후 ​ User 도메인에서 자체 로그인 로직, User 관련 로직, Jwt 도메인에서 Jwt 발급 및 관리 로직을 모두 작성했습니다. ​ 지금 로직 자체만으로 로그인이 가능하지만, 로그인 이후의 프론트로 JWT를 발급해야 하는 일이 남았습니다. ​ 자체 로그인 성공 핸들러 작성 ​ - handler > LoginSuccessHandler.java import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.example.backend.domain.jwt.service.JwtService; import org.example.backend.util.JWTUtil; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.security.core.Authentication; import org.springframework.security.web.authentication.AuthenticationSuccessHandler; import org.springframework.stereotype.Component; import java.io.IOException; @Component @Qualifier("LoginSuccessHandler") public class LoginSuccessHandler implements AuthenticationSuccessHandler { private final JwtService jwtService; public LoginSuccessHandler(JwtService jwtService) { this.jwtService = jwtService; } @Override public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException { // username, role String username = authentication.getName(); String role = authentication.getAuthorities().iterator().next().getAuthority(); // JWT(Access/Refresh) 발급 String accessToken = JWTUtil.createJWT(username, role, true); String refreshToken = JWTUtil.createJWT(username, role, false); // 발급한 Refresh DB 테이블 저장 (Refresh whitelist) jwtService.addRefresh(username, refreshToken); // 응답 response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); String json = String.format("{\"accessToken\":\"%s\", \"refreshToken\":\"%s\"}", accessToken, refreshToken); response.getWriter().write(json); response.getWriter().flush(); } } ​ 자체 LoginFilter에서 성공 핸들러 등록 ​ - filter > LoginFilter.java import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import jakarta.servlet.FilterChain; import jakarta.servlet.ServletException; import jakarta.servlet.ServletInputStream; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.springframework.http.HttpMethod; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.AuthenticationServiceException; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter; import org.springframework.security.web.authentication.AuthenticationSuccessHandler; import org.springframework.security.web.servlet.util.matcher.PathPatternRequestMatcher; import org.springframework.security.web.util.matcher.RequestMatcher; import org.springframework.util.StreamUtils; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.Map; public class LoginFilter extends AbstractAuthenticationProcessingFilter { public static final String SPRING_SECURITY_FORM_USERNAME_KEY = "username"; public static final String SPRING_SECURITY_FORM_PASSWORD_KEY = "password"; private static final RequestMatcher DEFAULT_ANT_PATH_REQUEST_MATCHER = PathPatternRequestMatcher.withDefaults() .matcher(HttpMethod.POST, "/login"); private String usernameParameter = SPRING_SECURITY_FORM_USERNAME_KEY; private String passwordParameter = SPRING_SECURITY_FORM_PASSWORD_KEY; private final AuthenticationSuccessHandler authenticationSuccessHandler; public LoginFilter(AuthenticationManager authenticationManager, AuthenticationSuccessHandler authenticationSuccessHandler) { super(DEFAULT_ANT_PATH_REQUEST_MATCHER, authenticationManager); this.authenticationSuccessHandler = authenticationSuccessHandler; } @Override public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException { if (!request.getMethod().equals("POST")) { throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod()); } Map loginMap; try { ObjectMapper objectMapper = new ObjectMapper(); ServletInputStream inputStream = request.getInputStream(); String messageBody = StreamUtils.copyToString(inputStream, StandardCharsets.UTF_8); loginMap = objectMapper.readValue(messageBody, new TypeReference<>() { }); } catch (IOException e) { throw new RuntimeException(e); } String username = loginMap.get(usernameParameter); username = (username != null) ? username.trim() : ""; String password = loginMap.get(passwordParameter); password = (password != null) ? password : ""; UsernamePasswordAuthenticationToken authRequest = UsernamePasswordAuthenticationToken.unauthenticated(username, password); setDetails(request, authRequest); return this.getAuthenticationManager().authenticate(authRequest); } protected void setDetails(HttpServletRequest request, UsernamePasswordAuthenticationToken authRequest) { authRequest.setDetails(this.authenticationDetailsSource.buildDetails(request)); } @Override protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException { authenticationSuccessHandler.onAuthenticationSuccess(request, response, authResult); } } ​ SecurityConfig에서 주입 ​ - config > SecurityConfig.java import jakarta.servlet.http.HttpServletResponse; import org.example.backend.filter.LoginFilter; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration; 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.config.http.SessionCreationPolicy; 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.AuthenticationSuccessHandler; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; @Configuration @EnableWebSecurity public class SecurityConfig { private final AuthenticationConfiguration authenticationConfiguration; private final AuthenticationSuccessHandler loginSuccessHandler; public SecurityConfig( AuthenticationConfiguration authenticationConfiguration, @Qualifier("LoginSuccessHandler") AuthenticationSuccessHandler loginSuccessHandler ) { this.authenticationConfiguration = authenticationConfiguration; this.loginSuccessHandler = loginSuccessHandler; } // 커스텀 자체 로그인 필터를 위한 AuthenticationManager Bean 수동 등록 @Bean public AuthenticationManager authenticationManager(AuthenticationConfiguration configuration) throws Exception { return configuration.getAuthenticationManager(); } // 비밀번호 단방향(BCrypt) 암호화용 Bean @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } // SecurityFilterChain @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { // CSRF 보안 필터 disable http .csrf(AbstractHttpConfigurer::disable); // CORS 설정 // 기본 Form 기반 인증 필터들 disable http .formLogin(AbstractHttpConfigurer::disable); // 기본 Basic 인증 필터 disable http .httpBasic(AbstractHttpConfigurer::disable); // 인가 http .authorizeHttpRequests(auth -> auth .anyRequest().permitAll()); // 예외 처리 http .exceptionHandling(e -> e .authenticationEntryPoint((request, response, authException) -> { response.sendError(HttpServletResponse.SC_UNAUTHORIZED); // 401 응답 }) .accessDeniedHandler((request, response, authException) -> { response.sendError(HttpServletResponse.SC_FORBIDDEN); // 403 응답 }) ); // 커스텀 필터 추가 http .addFilterBefore(new LoginFilter(authenticationManager(authenticationConfiguration), loginSuccessHandler), UsernamePasswordAuthenticationFilter.class); // 세션 필터 설정 (STATELESS) http .sessionManagement(session -> session .sessionCreationPolicy(SessionCreationPolicy.STATELESS)); return http.build(); } } ​ 이전 : 8. 백엔드 : JwtService 메소드 작성 1 다음 : 10. 백엔드 : User API 작성 및 로그인 https://youtu.be/mle18IGALW8 135, 스프링 부트에 JWT 방식으로 인증을 진행하는 스프링 시큐리티를 적용하고 JWT 발급, 인증/인가를 구현하는 방법 스프링 시큐리티 JWT ​ 1. 실습 목표 및 간단한 동작 원리 2. 프로젝트 생성 및 의존성 추가 3. SecurityConfig 클래스 4. POSTMAN 설치 5. DB연결 및 Entity 작성 6. 회원가입 로직 구현 7. 로그인 필터 구현 8. DB기반 로그인 검증 로직 9. JWT 발급 및 검증 클래스 10. 로그인 성공 JWT 발급 11. JWT 검증 필터 12. 세션 정보 13. CORS 설정 14. JWT의 궁극적인 목표 ​ 코드 ​ 코드 파일 바로가기 ​ 기타 ​ LoginFilter JSON 요청 받기 ​ 136, 스프링 시큐리티 JWT > 1. 실습 목표 및 간단한 동작 원리 실습 목표 ​ 스프링 시큐리티 6 프레임워크를 활용하여 JWT 기반의 인증/인가를 구현하고 회원 정보 저장(영속성) MySQL 데이터베이스를 활용한다. ​ 서버는 API 서버 형태로 구축한다. (웹 페이지를 응답하는 것이 아닌 API 클라이언트 요청을 통해 데이터 응답만 확인함) ​ 구현 ​ - 인증 : 로그인 - 인가 : JWT를 통한 경로별 접근 권한 - 회원가입 ​ JWT 인증 방식 시큐리티 동작 원리 ​ - 회원가입 : 내부 회원 가입 로직은 세션 방식과 JWT 방식의 차이가 없다. ​ - 로그인 (인증) : 로그인 요청을 받은 후 세션 방식은 서버 세션이 유저 정보를 저장하지만 JWT 방식은 토큰을 생성하여 응답한다. ​ - 경로 접근 (인가) : JWT Filter를 통해 요청의 헤더에서 JWT를 찾아 검증을하고 일시적 요청에 대한 Session을 생성한다. (생성된 세션은 요청이 끝나면 소멸됨) ​ ​ 버전 및 의존성 ​ - Spring Boot 3.2.1 - Security 6.2.1 - Lombok - Spring Data JPA - MySQL - Gradle - Groovy - IntelliJ Ultimate ​ 기타 ​ - 스프링 시큐리티 JWT 구현 방법이 아주 많습니다. 개발자별 다른 구현을 진행하고 버전별로도 메소드가 많이 다릅니다. 최대한 공식 문서에 구현된 형태로 코드를 작성하지만 구현은 다를 수 있습니다. - 저는 간단하게 API 서버에서 JWT 구현을 진행했고 토큰 발급의 경우 단일 토큰으로 진행합니다. (Access, Refresh로 나누는 경우도 있지만 기본 강의라 간단하게 한개로 진행하겠습니다.) - 스프링 시큐리티 JWT 시리즈를 끝낸 후 OAuth2 소셜 로그인도 진행하려 합니다. (따라서 이번 시리즈에서는 소셜 로그인을 진행하지 않습니다.) - 개념적인 부분 설명은 어디서든지 찾아볼 수 있기 때문에 많이 줄이고 구현 실습 위주로 진행하겠습니다. - 제 코드는 JWT를 구현하기 위한 가장 기본적인 뼈대 코드로 이 시리즈가 발판이 되어 여러분들이 더 좋은 결과물을 만드셨으면 좋겠습니다! ​ 참조 ​ https://docs.spring.io/spring-security/reference/servlet/architecture.html Architecture :: Spring Security Spring Security / Servlet Applications / Architecture Architecture This section discusses Spring Security’s high-level architecture within Servlet based applications. We build on this high-level understanding within the Authentication , Authorization , and Protection Against Exploits sections of the... docs.spring.io ​ 다음 : 2. 프로젝트 생성 및 의존성 추가 https://youtu.be/NPRh2v7PTZg 137, 스프링 시큐리티 JWT > 2. 프로젝트 생성 및 의존성 추가 의존성 ​ https://start.spring.io/ {"_links":{"gradle-project":{"href":"https://start.spring.io/starter.zip?type=gradle-project{&dependencies,packaging,javaVersion,language,bootVersion,groupId,artifactId,version,name,description,packageName}","templated":true},"gradle-project-kotlin":{"href":"https://start.spring.io/starter.zip?type=... start.spring.io ​ - 필수 의존성 - Lombok - Spring Web - Spring Security - Spring Data JPA - MySQL Driver ​ 데이터베이스 의존성 주석 처리 ​ 임시로 주석 처리 진행 (스프링 부트에서 데이터베이스 의존성을 추가한 뒤 연결을 진행하지 않을 경우 런타임 에러 발생) ​ JWT 필수 의존성 ​ JWT 토큰을 생성하고 관리하기 위해 JWT 의존성을 필수적으로 설정해야 합니다. ​ 설정은 build.gradle을 통해 진행하며 이때 버전을 선택하여 적용해야 합니다. 대부분은 JWT 0.11.5 버전을 통해 구현하지만 최신 버전은 0.12.3입니다. 따라서 0.12.3을 기반으로 구현하지만 추가적으로 0.11.5 버전에 대한 구현 방법도 올릴 예정입니다. (JWT를 생성하고 내부에서 데이터를 얻는 메소드가 버전마다 많이 상이합니다.) - 0.12.3 버전 : build.gradle dependencies { implementation 'io.jsonwebtoken:jjwt-api:0.12.3' implementation 'io.jsonwebtoken:jjwt-impl:0.12.3' implementation 'io.jsonwebtoken:jjwt-jackson:0.12.3' } ​ - 0.11.5 버전 : build.gradle dependencies { implementation 'io.jsonwebtoken:jjwt-api:0.11.5' implementation 'io.jsonwebtoken:jjwt-impl:0.11.5' implementation 'io.jsonwebtoken:jjwt-jackson:0.11.5' } ​ - 의존성 BOM ​ Maven Repository: io.jsonwebtoken >> jjwt-api >> 0.12.3 바로가기 ​ Maven Repository: io.jsonwebtoken >> jjwt-api >> 0.11.5 바로가기 ​ 기본 Controller 생성 ​ - MainController import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ResponseBody; @Controller @ResponseBody public class MainController { @GetMapping("/") public String mainP() { return "main Controller"; } } ​ - AdminController import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ResponseBody; @Controller @ResponseBody public class AdminController { @GetMapping("/admin") public String adminP() { return "admin Controller"; } } ​ 이전 : 1. 실습 목표 및 간단한 동작 원리 다음 : 3. SecurityConfig 클래스 https://youtu.be/ZTaZOCqTez4 138, 스프링 시큐리티 JWT > 3. SecurityConfig 클래스 SecurityConfig 클래스 설명 ​ 스프링 시큐리티의 인가 및 설정을 담당하는 클래스이다. Security Config 구현은 스프링 시큐리티의 세부 버전별로 많이 상이합니다. (이번 시리즈는 스프링 시큐리티 6.2.1 버전으로 구현합니다.) ​ 자주 접할 수 있는 버전에 대한 구현 차이는 아래 영상을 통해 확인할 수 있습니다. - 스프링 시큐리티 시리즈 : 버전별 Security Config 구현 방법 스프링 시큐리티 : 버전별 Security Config 구현 방법 ​ ​ Security Config 클래스 기본 요소 작성 ​ 시큐리티 JWT 구현을 위한 Config 클래스의 일부분을 작성할 예정입니다. 먼저 기본적인 설정만 진행하고 시리즈를 진행하며 커스텀 필터 요소들을 추가 구현할 예정입니다. - SecurityConfig @Configuration @EnableWebSecurity public class SecurityConfig { @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { //csrf disable http .csrf((auth) -> auth.disable()); //From 로그인 방식 disable http .formLogin((auth) -> auth.disable()); //http basic 인증 방식 disable http .httpBasic((auth) -> auth.disable()); //경로별 인가 작업 http .authorizeHttpRequests((auth) -> auth .requestMatchers("/login", "/", "/join").permitAll() .requestMatchers("/admin").hasRole("ADMIN") .anyRequest().authenticated()); //세션 설정 http .sessionManagement((session) -> session .sessionCreationPolicy(SessionCreationPolicy.STATELESS)); return http.build(); } } ​ JWT를 통한 인증/인가를 위해서 세션을 STATELESS 상태로 설정하는 것이 중요하다. ​ BCryptPaasswordEncoder 등록 ​ - SecurityConfig @Configuration @EnableWebSecurity public class SecurityConfig { @Bean public BCryptPasswordEncoder bCryptPasswordEncoder() { return new BCryptPasswordEncoder(); } @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http .csrf((auth) -> auth.disable()); http .formLogin((auth) -> auth.disable()); http .httpBasic((auth) -> auth.disable()); http .authorizeHttpRequests((auth) -> auth .requestMatchers("/login", "/", "/join").permitAll() .anyRequest().authenticated()); http .sessionManagement((session) -> session .sessionCreationPolicy(SessionCreationPolicy.STATELESS)); return http.build(); } } ​ 이전 : 2. 프로젝트 생성 및 의존성 추가 다음 : 4. POSTMAN 설치 https://youtu.be/A3YsWHGbeZQ 139, 스프링 시큐리티 JWT > 4. POSTMAN 설치 API 서버와 요청 클라이언트 ​ API 서버는 웹서버와 달리 서버측으로 요청을 보낼 수 있는 페이지가 존재하지 않고 엔드 포인트만 존재하기 때문에 요청을 보낼 API 클라이언트가 필요하다. ​ POSTMAN ​ - 공식 홈페이지 주소 https://www.postman.com/downloads/ Download Postman | Get Started for Free Try Postman for free! Join 40 million users who rely on Postman, the collaboration platform for API development. Create better APIs—faster. www.postman.com ​ POSTMAN 호출 ​ ​ 이전 : 3. SecurityConfig 클래스 등록 다음 : 5. DB연결 및 Entity 작성 https://youtu.be/TN2rEgvQObM 140, 스프링 시큐리티 JWT > 5. DB연결 및 Entity 작성 데이터베이스 종류와 ORM ​ 회원 정보를 저장하기 위한 데이터베이스는 MySQL 엔진의 데이터베이스를 사용한다. 그리고 접근은 Spring Data JPA를 사용한다. ​ 데이터베이스 의존성 주석 해제 ​ 2강에서 진행했던 build.gradle의 Spring Data JPA 및 MySQL Driver 의존성 주석을 해제한다. ​ 변수 설정 ​ - DB 연결 설정 : application.properteis spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver spring.datasource.url=jdbc:mysql://아이피:3306/데이터베이스?useSSL=false&useUnicode=true&serverTimezone=Asia/Seoul&allowPublicKeyRetrieval=true spring.datasource.username=아이디 spring.datasource.password=비밀번호 ​ - Hibernate ddl 설정 : application.properites spring.jpa.hibernate.ddl-auto=none spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl ​ DB 연결에 대한 자세한 설명 ​ 스프링 부트 데이터베이스 2 : MySQL RDB 단일 연결 영상 바로가기 ​ 회원 테이블 Entity 작성 : UserEntity ​ - UserEntity @Entity @Setter @Getter public class UserEntity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; private String username; private String password; private String role; } ​ 회원 테이블 Repository 작성 : UserRepository ​ - UserRepository public interface UserRepository extends JpaRepository { } ​ ddl-auto=create 설정 후 실행 ​ 데이터베이스에서 회원 정보를 저장할 테이블을 생성해야 하지만 ddl-auto 설정을 통해 스프링 부트 Entity 클래스 기반으로 테이블을 생성할 수 있다. ​ 이전 : 4. POSTMAN 설치 다음 : 6. 회원가입 로직 구현 https://youtu.be/JFTpzy7gsg0 141, 스프링 시큐리티 JWT > 6. 회원가입 로직 구현 회원가입 로직 ​ ​ JoinDTO ​ - JoinDTO @Setter @Getter public class JoinDTO { private String username; private String password; } ​ JoinController ​ - JoinController @Controller @ResponseBody public class JoinController { private final JoinService joinService; public JoinController(JoinService joinService) { this.joinService = joinService; } @PostMapping("/join") public String joinProcess(JoinDTO joinDTO) { System.out.println(joinDTO.getUsername()); joinService.joinProcess(joinDTO); return "ok"; } } ​ JoinService ​ - JoinService @Service public class JoinService { private final UserRepository userRepository; private final BCryptPasswordEncoder bCryptPasswordEncoder; public JoinService(UserRepository userRepository, BCryptPasswordEncoder bCryptPasswordEncoder) { this.userRepository = userRepository; this.bCryptPasswordEncoder = bCryptPasswordEncoder; } public void joinProcess(JoinDTO joinDTO) { String username = joinDTO.getUsername(); String password = joinDTO.getPassword(); Boolean isExist = userRepository.existsByUsername(username); if (isExist) { return; } UserEntity data = new UserEntity(); data.setUsername(username); data.setPassword(bCryptPasswordEncoder.encode(password)); data.setRole("ROLE_ADMIN"); userRepository.save(data); } } ​ UserRepository ​ - UserRepository public interface UserRepository extends JpaRepository { Boolean existsByUsername(String username); } ​ 이전 : 5. DB연결 및 Entity 작성 다음 : 7. 로그인 필터 구현 https://youtu.be/yNACbJF4uoo 142, 스프링 시큐리티 JWT > 7. 로그인 필터 구현 자료 ​ - 스프링 시큐리티 필터 참고 자료 https://docs.spring.io/spring-security/reference/servlet/architecture.html Architecture :: Spring Security Spring Security / Servlet Applications / Architecture Architecture This section discusses Spring Security’s high-level architecture within Servlet based applications. We build on this high-level understanding within the Authentication , Authorization , and Protection Against Exploits sections of the... docs.spring.io ​ 로그인 모식도 ​ (정확한 스프링 시큐리티 내부 구조는 아닙니다. 완벽한 구조를 이해하시기 위해선 "스프링 시큐리티 내부 구조" 시리즈를 시청하시는 것을 추천드립니다.) ​ https://www.youtube.com/playlist?list=PLJkjrxxiBSFCFM0pjDwm6F98veieD0MER 스프링 시큐리티 내부 구조 스프링 시큐리티 내부 동작 원리와 구조를 학습하는 시리즈입니다. www.youtube.com ​ 스프링 시큐리티 필터 동작 원리 ​ 스프링 시큐리티는 클라이언트의 요청이 여러개의 필터를 거쳐 DispatcherServlet(Controller)으로 향하는 중간 필터에서 요청을 가로챈 후 검증(인증/인가)을 진행한다. - 클라이언트 요청 → 서블릿 필터 → 서블릿 (컨트롤러) ​ - Delegating Filter Proxy 서블릿 컨테이너 (톰캣)에 존재하는 필터 체인에 DelegatingFilter를 등록한 뒤 모든 요청을 가로챈다. ​ ​ - 서블릿 필터 체인의 DelegatingFilter → Security 필터 체인 (내부 처리 후) → 서블릿 필터 체인의 DelegatingFilter 가로챈 요청은 SecurityFilterChain에서 처리 후 상황에 따른 거부, 리디렉션, 서블릿으로 요청 전달을 진행한다. ​ ​ - SecurityFilterChain의 필터 목록과 순서 ​ ​ (모든 필터는 전부 활성화되지 않습니다.) ​ Form 로그인 방식에서 UsernamePasswordAuthenticationFilter ​ Form 로그인 방식에서는 클라이언트단이 username과 password를 전송한 뒤 Security 필터를 통과하는데 UsernamePasswordAuthentication 필터에서 회원 검증을 진행을 시작한다. (회원 검증의 경우 UsernamePasswordAuthenticationFilter가 호출한 AuthenticationManager를 통해 진행하며 DB에서 조회한 데이터를 UserDetailsService를 통해 받음) 우리의 JWT 프로젝트는 SecurityConfig에서 formLogin 방식을 disable 했기 때문에 기본적으로 활성화 되어 있는 해당 필터는 동작하지 않는다. 따라서 로그인을 진행하기 위해서 필터를 커스텀하여 등록해야 한다. ​ 로그인 로직 구현 목표 ​ - 아이디, 비밀번호 검증을 위한 커스텀 필터 작성 - DB에 저장되어 있는 회원 정보를 기반으로 검증할 로직 작성 - 로그인 성공시 JWT를 반환할 success 핸들러 생성 - 커스텀 필터 SecurityConfig에 등록 ​ 로그인 요청 받기 : 커스텀 UsernamePasswordAuthentication 필터 작성 ​ 로그인 검증을 위한 커스텀 UsernamePasswordAuthentication 필터 작성 - LoginFilter public class LoginFilter extends UsernamePasswordAuthenticationFilter { private final AuthenticationManager authenticationManager; public LoginFilter(AuthenticationManager authenticationManager) { this.authenticationManager = authenticationManager; } @Override public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException { //클라이언트 요청에서 username, password 추출 String username = obtainUsername(request); String password = obtainPassword(request); //스프링 시큐리티에서 username과 password를 검증하기 위해서는 token에 담아야 함 UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(username, password, null); //token에 담은 검증을 위한 AuthenticationManager로 전달 return authenticationManager.authenticate(authToken); } //로그인 성공시 실행하는 메소드 (여기서 JWT를 발급하면 됨) @Override protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authentication) { } //로그인 실패시 실행하는 메소드 @Override protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException failed) { } } ​ SecurityConfig 설정 ​ - SecurityConfig : 커스텀 로그인 필터 등록 @Configuration @EnableWebSecurity public class SecurityConfig { @Bean public BCryptPasswordEncoder bCryptPasswordEncoder() { return new BCryptPasswordEncoder(); } @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http .csrf((auth) -> auth.disable()); http .formLogin((auth) -> auth.disable()); http .httpBasic((auth) -> auth.disable()); http .authorizeHttpRequests((auth) -> auth .requestMatchers("/login", "/", "/join").permitAll() .anyRequest().authenticated()); //필터 추가 LoginFilter()는 인자를 받음 (AuthenticationManager() 메소드에 authenticationConfiguration 객체를 넣어야 함) 따라서 등록 필요 http .addFilterAt(new LoginFilter(), UsernamePasswordAuthenticationFilter.class); http .sessionManagement((session) -> session .sessionCreationPolicy(SessionCreationPolicy.STATELESS)); return http.build(); } } ​ - SecurityConfig : AuthenticationMananger Bean 등록과 LoginFilter 인수 전달 @Configuration @EnableWebSecurity public class SecurityConfig { //AuthenticationManager가 인자로 받을 AuthenticationConfiguraion 객체 생성자 주입 private final AuthenticationConfiguration authenticationConfiguration; public SecurityConfig(AuthenticationConfiguration authenticationConfiguration) { this.authenticationConfiguration = authenticationConfiguration; } //AuthenticationManager Bean 등록 @Bean public AuthenticationManager authenticationManager(AuthenticationConfiguration configuration) throws Exception { return configuration.getAuthenticationManager(); } @Bean public BCryptPasswordEncoder bCryptPasswordEncoder() { return new BCryptPasswordEncoder(); } @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http .csrf((auth) -> auth.disable()); http .formLogin((auth) -> auth.disable()); http .httpBasic((auth) -> auth.disable()); http .authorizeHttpRequests((auth) -> auth .requestMatchers("/login", "/", "/join").permitAll() .anyRequest().authenticated()); //필터 추가 LoginFilter()는 인자를 받음 (AuthenticationManager() 메소드에 authenticationConfiguration 객체를 넣어야 함) 따라서 등록 필요 http .addFilterAt(new LoginFilter(authenticationManager(authenticationConfiguration)), UsernamePasswordAuthenticationFilter.class); http .sessionManagement((session) -> session .sessionCreationPolicy(SessionCreationPolicy.STATELESS)); return http.build(); } } ​ 로그인 성공시 JWT 반환 ​ 로그인 성공시 successfulAuthentication() 메소드를 통해 JWT를 응답해야 한다. 따라서 JWT 응답 구문을 작성해야 하는데 JWT 발급 클래스를 아직 생성하지 않았기 때문에 다음 시간에 DB 기반 회원 검증 구현을 진행한 뒤 JWT 발급 및 검증을 진행하는 클래스를 생성하겠습니다. 이전 : 6. 회원가입 로직 구현 다음 : 8. DB기반 로그인 검증 로직 https://youtu.be/3Ff7UHGG3t8 143, 스프링 시큐리티 JWT > 8. DB기반 로그인 검증 로직 DB 기반 로그인 검증 ​ ​ 저번 7강을 통해 AuthenticationManager 앞단을 구현했고 이번 8강에서 DB에서 AuthenticationManager까지 로직을 구현하겠습니다. 구현은 UserDetails, UserDetailsService, UserRepository의 회원 조회 메소드를 진행하겠습니다. ​ UserRepository ​ - UserRepository public interface UserRepository extends JpaRepository { Boolean existsByUsername(String username); //username을 받아 DB 테이블에서 회원을 조회하는 메소드 작성 UserEntity findByUsername(String username); } ​ UserDetailsService 커스텀 구현 ​ - CustomUserDetailsService @Service public class CustomUserDetailsService implements UserDetailsService { private final UserRepository userRepository; public CustomUserDetailsService(UserRepository userRepository) { this.userRepository = userRepository; } @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { //DB에서 조회 UserEntity userData = userRepository.findByUsername(username); if (userData != null) { //UserDetails에 담아서 return하면 AutneticationManager가 검증 함 return new CustomUserDetails(userData); } return null; } } ​ UserDetails 커스텀 구현 ​ - CustomUserDetails public class CustomUserDetails implements UserDetails { private final UserEntity userEntity; public CustomUserDetails(UserEntity userEntity) { this.userEntity = userEntity; } @Override public Collection getAuthorities() { Collection collection = new ArrayList<>(); collection.add(new GrantedAuthority() { @Override public String getAuthority() { return userEntity.getRole(); } }); return collection; } @Override public String getPassword() { return userEntity.getPassword(); } @Override public String getUsername() { return userEntity.getUsername(); } @Override public boolean isAccountNonExpired() { return true; } @Override public boolean isAccountNonLocked() { return true; } @Override public boolean isCredentialsNonExpired() { return true; } @Override public boolean isEnabled() { return true; } } ​ 이전 : 7. 로그인 필터 구현 다음 : 9. JWT 발급 및 검증 클래스 https://youtu.be/q4eTHvQAvRo 144, 스프링 시큐리티 JWT > 9. JWT 발급 및 검증 클래스 JWT 발급과 검증 ​ - 로그인시 → 성공 → JWT 발급 - 접근시 → JWT 검증 JWT에 관해 발급과 검증을 담당할 클래스가 필요하다. 따라서 JWTUtil이라는 클래스를 생성하여 JWT 발급, 검증 메소드를 작성하는 시간입니다. ​ JWT 생성 원리 ​ https://www.jwt.io/ JSON Web Tokens - jwt.io JSON Web Token (JWT) is a compact URL-safe means of representing claims to be transferred between two parties. The claims in a JWT are encoded as a JSON object that is digitally signed using JSON Web Signature (JWS). www.jwt.io ​ JWT는 Header.Payload.Signature 구조로 이루어져 있다. 각 요소는 다음 기능을 수행한다. - Header - JWT임을 명시 - 사용된 암호화 알고리즘 - Payload - 정보 - Signature - 암호화알고리즘((BASE64(Header))+(BASE64(Payload)) + 암호화키) JWT의 특징은 내부 정보를 단순 BASE64 방식으로 인코딩하기 때문에 외부에서 쉽게 디코딩 할 수 있다. ​ 외부에서 열람해도 되는 정보를 담아야하며, 토큰 자체의 발급처를 확인하기 위해서 사용한다. ​ (지폐와 같이 외부에서 그 금액을 확인하고 금방 외형을 따라서 만들 수 있지만 발급처에 대한 보장 및 검증은 확실하게 해야하는 경우에 사용한다. 따라서 토큰 내부에 비밀번호와 같은 값 입력 금지) ​ JWT 암호화 방식 ​ - 암호화 종류 - 양방향 - 대칭키 - 이 프로젝트는 양방향 대칭키 방식 사용 : HS256 - 비대칭키 - 단방향 ​ 암호화 키 저장 ​ 암호화 키는 하드코딩 방식으로 구현 내부에 탑재하는 것을 지양하기 때문에 변수 설정 파일에 저장한다. - application.properties spring.jwt.secret=vmfhaltmskdlstkfkdgodyroqkfwkdbalroqkfwkdbalaaaaaaaaaaaaaaaabbbbb ​ JWTUtil ​ - 토큰 Payload에 저장될 정보 - username - role - 생성일 - 만료일 - JWTUtil 구현 메소드 - JWTUtil 생성자 - username 확인 메소드 - role 확인 메소드 - 만료일 확인 메소드 - JWTUtil : 0.12.3 @Component public class JWTUtil { private SecretKey secretKey; public JWTUtil(@Value("${spring.jwt.secret}")String secret) { secretKey = new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), Jwts.SIG.HS256.key().build().getAlgorithm()); } public String getUsername(String token) { return Jwts.parser().verifyWith(secretKey).build().parseSignedClaims(token).getPayload().get("username", String.class); } public String getRole(String token) { return Jwts.parser().verifyWith(secretKey).build().parseSignedClaims(token).getPayload().get("role", String.class); } public Boolean isExpired(String token) { return Jwts.parser().verifyWith(secretKey).build().parseSignedClaims(token).getPayload().getExpiration().before(new Date()); } public String createJwt(String username, String role, Long expiredMs) { return Jwts.builder() .claim("username", username) .claim("role", role) .issuedAt(new Date(System.currentTimeMillis())) .expiration(new Date(System.currentTimeMillis() + expiredMs)) .signWith(secretKey) .compact(); } } ​ - JWTUtil : 0.11.5 @Component public class JWTUtil { private Key key; public JWTUtil(@Value("${spring.jwt.secret}")String secret) { byte[] byteSecretKey = Decoders.BASE64.decode(secret); key = Keys.hmacShaKeyFor(byteSecretKey); } public String getUsername(String token) { return Jwts.parserBuilder().setSigningKey(key).build().parseClaimsJws(token).getBody().get("username", String.class); } public String getRole(String token) { return Jwts.parserBuilder().setSigningKey(key).build().parseClaimsJws(token).getBody().get("role", String.class); } public Boolean isExpired(String token) { return Jwts.parserBuilder().setSigningKey(key).build().parseClaimsJws(token).getBody().getExpiration().before(new Date()); } public String createJwt(String username, String role, Long expiredMs) { Claims claims = Jwts.claims(); claims.put("username", username); claims.put("role", role); return Jwts.builder() .setClaims(claims) .setIssuedAt(new Date(System.currentTimeMillis())) .setExpiration(new Date(System.currentTimeMillis() + expiredMs)) .signWith(key, SignatureAlgorithm.HS256) .compact(); } } ​ 이전 : 8. DB기반 로그인 검증 로직 다음 : 10. 로그인 성공 JWT 발급 https://youtu.be/obNHwsl0fXM 145, 스프링 시큐리티 JWT > 10. 로그인 성공 JWT 발급 로그인 성공 ​ 7 ~ 9강을 통해 로그인 로직, JWTUtil 클래스를 생성하였습니다. 이제 로그인이 성공 했을 경우 JWT를 발급하기 위한 구현을 진행하겠습니다. ​ JWTUtil 주입 ​ - LoginFilter : JWTUtil 주입 public class LoginFilter extends UsernamePasswordAuthenticationFilter { private final AuthenticationManager authenticationManager; //JWTUtil 주입 private final JWTUtil jwtUtil; public LoginFilter(AuthenticationManager authenticationManager, JWTUtil jwtUtil) { this.authenticationManager = authenticationManager; this.jwtUtil = jwtUtil; } @Override public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException { //클라이언트 요청에서 username, password 추출 String username = obtainUsername(request); String password = obtainPassword(request); //스프링 시큐리티에서 username과 password를 검증하기 위해서는 token에 담아야 함 UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(username, password, null); //token에 담은 검증을 위한 AuthenticationManager로 전달 return authenticationManager.authenticate(authToken); } //로그인 성공시 실행하는 메소드 (여기서 JWT를 발급하면 됨) @Override protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authentication) { } //로그인 실패시 실행하는 메소드 @Override protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException failed) { } } ​ - SecurityConfig에서 Filter에 JWTUtil 주입​ @Configuration @EnableWebSecurity public class SecurityConfig { private final AuthenticationConfiguration authenticationConfiguration; //JWTUtil 주입 private final JWTUtil jwtUtil; public SecurityConfig(AuthenticationConfiguration authenticationConfiguration, JWTUtil jwtUtil) { this.authenticationConfiguration = authenticationConfiguration; this.jwtUtil = jwtUtil; } @Bean public AuthenticationManager authenticationManager(AuthenticationConfiguration configuration) throws Exception { return configuration.getAuthenticationManager(); } @Bean public BCryptPasswordEncoder bCryptPasswordEncoder() { return new BCryptPasswordEncoder(); } @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http .csrf((auth) -> auth.disable()); http .formLogin((auth) -> auth.disable()); http .httpBasic((auth) -> auth.disable()); http .authorizeHttpRequests((auth) -> auth .requestMatchers("/login", "/", "/join").permitAll() .anyRequest().authenticated()); //AuthenticationManager()와 JWTUtil 인수 전달 http .addFilterAt(new LoginFilter(authenticationManager(authenticationConfiguration), jwtUtil), UsernamePasswordAuthenticationFilter.class); http .sessionManagement((session) -> session .sessionCreationPolicy(SessionCreationPolicy.STATELESS)); return http.build(); } } ​ LoginFilter 로그인 성공 successfulAuthentication 메소드 구현 ​ - LoginFilter public class LoginFilter extends UsernamePasswordAuthenticationFilter { @Override protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authentication) { //UserDetails CustomUserDetails customUserDetails = (CustomUserDetails) authentication.getPrincipal(); String username = customUserDetails.getUsername(); Collection authorities = authentication.getAuthorities(); Iterator iterator = authorities.iterator(); GrantedAuthority auth = iterator.next(); String role = auth.getAuthority(); String token = jwtUtil.createJwt(username, role, 60*60*10L); response.addHeader("Authorization", "Bearer " + token); } } ​ HTTP 인증 방식은 RFC 7235 정의에 따라 아래 인증 헤더 형태를 가져야 한다. Authorization: 타입 인증토큰 //예시 Authorization: Bearer 인증토큰string ​ LoginFilter 로그인 실패 unsuccessfulAuthentication 메소드 구현 ​ - LoginFilter public class LoginFilter extends UsernamePasswordAuthenticationFilter { private final AuthenticationManager authenticationManager; private final JWTUtil jwtUtil; public LoginFilter(AuthenticationManager authenticationManager, JWTUtil jwtUtil) { this.authenticationManager = authenticationManager; this.jwtUtil = jwtUtil; } @Override protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException failed) { //로그인 실패시 401 응답 코드 반환 response.setStatus(401); } } ​ 발급 테스트 ​ /login 경로로 username과 password를 포함한 POST 요청을 보낸 후 응답 헤더에서 Authorization 키에 담긴 JWT를 확인한다. - 요청 : POST /login ​ - 응답 ​ LoginFilter 최종 ​ public class LoginFilter extends UsernamePasswordAuthenticationFilter { private final AuthenticationManager authenticationManager; private final JWTUtil jwtUtil; public LoginFilter(AuthenticationManager authenticationManager, JWTUtil jwtUtil) { this.authenticationManager = authenticationManager; this.jwtUtil = jwtUtil; } @Override public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException { String username = obtainUsername(request); String password = obtainPassword(request); UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(username, password, null); return authenticationManager.authenticate(authToken); } @Override protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authentication) { CustomUserDetails customUserDetails = (CustomUserDetails) authentication.getPrincipal(); String username = customUserDetails.getUsername(); Collection authorities = authentication.getAuthorities(); Iterator iterator = authorities.iterator(); GrantedAuthority auth = iterator.next(); String role = auth.getAuthority(); String token = jwtUtil.createJwt(username, role, 60*60*10L); response.addHeader("Authorization", "Bearer " + token); } @Override protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException failed) { response.setStatus(401); } } ​ 이전 : 9. JWT 발급 및 검증 클래스 다음 : 11. JWT 검증 필터 https://youtu.be/nH3A22izjY0 146, 스프링 시큐리티 JWT > 11. JWT 검증 필터 JWT 검증 필터 ​ 스프링 시큐리티 filter chain에 요청에 담긴 JWT를 검증하기 위한 커스텀 필터를 등록해야 한다. ​ 해당 필터를 통해 요청 헤더 Authorization 키에 JWT가 존재하는 경우 JWT를 검증하고 강제로SecurityContextHolder에 세션을 생성한다. (이 세션은 STATLESS 상태로 관리되기 때문에 해당 요청이 끝나면 소멸 된다.) ​ JWTFilter 구현 ​ - JWTFilter public class JWTFilter extends OncePerRequestFilter { private final JWTUtil jwtUtil; public JWTFilter(JWTUtil jwtUtil) { this.jwtUtil = jwtUtil; } @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { //request에서 Authorization 헤더를 찾음 String authorization= request.getHeader("Authorization"); //Authorization 헤더 검증 if (authorization == null || !authorization.startsWith("Bearer ")) { System.out.println("token null"); filterChain.doFilter(request, response); //조건이 해당되면 메소드 종료 (필수) return; } System.out.println("authorization now"); //Bearer 부분 제거 후 순수 토큰만 획득 String token = authorization.split(" ")[1]; //토큰 소멸 시간 검증 if (jwtUtil.isExpired(token)) { System.out.println("token expired"); filterChain.doFilter(request, response); //조건이 해당되면 메소드 종료 (필수) return; } //토큰에서 username과 role 획득 String username = jwtUtil.getUsername(token); String role = jwtUtil.getRole(token); //userEntity를 생성하여 값 set UserEntity userEntity = new UserEntity(); userEntity.setUsername(username); userEntity.setPassword("temppassword"); userEntity.setRole(role); //UserDetails에 회원 정보 객체 담기 CustomUserDetails customUserDetails = new CustomUserDetails(userEntity); //스프링 시큐리티 인증 토큰 생성 Authentication authToken = new UsernamePasswordAuthenticationToken(customUserDetails, null, customUserDetails.getAuthorities()); //세션에 사용자 등록 SecurityContextHolder.getContext().setAuthentication(authToken); filterChain.doFilter(request, response); } } ​ SecurityConfig JWTFilter 등록 ​ - SecurityConfig @Configuration @EnableWebSecurity public class SecurityConfig { private final AuthenticationConfiguration authenticationConfiguration; private final JWTUtil jwtUtil; public SecurityConfig(AuthenticationConfiguration authenticationConfiguration, JWTUtil jwtUtil) { this.authenticationConfiguration = authenticationConfiguration; this.jwtUtil = jwtUtil; } @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http .csrf((auth) -> auth.disable()); http .formLogin((auth) -> auth.disable()); http .httpBasic((auth) -> auth.disable()); http .authorizeHttpRequests((auth) -> auth .requestMatchers("/login", "/", "/join").permitAll() .anyRequest().authenticated()); //JWTFilter 등록 http .addFilterBefore(new JWTFilter(jwtUtil), LoginFilter.class); http .addFilterAt(new LoginFilter(authenticationManager(authenticationConfiguration), jwtUtil), UsernamePasswordAuthenticationFilter.class); http .sessionManagement((session) -> session .sessionCreationPolicy(SessionCreationPolicy.STATELESS)); return http.build(); } } ​ JWT 요청 인가 테스트 ​ 요청 헤더에 JWT를 첨부하고 로그인이 권한이 필요한 페이지에 접근을 진행하겠습니다. ​ ​ 이전 : 10. 로그인 성공 JWT 발급 다음 : 12. 세션 정보 https://youtu.be/7B6KHSZN3jY 147, 스프링 시큐리티 JWT > 12. 세션 정보 JWTFilter를 통과한 뒤 세션 확인 ​ @Controller @ResponseBody public class MainController { @GetMapping("/") public String mainP() { String name = SecurityContextHolder.getContext().getAuthentication().getName(); return "Main Controller : "+name; } } ​ 세션 현재 사용자 아이디 ​ SecurityContextHolder.getContext().getAuthentication().getName(); ​ 세션 현재 사용자 role ​ Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); Collection authorities = authentication.getAuthorities(); Iterator iter = authorities.iterator(); GrantedAuthority auth = iter.next(); String role = auth.getAuthority(); ​ 이전 : 11. JWT 검증 필터 다음 : 13. CORS 설정 https://youtu.be/Y1p6bVrRExs 148, 스프링 시큐리티 JWT > 13. CORS 설정 자료 ​ https://docs.spring.io/spring-security/reference/servlet/integrations/cors.html CORS :: Spring Security Spring Security / Servlet Applications / Integrations / Spring’s CORS Support CORS Spring Framework provides first class support for CORS . CORS must be processed before Spring Security, because the pre-flight request does not contain any cookies (that is, the JSESSIONID ). If the request does not c... docs.spring.io ​ CORS란? ​ https://ko.wikipedia.org/wiki/%EA%B5%90%EC%B0%A8_%EC%B6%9C%EC%B2%98_%EB%A6%AC%EC%86%8C%EC%8A%A4_%EA%B3%B5%EC%9C%A0 교차 출처 리소스 공유 - 위키백과, 우리 모두의 백과사전 교차 출처 리소스 공유 (Cross-origin resource sharing, CORS ), 교차 출처 자원 공유 는 웹 페이지 상의 제한된 리소스 를 최초 자원이 서비스된 도메인 밖의 다른 도메인 으로부터 요청할 수 있게 허용하는 구조이다. [ 1 ] 웹페이지는 교차 출처 이미지, 스타일시트 , 스크립트, iframe , 동영상을 자유로이 임베드할 수 있다. [ 2 ] 다만 특정 교차 도메인 간(cross-domain) 요청, 특히 Ajax 요청은 동일-출처 보안 정책 에 의해 기본적으로 금지된다. CORS는 교차 출처 요청을 ... ko.wikipedia.org ​ 발생 원리 ​ ​ CORS 설정 ​ - SecurityConfig @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http .cors((corsCustomizer -> corsCustomizer.configurationSource(new CorsConfigurationSource() { @Override public CorsConfiguration getCorsConfiguration(HttpServletRequest request) { CorsConfiguration configuration = new CorsConfiguration(); configuration.setAllowedOrigins(Collections.singletonList("http://localhost:3000")); configuration.setAllowedMethods(Collections.singletonList("*")); configuration.setAllowCredentials(true); configuration.setAllowedHeaders(Collections.singletonList("*")); configuration.setMaxAge(3600L); configuration.setExposedHeaders(Collections.singletonList("Authorization")); return configuration; } }))); return http.build(); } ​ - config>CorsMvcConfig​ @Configuration public class CorsMvcConfig implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry corsRegistry) { corsRegistry.addMapping("/**") .allowedOrigins("http://localhost:3000"); } } ​ 이전 : 12. 세션 정보 다음 : 14. JWT의 목표 https://youtu.be/MGkYFwdabeM 149, 스프링 시큐리티 JWT > 14. JWT의 궁극적인 목표 주관적으로 제가 했었던 생각을 공유하고자 작성한 글입니다. 개발 자체가 모든 방향에서 항상 정답일 수 없듯이 잘 이해해서 들어주시면 감사하겠습니다. ​ JWT를 깊게 생각하며 ​ JWT 공부를 시작했을 때 JWT를 왜 사용하는지를 잊어버려 한동안 고민에 잠겼고 결론을 찾아 헤매었던 적이 있습니다. 그 고민의 흐름과 주관적인 결론을 남깁니다. - JWT의 STATELESS 상태에 대한 집착 시큐리티 JWT config를 구성하며 STATELESS 상태에 초점이 맞추어졌습니다. (JWT 구현을 위해 STATELESS 상태가 필요하지만 STATELESS에 집착해야 하는건 아닙니다. 따라서 여기서 포인트 자체를 놓쳤습니다. 아무튼 이 과정을 작성하며 STATELESS 상태에 광적으로 집착을 하였습니다.) - 토큰 탈취의 문제 - Refresh 토큰의 도입과 Refresh 토큰도 동일한 상황 이때 부터 의문 사항이 생기게 되는 시발점입니다. JWT 자체가 세션 대비 토큰을 탈취 당했을때의 위험성이 큽니다. 따라서 Refresh, Access라는 2가지의 토큰을 발급해주는데 Refresh 토큰 요청 주기 자체가 길기 때문에 탈취 당할 확률은 낮지만 탈취 당할 수 있다 입니다. 이제 이 문제에 대한 여러 상황이 발생합니다. - 토큰이 탈취 되었을때 서버의 제어권과 로그아웃 문제 등등 토큰이 탈취되면 만료 기간 까지 서버측은 고통을 받습니다. 따라서 서버 비밀키를 변경하는 상황까지 도달하게 됩니다. 프론트 서버측 로그아웃을 구현하여도 이미 토큰을 복제 했다면 계속 서버에 접속할 수 있기 때문에 여전히 문제가 있습니다. 이를 위해 서버측 Redis와 같은 저장소에 발급한 Refresh 토큰을 저장한다는 구현들이 많았습니다. 그래서 로그아웃 상태거나 탈취된 토큰은 Redis 서버에서 제거하여 앞으로 Access 토큰 재발급이 불가능하도록 설정하는 것이었습니다. - 깊은 고민의 발생 - 모순? Refresh들을 저장하기 위한 Redis를 도입해버리면 사실상 세션 클러스터링을 작업하고 세션 방식을 사용하는 것이 좋지 않을까? STATELESS 작업을 했지만 다른 곳에서 상태 저장이 생겨버리네? (사실 엄밀하게는 아니지만 비슷한 맥락으로) 아무튼 여기까지해서 많은 고민을 했고 탈취를 막으면서도 Redis를 도입하지 않을 방법에 대해서 한가지 방법을 떠올렸습니다. - IP 검증을 해보자 - 실패 처음 로그인이 요청된 IP를 JWT에 담아 매번 요청이 올때마다 JWT의 IP와 요청 IP가 동일한지 검증을 진행하는 방법을 구상했는데 사용자들의 단말기는 IP값이 동적으로 자주 변경되기 때문에 문제가 되어 실패했습니다. 그래서 고민의 굴레에 빠졌습니다. STATELESS → 그런데 Redis → 그럼 차라리 세션 → 왜 JWT를 사용했지? JWT를 왜 사용하는가? ​ - 독일의 철학자 한나 아렌트의 “만드는 사람과 만드는 동물” → 나는 만드는 동물인가? ​ 위와 같이 꼬리에 꼬리를 무는 고민에 해답은 목표가 무엇인지 판단하는 것이었다. ​ 한나 아렌트에 의하면 인간은 어떤 일에 몰두하는 존재지만 동시에 판단하는 존재인 “만드는 사람”이다. 우리가 JWT의 목적을 확인하지 않고 구현에만 열중한다면 무엇을 하는지도 모르는 “만드는 동물”에 불과하다. 따라서 JWT의 STATELESS한 상태에만 목적을 두는 것이 아닌 JWT가 왜 필요한지를 생각했고 해답을 찾았다. ​ JWT를 사용한 이유 ​ - 모바일 앱 JWT가 사용된 주 이유는 결국 모바일 앱의 등장입니다. 모바일 앱의 특성상 주로 JWT 방식으로 인증/인가를 진행합니다. 결국 STATLESS는 부수적인 효과였습니다. - 모바일 앱에서의 로그아웃 모바일 앱에서는 JWT 탈취 우려가 거의 없기 때문에 앱단에서 로그아웃을 진행하여 JWT 자체를 제거해버리면 서버측에선 추가 조치도 필요가 없습니다. (토큰 자체가 확실하게 없어졌다는 보장이 되기 때문에) - 장시간 로그인과 세션 장기간 동안 로그인 상태를 유지하려고 세션 설정을 하면 서버 측 부하가 많이 가기 때문에 JWT 방식을 이용하는 것도 한 방법입니다. ​ API 서버에서 Refresh 토큰을 저장하여 어느 정도의 상태(STATE)를 만드는 이유 ​ 이제는 상태를 남기는것에 대해서 큰 고민은 없어졌습니다. JWT의 목적이 STATELESS가 아니기 때문이니까요. ​ 이전 : 13. CORS 설정 https://youtu.be/qIG-GNorXG4 150, 스프링 시큐리티 JWT > LoginFilter JSON 요청 받기 로그인 데이터 JSON으로 받기 ​ 기존 작성된 LoginFilter의 경우 multipart/form-data 형태의 데이터를 응답 받도록 설계되어 있습니다. ​ 7. 로그인 필터 구현 다만 프론트에서는 fetch나 axios를 통해 JSON 형태로 만들어서 전송하는 경우가 많기 때문에 LoginFilter에서 JSON 형태의 데이터를 받을 수 있도록 설정하겠습니다. ​ 요청 형태 : JSON ​ { "username": "devyummi", "password": "1234" } ​ 구현 ​ - 데이터를 받을 LoginDTO 작성 @Getter @Setter public class LoginDTO { private String username; private String password; } ​ - LoginFilter 일부 수정 LoginDTO loginDTO = new LoginDTO(); try { ObjectMapper objectMapper = new ObjectMapper(); ServletInputStream inputStream = request.getInputStream(); String messageBody = StreamUtils.copyToString(inputStream, StandardCharsets.UTF_8); loginDTO = objectMapper.readValue(messageBody, LoginDTO.class); } catch (IOException e) { throw new RuntimeException(e); } System.out.println(loginDTO.getUsername()); String username = loginDTO.getUsername(); String password = loginDTO.getPassword(); ​ 기존의 obtainUsername(request)와 obtainPassword(request) 대신 위의 코드를 통해 username, password를 JSON 요청으로 부터 받으실 수 있습니다. ​ 151, OpenAI Chat GPT 5 출시 및 API 가격 ​ https://openai.com/ko-KR/api/pricing/ ​ ​ 기존 4.1 시리즈 보다 저렴합니다. (성능은 up) ​ ​ https://platform.openai.com/docs/pricing OpenAI Platform Explore developer resources, tutorials, API docs, and dynamic examples to get the most out of OpenAI's platform. platform.openai.com 152, 스프링 + 리액트 로그인 > 10. User API 작성 및 로그인 API 작성 ​ User 도메인 일부 로직과 자체 로그인 시스템을 구현했습니다. 따라서 API를 만들고 중간 테스트를 진행하겠습니다. ​ Valid 검증 ​ API를 만들고 프론트로 부터 DTO 데이터를 받기 전에 간단하게 Valid 검증을 할 수 있도록 Valid 의존성을 추가하겠습니다. ​ - build.gradle > dependencies implementation 'org.springframework.boot:spring-boot-starter-validation' ​ - domain > user > dto > UserRequestDTO.java ​ 우선 User 도메인에 대해서 먼저 Valid 검증을 추가하겠습니다. ​ import jakarta.validation.constraints.Email; import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.Size; import lombok.Getter; import lombok.Setter; @Getter @Setter public class UserRequestDTO { public interface existGroup {} // 회원 가입시 username 존재 확인 public interface addGroup {} // 회원 가입시 public interface passwordGroup {} // 비밀번호 변경시 public interface updateGroup {} // 회원 수정시 public interface deleteGroup {} // 회원 삭제시 @NotBlank(groups = {existGroup.class, addGroup.class, updateGroup.class, deleteGroup.class}) @Size(min = 4) private String username; @NotBlank(groups = {addGroup.class, passwordGroup.class}) @Size(min = 4) private String password; @NotBlank(groups = {addGroup.class, updateGroup.class}) private String nickname; @Email(groups = {addGroup.class, updateGroup.class}) private String email; } ​ 등록을 했고, Controller에서 Valid 체크를 진행하시면 됩니다. ​ UserController 작성 ​ User 도메인 관련 API들을 뽑아줄 Controller 클래스를 작성하겠습니다. 우선 클래스 등록과 필요한 메소드를 주석으로 달아보겠습니다. ​ ​ - api > UserController.java import org.example.backend.domain.user.service.UserService; import org.springframework.web.bind.annotation.RestController; @RestController public class UserController { private final UserService userService; public UserController(UserService userService) { this.userService = userService; } // 자체 로그인 유저 존재 확인 // 회원가입 // 유저 정보 // 유저 수정 (자체 로그인 유저만) // 유저 제거 (자체/소셜) } ​ 회원 가입 API 메소드 등록 ​ 간단하게 회원 가입용 API 등록 후 테스트를 진행하겠습니다. ​ - api > UserController.java : 메소드 추가 import org.example.backend.domain.user.dto.UserRequestDTO; import org.example.backend.domain.user.service.UserService; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; import java.util.Collections; import java.util.Map; @RestController public class UserController { private final UserService userService; public UserController(UserService userService) { this.userService = userService; } // 자체 로그인 유저 존재 확인 @PostMapping(value = "/user/exist", consumes = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity existUserApi( @Validated(UserRequestDTO.existGroup.class) @RequestBody UserRequestDTO dto ) { return ResponseEntity.ok(userService.existUser(dto)); } // 회원가입 @PostMapping(value = "/user", consumes = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity> joinApi( @Validated(UserRequestDTO.addGroup.class) @RequestBody UserRequestDTO dto ) { Long id = userService.addUser(dto); Map responseBody = Collections.singletonMap("userEntityId", id); return ResponseEntity.status(201).body(responseBody); } // 유저 정보 // 유저 수정 (자체 로그인 유저만) // 유저 제거 (자체/소셜) } ​ 테스트 ​ 테스트는 회원 가입 이후, 자체 로그인을 수행하여 JWT가 Body로 담겨오는지 확인하겠습니다. ​ 이전 : 9. 백엔드 : 자체 로그인 성공 핸들러 다음 : 11. 백엔드 : 소셜 로그인 설정 https://youtu.be/0SAgszH2q4Q 153, 스프링 + 리액트 로그인 > 11. 백엔드 : 소셜 로그인 설정 모식도 ​ ​ 소셜 로그인 설정 ​ 소셜 로그인을 위한 SecurityConfig 설정, application.properties 변수 등록, Service단 메소드 설정을 진행하겠습니다. 소셜 로그인 또한 시큐리티, OAuth2 클라이언트 의존성의 규칙을 많이 따라주어야 합니다. ​ ​ SecurityConfig SecurityFilterChain에 OAuth2 필터 enable ​ SecurityFilterChain에 소셜 로그인 관련된 필터들도 활성화 시키겠습니다. ​ - config > SecurityConfig.java : SecurityFilterChain 설정 추가 // OAuth2 인증용 http .oauth2Login(oauth2 -> oauth2 .successHandler()); ​ 네이버, 구글 소셜 로그인 신청 application.properties 변수 등록 ​ 소셜 로그인용 필터는 활성화 되었지만, 필터에서 "네이버", "구글"측에 소셜 로그인 진행을 위한 요청을 보내기 위해선 application.properties에 변수 설정이 요구됩니다. ​ - application.properties # OAuth2 : NAVER registration spring.security.oauth2.client.registration.naver.client-name=naver spring.security.oauth2.client.registration.naver.client-id= spring.security.oauth2.client.registration.naver.client-secret= spring.security.oauth2.client.registration.naver.redirect-uri=http://localhost:8080/login/oauth2/code/naver spring.security.oauth2.client.registration.naver.authorization-grant-type=authorization_code spring.security.oauth2.client.registration.naver.scope=name,email spring.security.oauth2.client.provider.naver.authorization-uri=https://nid.naver.com/oauth2.0/authorize spring.security.oauth2.client.provider.naver.token-uri=https://nid.naver.com/oauth2.0/token spring.security.oauth2.client.provider.naver.user-info-uri=https://openapi.naver.com/v1/nid/me spring.security.oauth2.client.provider.naver.user-name-attribute=response # OAuth2 : Google registration spring.security.oauth2.client.registration.google.client-name=google spring.security.oauth2.client.registration.google.client-id= spring.security.oauth2.client.registration.google.client-secret= spring.security.oauth2.client.registration.google.redirect-uri=http://localhost:8080/login/oauth2/code/google spring.security.oauth2.client.registration.google.authorization-grant-type=authorization_code spring.security.oauth2.client.registration.google.scope=profile,email ​ 네이버와 구글에 대한 신청 방법은 아래 영상을 통해 확인하실 수 있습니다. ​ https://youtu.be/L8yAtjjOhDo?si=qZ1PblKYHQtB_gJx ​ https://youtu.be/VFvlivlhoMo?si=zP0LK1uRdx_3uz9m ​ OAuth2UserService ​ 소셜 로그인의 CODE 발급 -> 토큰 교환 -> 유저 데이터 획득 후 -> 그 유저 데이터를 받는곳을 구현해야 합니다. ​ 데이터를 받아 신규 유저라면 가입, 기존 유저라면 업데이트를 진행하며, 최종 로그인이 완료됩니다. ​ - domain > user > service > UserService.java : 메소드 오버라이딩 @Service public class UserService extends DefaultOAuth2UserService implements UserDetailsService { @Override public OAuth2User loadUser(OAuth2UserRequest userRequest) throws OAuth2AuthenticationException { // 부모 메소드 호출 OAuth2User oAuth2User = super.loadUser(userRequest); // 데이터 Map attributes; List authorities; String username; String role = UserRoleType.USER.name(); String email; String nickname; // provider 제공자별 데이터 획득 String registrationId = userRequest.getClientRegistration().getRegistrationId().toUpperCase(); if (registrationId.equals(SocialProviderType.NAVER.name())) { attributes = (Map) oAuth2User.getAttributes().get("response"); username = registrationId + "_" + attributes.get("id"); email = attributes.get("email").toString(); nickname = attributes.get("nickname").toString(); } else if (registrationId.equals(SocialProviderType.GOOGLE.name())) { attributes = (Map) oAuth2User.getAttributes(); username = registrationId + "_" + attributes.get("sub"); email = attributes.get("email").toString(); nickname = attributes.get("name").toString(); } else { throw new OAuth2AuthenticationException("지원하지 않는 소셜 로그인입니다."); } // 데이터베이스 조회 -> 존재하면 업데이트, 없으면 신규 가입 Optional entity = userRepository.findByUsernameAndIsSocial(username, true); if (entity.isPresent()) { // role 조회 role = entity.get().getRoleType().name(); // 기존 유저 업데이트 UserRequestDTO dto = new UserRequestDTO(); dto.setNickname(nickname); dto.setEmail(email); entity.get().updateUser(dto); userRepository.save(entity.get()); } else { // 신규 유저 추가 UserEntity newUserEntity = UserEntity.builder() .username(username) .password("") .isLock(false) .isSocial(true) .socialProviderType(SocialProviderType.valueOf(registrationId)) .roleType(UserRoleType.USER) .nickname(nickname) .email(email) .build(); userRepository.save(newUserEntity); } authorities = List.of(new SimpleGrantedAuthority(role)); return new CustomOAuth2User(attributes, authorities, username); } ​ - domain > user > repository > UserRepository.java : 메소드 추가 Optional findByUsernameAndIsSocial(String username, Boolean social); ​ - domain > user > dto > CustomOAuth2User.java import org.springframework.security.core.GrantedAuthority; import org.springframework.security.oauth2.core.user.OAuth2User; import java.util.Collection; import java.util.Map; public class CustomOAuth2User implements OAuth2User { private final Map attributes; private final Collection authorities; private final String username; public CustomOAuth2User(Map attributes, Collection authorities, String username) { this.attributes = attributes; this.authorities = authorities; this.username = username; } @Override public Map getAttributes() { return attributes; } @Override public Collection getAuthorities() { return authorities; } @Override public String getName() { return username; } } ​ 소셜 로그인 성공 핸들러 ​ 소셜 로그인 성공 이후, 프론트로 JWT를 발급하기 위한 핸들러를 추가합니다. ​ - handler > SocialSuccessHandler.java import jakarta.servlet.ServletException; import jakarta.servlet.http.Cookie; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.example.backend.domain.jwt.service.JwtService; import org.example.backend.util.JWTUtil; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.security.core.Authentication; import org.springframework.security.web.authentication.AuthenticationSuccessHandler; import org.springframework.stereotype.Component; import java.io.IOException; @Component @Qualifier("SocialSuccessHandler") public class SocialSuccessHandler implements AuthenticationSuccessHandler { private final JwtService jwtService; public SocialSuccessHandler(JwtService jwtService) { this.jwtService = jwtService; } @Override public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException { // username, role String username = authentication.getName(); String role = authentication.getAuthorities().iterator().next().getAuthority(); // JWT(Refresh) 발급 String refreshToken = JWTUtil.createJWT(username, "ROLE_" + role, false); // 발급한 Refresh DB 테이블 저장 (Refresh whitelist) jwtService.addRefresh(username, refreshToken); // 응답 Cookie refreshCookie = new Cookie("refreshToken", refreshToken); refreshCookie.setHttpOnly(true); refreshCookie.setSecure(false); refreshCookie.setPath("/"); refreshCookie.setMaxAge(10); // 10초 (프론트에서 발급 후 바로 헤더 전환 로직 진행 예정) response.addCookie(refreshCookie); response.sendRedirect("http://localhost:5173/cookie"); } } ​ - config > SecurityConfig.java : 성공핸들러 등록 private final AuthenticationConfiguration authenticationConfiguration; private final AuthenticationSuccessHandler loginSuccessHandler; private final AuthenticationSuccessHandler socialSuccessHandler; public SecurityConfig( AuthenticationConfiguration authenticationConfiguration, @Qualifier("LoginSuccessHandler") AuthenticationSuccessHandler loginSuccessHandler, @Qualifier("SocialSuccessHandler") AuthenticationSuccessHandler socialSuccessHandler ) { this.authenticationConfiguration = authenticationConfiguration; this.loginSuccessHandler = loginSuccessHandler; this.socialSuccessHandler = socialSuccessHandler; } .successHandler(socialSuccessHandler)); ​ 이전 : 10. 백엔드 : User API 작성 및 로그인 다음 : 12. 백엔드 : UserService 메소드 작성 2 https://youtu.be/krwIfQzP078 154, 스프링 + 리액트 로그인 > 12. 백엔드 : UserService 메소드 작성 2 User 도메인 완료 ​ UserService 나머지 메소드, User API, 로그아웃 관련된 메소드를 작성하여 User 도메인을 마무리하겠습니다. ​ UserService ​ - domain > user > dto > UserResponseDTO.java public record UserResponseDTO(String username, Boolean social, String nickname, String email) { } ​ - domain > user > service > UserService.java : 메소드 추가 private final PasswordEncoder passwordEncoder; private final UserRepository userRepository; private final JwtService jwtService; public UserService(PasswordEncoder passwordEncoder, UserRepository userRepository, JwtService jwtService) { this.passwordEncoder = passwordEncoder; this.userRepository = userRepository; this.jwtService = jwtService; } // 자체/소셜 로그인 회원 탈퇴 @Transactional public void deleteUser(UserRequestDTO dto) throws AccessDeniedException { // 본인 및 어드민만 삭제 가능 검증 SecurityContext context = SecurityContextHolder.getContext(); String sessionUsername = context.getAuthentication().getName(); String sessionRole = context.getAuthentication().getAuthorities().iterator().next().getAuthority(); boolean isOwner = sessionUsername.equals(dto.getUsername()); boolean isAdmin = sessionRole.equals("ROLE_"+UserRoleType.ADMIN.name()); if (!isOwner && !isAdmin) { throw new AccessDeniedException("본인 혹은 관리자만 삭제할 수 있습니다."); } // 유저 제거 userRepository.deleteByUsername(dto.getUsername()); // Refresh 토큰 제거 jwtService.removeRefreshUser(dto.getUsername()); } // 자체/소셜 유저 정보 조회 @Transactional(readOnly = true) public UserResponseDTO readUser() { String username = SecurityContextHolder.getContext().getAuthentication().getName(); UserEntity entity = userRepository.findByUsernameAndIsLock(username, false) .orElseThrow(() -> new UsernameNotFoundException("해당 유저를 찾을 수 없습니다: " + username)); return new UserResponseDTO(username, entity.getIsSocial(), entity.getNickname(), entity.getEmail()); } ​ - domain > user > repository > UserRepository.java : 메소드 추가 Optional findByUsernameAndIsLock(String username, Boolean isLock); @Transactional void deleteByUsername(String username); ​ UserController ​ - api > UserController.java : 메소드 추가 // 유저 정보 @GetMapping(value = "/user", consumes = MediaType.APPLICATION_JSON_VALUE) public UserResponseDTO userMeApi() { return userService.readUser(); } // 유저 수정 (자체 로그인 유저만) @PutMapping(value = "/user", consumes = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity updateUserApi( @Validated(UserRequestDTO.updateGroup.class) @RequestBody UserRequestDTO dto ) throws AccessDeniedException { return ResponseEntity.status(200).body(userService.updateUser(dto)); } // 유저 제거 (자체/소셜) @DeleteMapping(value = "/user", consumes = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity deleteUserApi( @Validated(UserRequestDTO.deleteGroup.class) @RequestBody UserRequestDTO dto ) throws AccessDeniedException { userService.deleteUser(dto); return ResponseEntity.status(200).body(true); } ​ 로그아웃 설정 : 핸들러 추가 ​ 로그아웃시, 발급한 Refresh 토큰을 받아 백엔드에서는 무효화 처리를 진행해야 합니다. ​ - handler > RefreshTokenLogoutHandler.java import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.example.backend.domain.jwt.service.JwtService; import org.example.backend.util.JWTUtil; import org.springframework.security.core.Authentication; import org.springframework.security.web.authentication.logout.LogoutHandler; import org.springframework.util.StringUtils; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class RefreshTokenLogoutHandler implements LogoutHandler { private final JwtService jwtService; public RefreshTokenLogoutHandler(JwtService jwtService) { this.jwtService = jwtService; } @Override public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) { try { String body = new BufferedReader(new InputStreamReader(request.getInputStream())) .lines().reduce("", String::concat); if (!StringUtils.hasText(body)) return; ObjectMapper mapper = new ObjectMapper(); JsonNode jsonNode = mapper.readTree(body); String refreshToken = jsonNode.has("refreshToken") ? jsonNode.get("refreshToken").asText() : null; // 유효성 검증 if (refreshToken == null) { return; } Boolean isValid = JWTUtil.isValid(refreshToken, false); if (!isValid) { return; } // Refresh 토큰 삭제 jwtService.removeRefresh(refreshToken); } catch (IOException e) { throw new RuntimeException("Failed to read refresh token", e); } } } ​ 작성한 로그아웃 핸들러를 로그아웃 필터에 등록해야 합니다. ​ - config > SecurityConfig.java : SecurityFilterChain 설정 // 기본 로그아웃 필터 + 커스텀 Refresh 토큰 삭제 핸들러 추가 http .logout(logout -> logout .addLogoutHandler(new RefreshTokenLogoutHandler(jwtService))); ​ 이전 : 11. 백엔드 : 소셜 로그인 설정 다음 : 13. 백엔드 : JWTFilter https://youtu.be/bY6F9JA8drs?si=dkWIFp6IHTWWDguJ 155, 스프링 + 리액트 로그인 > 13. 백엔드 : JWTFilter API 요청시 JWT 검증 ​ STATELESS 서버에서 권한이 요구되는 API에 접근하게 된다면 로그인 후 발급한 JWT를 헤더에 지참해야 합니다. 우리는 헤더에 함께 오는 JWT(Access)가 있다면 그것을 검증하여 쓰레드에 배정되는 SecurityContext에 username과 role을 부여하면 됩니다. ​ JWT 검증은 서블릿 레이어에 도달하기 이전인, Filter(시큐리티 필터)에서 수행합니다. ​ ​ JWTFilter ​ - filter > JWTFilter.java import jakarta.servlet.FilterChain; import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.example.backend.util.JWTUtil; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.web.filter.OncePerRequestFilter; import java.io.IOException; import java.util.Collections; import java.util.List; public class JWTFilter extends OncePerRequestFilter { @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { String authorization = request.getHeader("Authorization"); if (authorization == null) { filterChain.doFilter(request, response); return; } if (!authorization.startsWith("Bearer ")) { throw new ServletException("Invalid JWT token"); } // 토큰 파싱 String accessToken = authorization.split(" ")[1]; if (JWTUtil.isValid(accessToken, true)) { String username = JWTUtil.getUsername(accessToken); String role = JWTUtil.getRole(accessToken); List authorities = Collections.singletonList(new SimpleGrantedAuthority(role)); Authentication auth = new UsernamePasswordAuthenticationToken(username, null, authorities); SecurityContextHolder.getContext().setAuthentication(auth); filterChain.doFilter(request, response); } else { response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); response.setContentType("application/json;charset=UTF-8"); response.getWriter().write("{\"error\":\"토큰 만료 또는 유효하지 않은 토큰\"}"); return; } } } ​ 작성한 JWTFilter.java를 SecurityFilterChain에 등록하면 됩니다. ​ - config > SecurityConfig.java : SecurityFilterChain 필터 등록 http .addFilterBefore(new JWTFilter(), LogoutFilter.class); ​ 이전 : 12. 백엔드 : UserService 메소드 작성 2 다음 : 14. 백엔드 : JwtService 메소드 작성 2 https://youtu.be/7W3TKbBbDhA 156, 스프링 + 리액트 로그인 > 14. JwtService 메소드 작성 2 Jwt 도메인 완료 ​ Jwt 발급 및 관리 메소드는 작성되어 있지만 Refresh 토큰을 통한 Access 재발급, 소셜 로그인 쿠키 -> 헤더 교환 로직은 아직 작성하지 않았습니다. 해당 메소드와 API를 작성하겠습니다. JwtService ​ - domain > jwt > service > JwtService.java // 소셜 로그인 성공 후 쿠키(Refresh) -> 헤더 방식으로 응답 @Transactional public JWTResponseDTO cookie2Header( HttpServletRequest request, HttpServletResponse response ) { // 쿠키 리스트 Cookie[] cookies = request.getCookies(); if (cookies == null) { throw new RuntimeException("쿠키가 존재하지 않습니다."); } // Refresh 토큰 획득 String refreshToken = null; for (Cookie cookie : cookies) { if ("refreshToken".equals(cookie.getName())) { refreshToken = cookie.getValue(); break; } } if (refreshToken == null) { throw new RuntimeException("refreshToken 쿠키가 없습니다."); } // Refresh 토큰 검증 Boolean isValid = JWTUtil.isValid(refreshToken, false); if (!isValid) { throw new RuntimeException("유효하지 않은 refreshToken입니다."); } // 정보 추출 String username = JWTUtil.getUsername(refreshToken); String role = JWTUtil.getRole(refreshToken); // 토큰 생성 String newAccessToken = JWTUtil.createJWT(username, role, true); String newRefreshToken = JWTUtil.createJWT(username, role, false); // 기존 Refresh 토큰 DB 삭제 후 신규 추가 RefreshEntity newRefreshEntity = RefreshEntity.builder() .username(username) .refresh(newRefreshToken) .build(); removeRefresh(refreshToken); refreshRepository.flush(); // 같은 트랜잭션 내부라 : 삭제 -> 생성 문제 해결 refreshRepository.save(newRefreshEntity); // 기존 쿠키 제거 Cookie refreshCookie = new Cookie("refreshToken", null); refreshCookie.setHttpOnly(true); refreshCookie.setSecure(false); refreshCookie.setPath("/"); refreshCookie.setMaxAge(10); response.addCookie(refreshCookie); return new JWTResponseDTO(newAccessToken, newRefreshToken); } // Refresh 토큰으로 Access 토큰 재발급 로직 (Rotate 포함) @Transactional public JWTResponseDTO refreshRotate(RefreshRequestDTO dto) { String refreshToken = dto.getRefreshToken(); // Refresh 토큰 검증 Boolean isValid = JWTUtil.isValid(refreshToken, false); if (!isValid) { throw new RuntimeException("유효하지 않은 refreshToken입니다."); } // RefreshEntity 존재 확인 (화이트리스트) if (!existsRefresh(refreshToken)) { throw new RuntimeException("유효하지 않은 refreshToken입니다."); } // 정보 추출 String username = JWTUtil.getUsername(refreshToken); String role = JWTUtil.getRole(refreshToken); // 토큰 생성 String newAccessToken = JWTUtil.createJWT(username, role, true); String newRefreshToken = JWTUtil.createJWT(username, role, false); // 기존 Refresh 토큰 DB 삭제 후 신규 추가 RefreshEntity newRefreshEntity = RefreshEntity.builder() .username(username) .refresh(newRefreshToken) .build(); removeRefresh(refreshToken); refreshRepository.save(newRefreshEntity); return new JWTResponseDTO(newAccessToken, newRefreshToken); } ​ - domain > jwt > dto > JWTResponseDTO.java public record JWTResponseDTO(String accessToken, String refreshToken) { } ​ - domain > jwt > dto > RefreshRequestDTO.java import jakarta.validation.constraints.NotBlank; import lombok.Getter; import lombok.Setter; @Getter @Setter public class RefreshRequestDTO { @NotBlank private String refreshToken; } ​ JwtController ​ - api > JwtController.java import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.example.backend.domain.jwt.dto.JWTResponseDTO; import org.example.backend.domain.jwt.dto.RefreshRequestDTO; import org.example.backend.domain.jwt.service.JwtService; import org.springframework.http.MediaType; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; @RestController public class JwtController { private final JwtService jwtService; public JwtController(JwtService jwtService) { this.jwtService = jwtService; } // 소셜 로그인 쿠키 방식의 Refresh 토큰 헤더 방식으로 교환 @PostMapping(value = "/jwt/exchange", consumes = MediaType.APPLICATION_JSON_VALUE) public JWTResponseDTO jwtExchangeApi( HttpServletRequest request, HttpServletResponse response ) { return jwtService.cookie2Header(request, response); } // Refresh 토큰으로 Access 토큰 재발급 (Rotate 포함) @PostMapping(value = "/jwt/refresh", consumes = MediaType.APPLICATION_JSON_VALUE) public JWTResponseDTO jwtRefreshApi( @Validated @RequestBody RefreshRequestDTO dto ) { return jwtService.refreshRotate(dto); } } ​ 이전 : 13. JWTFilter 다음 : 15. CORS 및 기타 설정 https://youtu.be/6i0JXWw4iuI 157, 스프링 + 리액트 로그인 > 15. 백엔드 : CORS 및 기타 설정 백엔드 마무리 ​ 백엔드 마무리 작업으로 아래 셋팅을 진행하겠습니다. ​ - CORS 설정 - 시큐리티 필터 CORS - MvcConfig CORS - 시큐리티 인가 설정 - 시큐리티 ROLE 계층 - Refresh 토큰 자동 삭제 스케쥴 - 예외 처리 ​ CORS 설정 ​ 프론트와 백이 분리되어 있기 때문에 CORS 설정을 해야합니다. 설정은 시큐리티와 MvcConfig 모두 진행합니다. vite 기반 리액트 프로젝트는 실행시 5173 포트로 실행됩니다. ​ - config > SecurityConfig.java : SecurityFilterChain 설정 추가 @Bean public CorsConfigurationSource corsConfigurationSource() { CorsConfiguration configuration = new CorsConfiguration(); configuration.setAllowedOrigins(List.of("http://localhost:5173")); configuration.setAllowedMethods(List.of("GET", "POST", "PUT", "DELETE", "OPTIONS")); configuration.setAllowedHeaders(List.of("*")); configuration.setAllowCredentials(true); configuration.setExposedHeaders(List.of("Authorization", "Set-Cookie")); configuration.setMaxAge(3600L); UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); source.registerCorsConfiguration("/**", configuration); return source; } http .cors(cors -> cors.configurationSource(corsConfigurationSource())); ​ - config > MvcConfig.java import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration public class MvcConfig implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry corsRegistry) { corsRegistry.addMapping("/**") .allowedOrigins("http://localhost:5173") .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS") .allowCredentials(true) .allowedHeaders("*") .exposedHeaders("Set-Cookie", "Authorization"); } } ​ 시큐리티 인가 설정 ​ API 경로별 스프링 시큐리티 인가 설정을 진행하겠습니다. ​ - config > SecurityConfig.java : SecurityFilterChain 인가 설정 // 인가 http .authorizeHttpRequests(auth -> auth .requestMatchers("/jwt/exchange", "/jwt/refresh").permitAll() .requestMatchers(HttpMethod.POST, "/user/exist", "/user").permitAll() .requestMatchers(HttpMethod.GET, "/user").hasRole(UserRoleType.USER.name()) .requestMatchers(HttpMethod.PUT, "/user").hasRole(UserRoleType.USER.name()) .requestMatchers(HttpMethod.DELETE, "/user").hasRole(UserRoleType.USER.name()) .anyRequest().authenticated() ); ​ 시큐리티 ROLE 계층 ​ 시큐리티가 가지고 있는 ROLE : ADMIN, USER에 대해 계층을 부여하겠습니다. ​ - config > SecurityConfig.java : 메소드 추가 // 권한 계층 @Bean public RoleHierarchy roleHierarchy() { return RoleHierarchyImpl.withRolePrefix("ROLE_") .role(UserRoleType.ADMIN.name()).implies(UserRoleType.USER.name()) .build(); } ​ Refresh 토큰 자동 삭제 스케쥴 ​ 로그아웃시, Refresh Rotate시 백엔드에 저장한 기존 Refresh 토큰을 삭제하지만 누락되는 경우도 존재하기 때문에 주기적으로 기간이 만료된 Refresh 토큰은 제거하는 스케쥴을 등록합니다. ​ - 메인 클래스 @EnableScheduling ​ - config > ScheduleConfig.java import org.example.backend.domain.jwt.repository.RefreshRepository; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; import java.time.LocalDateTime; @Component public class ScheduleConfig { private final RefreshRepository refreshRepository; public ScheduleConfig(RefreshRepository refreshRepository) { this.refreshRepository = refreshRepository; } // Refresh 토큰 저장소 8일 지난 토큰 삭제 @Scheduled(cron = "0 0 3 * * *") public void refreshEntityTtlSchedule() { LocalDateTime cutoff = LocalDateTime.now().minusDays(8); refreshRepository.deleteByCreatedDateBefore(cutoff); } } ​ - domain > jwt > repository > RefreshRepository.java // 특정일 지난 refresh 토큰 삭제 @Transactional void deleteByCreatedDateBefore(LocalDateTime createdDate); ​ 예외 처리 ​ Service, Controller에서 던진 예외를 받기 위한 RestControllerAdvice를 등록하겠습니다. ​ - config > CustomControllerAdvice.java import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RestControllerAdvice; import java.nio.file.AccessDeniedException; @RestControllerAdvice public class CustomControllerAdvice { @ExceptionHandler(AccessDeniedException.class) public ResponseEntity handleAccessDeniedException(AccessDeniedException ex) { return ResponseEntity .status(HttpStatus.FORBIDDEN) .body("접근 권한이 없습니다."); } @ExceptionHandler(RuntimeException.class) public ResponseEntity handleRuntimeException(RuntimeException ex) { return ResponseEntity .status(HttpStatus.BAD_REQUEST) .body("잘못된 요청입니다."); } } ​ 이전 : 14. 백엔드 : JwtService 메소드 작성 2 다음 : 16. 프론트 : 프로젝트 정리 https://youtu.be/hMRkLChQ-YE 158, MIT - Distributional Reinforcement Learning - PDF ​ https://direct.mit.edu/books/oa-monograph/5590/Distributional-Reinforcement-Learning ​ 첨부파일 Distributional Reinforcement Learning .pdf 162, 스프링 + 리액트 로그인 > 16. 프론트 : 프로젝트 정리 리액트 프로젝트 기본 코드 제거 ​ React.js 기반의 프로젝트를 생성하면, 기본 코드와 이미지가 존재합니다. 기본 asset과 코드를 제거하고 깨끗한 상태로 진행하겠습니다. ​ 백엔드 API URI 변수화 ​ 프론트에서 백엔드 API에 요청을 해야합니다. 현재 개발 환경이지만 추후 배포 환경으로 바뀔 수 있기 때문에 변수화를 진행하겠습니다. ​ - .env 파일 생성 ​ - .env VITE_BACKEND_API_BASE_URL=http://localhost:8080 ​ 실행 ​ npm run dev ​ ​ 이전 : 15. 백엔드 : CORS 및 기타 설정 다음 : 17. 프론트 : 로그인 페이지 https://youtu.be/EVKYhyE0QdA 165, 스프링 + 리액트 로그인 > 17. 프론트 : 로그인 페이지 생성 회원가입 페이지 생성 : JoinPage ​ 회원 가입 페이지부터 구현하겠습니다. ​ - src > pages > JoinPage.jsx // .env로 부터 백엔드 URL 받아오기 const BACKEND_API_BASE_URL = import.meta.env.VITE_BACKEND_API_BASE_URL; function JoinPage() { return ( <> ); } export default JoinPage; ​ 페이지를 구성하는 기본 코드를 작성합니다. ​ App.jsx에 회원가입 경로 등록 ​ - src > App.jsx import { BrowserRouter, Routes, Route } from "react-router-dom"; import JoinPage from "./pages/JoinPage"; import './App.css' function App() { return ( } /> ); } export default App ​ - 패키지 추가 : react-routor-dom npm install react-router-dom ​ JoinPage.jsx 작성 완료 ​ - src > pages > JoinPage.jsx import { useState, useEffect } from "react"; import { useNavigate } from "react-router-dom"; // .env로 부터 백엔드 URL 받아오기 const BACKEND_API_BASE_URL = import.meta.env.VITE_BACKEND_API_BASE_URL; function JoinPage() { const navigate = useNavigate(); // 회원가입 변수 const [username, setUsername] = useState(""); const [isUsernameValid, setIsUsernameValid] = useState(null); // null: 검사 전, true: 사용 가능, false: 중복 const [password, setPassword] = useState(""); const [nickname, setNickname] = useState(""); const [email, setEmail] = useState(""); const [error, setError] = useState(""); // username 입력창 변경 이벤트 useEffect(() => { // username 중복 확인 const checkUsername = async () => { if (username.length < 4) { setIsUsernameValid(null); return; } try { const res = await fetch(`${BACKEND_API_BASE_URL}/user/exist`, { method: "POST", headers: { "Content-Type": "application/json" }, credentials: "include", body: JSON.stringify({ username }), }); const exists = await res.json(); setIsUsernameValid(!exists); } catch { setIsUsernameValid(null); } }; const delay = setTimeout(checkUsername, 300); return () => clearTimeout(delay); }, [username]); // 회원 가입 이벤트 const handleSignUp = async (e) => { e.preventDefault(); setError(""); if ( username.length < 4 || password.length < 4 || nickname.trim() === "" || email.trim() === "" ) { setError("입력값을 다시 확인해주세요. (모든 항목은 필수이며, ID/비밀번호는 최소 4자)"); return; } try { const res = await fetch(`${BACKEND_API_BASE_URL}/user`, { method: "POST", headers: { "Content-Type": "application/json" }, credentials: "include", body: JSON.stringify({ username, password, nickname, email }), }); if (!res.ok) throw new Error("회원가입 실패"); navigate("/login"); } catch { setError("회원가입 중 오류가 발생했습니다."); } }; // 페이지 return (

회원 가입

setUsername(e.target.value)} required minLength={4} /> {username.length >= 4 && isUsernameValid === false && (

이미 사용 중인 아이디입니다.

)} {username.length >= 4 && isUsernameValid === true && (

사용 가능한 아이디입니다.

)} setPassword(e.target.value)} required minLength={4} /> setNickname(e.target.value)} required /> setEmail(e.target.value)} required /> {error &&

{error}

}
); } export default JoinPage; ​ 로그인 페이지 생성 : LoginPage ​ - src > pages > LoginPage.jsx // .env로 부터 백엔드 URL 받아오기 const BACKEND_API_BASE_URL = import.meta.env.VITE_BACKEND_API_BASE_URL; function LoginPage() { return ( <> ); } export default LoginPage; ​ App.jsx에 로그인 경로 등록 ​ - src > App.jsx import { BrowserRouter, Routes, Route } from "react-router-dom"; import JoinPage from "./pages/JoinPage"; import LoginPage from "./pages/LoginPage"; import './App.css' function App() { return ( } /> } /> ); } export default App ​ LoginPage.jsx 작성 완료 ​ - src > pages > LoginPage.jsx import { useState } from "react"; // .env로 부터 백엔드 URL 받아오기 const BACKEND_API_BASE_URL = import.meta.env.VITE_BACKEND_API_BASE_URL; function LoginPage() { // 자체 로그인시 username/password 변수 const [username, setUsername] = useState(""); const [password, setPassword] = useState(""); const [error, setError] = useState(""); // 자체 로그인 이벤트 const handleLogin = async (e) => { e.preventDefault(); setError(""); if (username === "" || password === "") { setError("아이디와 비밀번호를 입력하세요."); return; } // API 요청 try { const res = await fetch(`${BACKEND_API_BASE_URL}/login`, { method: "POST", headers: {"Content-Type": "application/json",}, credentials: "include", body: JSON.stringify({ username, password }), }); if (!res.ok) throw new Error("로그인 실패"); const data = await res.json(); localStorage.setItem("accessToken", data.accessToken); localStorage.setItem("refreshToken", data.refreshToken); } catch (err) { setError("아이디 또는 비밀번호가 틀렸습니다."); } }; // 페이지 return (

로그인

setUsername(e.target.value)} required /> setPassword(e.target.value)} required /> {error &&

{error}

}
); } export default LoginPage; ​ 이전 : 16. 프론트 : 프로젝트 정리 다음 : 18. 프론트 : 소셜 로그인 페이지 https://youtu.be/yrLChCtVAD8 166, 스프링 + 리액트 로그인 > 18. 프론트 : 소셜 로그인 페이지 로그인 페이지 소셜 로그인 추가 ​ - src > pages > LoginPage.jsx : return 부분 // 페이지 return (

로그인

setUsername(e.target.value)} required /> setPassword(e.target.value)} required /> {error &&

{error}

}
// 소셜 로그인 버튼
); ​ 소셜 로그인 버튼 클릭시 실행 메소드 ​ - src > pages > LoginPage.jsx : LoginPage 메소드 필드 // 소셜 로그인 이벤트 const handleSocialLogin = (provider) => { window.location.href = `${BACKEND_API_BASE_URL}/oauth2/authorization/${provider}` }; ​ 소셜 로그인 성공 이후 JWT 쿠키 -> Body 교체 ​ 소셜 로그인이 성공하게 되면 구조상 백엔드에서 쿠키 형식으로 JWT를 발급합니다. ​ 우리는 일반 로그인 방식에서 응답 JSON Body로 부터 JWT(Refresh/Access)를 파싱했는데, 소셜 로그인의 쿠키는 (HTTP Only가 켜져 있으면) 다루기가 힘듭니다. 따라서 받은 쿠키를 다시 백엔드로 보내서 Body 방식으로 가져오겠습니다. ​ - 백엔드 : 소셜 로그인 성공 핸들러에서 리디렉션 response.sendRedirect("http://localhost:5173/cookie"); ​ - src > pages > CookiePage.jsx // .env로 부터 백엔드 URL 받아오기 const BACKEND_API_BASE_URL = import.meta.env.VITE_BACKEND_API_BASE_URL; function CookiePage() { return (

로그인 처리 중입니다...

); } export default CookiePage; ​ App.jsx에 쿠키 교체 경로 등록 ​ - src > App.jsx import { BrowserRouter, Routes, Route } from "react-router-dom"; import JoinPage from "./pages/JoinPage"; import LoginPage from "./pages/LoginPage"; import CookiePage from "./pages/CookiePage"; import './App.css' function App() { return ( } /> } /> } /> ) } export default App Cookie.jsx 작성 완료 ​ - src > pages > CookiePage.jsx import { useEffect } from "react"; import { useNavigate } from "react-router-dom"; // .env로 부터 백엔드 URL 받아오기 const BACKEND_API_BASE_URL = import.meta.env.VITE_BACKEND_API_BASE_URL; function CookiePage() { const navigate = useNavigate(); // 페이지 접근시 (백엔드에서 리디렉션으로 여기로 보내면, 실행) useEffect(() => { const cookieToBody = async () => { // 요청 try { const res = await fetch(`${BACKEND_API_BASE_URL}/jwt/exchange`, { method: "POST", headers: { "Content-Type": "application/json" }, credentials: "include", }); if (!res.ok) throw new Error("인증 실패"); const data = await res.json(); localStorage.setItem("accessToken", data.accessToken); localStorage.setItem("refreshToken", data.refreshToken); navigate("/"); } catch (err) { alert("소셜 로그인 실패"); navigate("/login"); } }; cookieToBody(); }, [navigate]); return (

로그인 처리 중입니다...

); } export default CookiePage; ​ 이전 : 17. 프론트 : 로그인 페이지 다음 : 19. 프론트 : 유저 정보 페이지 https://youtu.be/MB0xJ7lhqUM 167, 스프링 + 리액트 로그인 > 19. 프론트 : 유저 정보 페이지 백엔드 자원 가져오기 ​ 로그인을 완료하여 권한(Token)을 얻었습니다. 이제 백엔드 엔드포인트에 권한을 들고 접근하여 자원을 가지고 오면 됩니다. ​ 접근 방식은 fetch() 요청시 Authorization 헤더에 Access 토큰을 첨부하는 것 입니다. 다만 문제가 존재합니다. ​ 단순하게 헤더에 Access 추가시 ​ 아래와 같이 요청하는 것이 맞습니다. 다만 Access 토큰이 만료되는 경우 문제가 됩니다. const accessToken = localStorage.getItem("accessToken"); fetch("http://localhost:8080/api/data", { method: "GET", headers: { "Content-Type": "application/json", "Authorization": `Bearer ${accessToken}` } }) ​ 우리는 Access 토큰이 만료되어 실패 응답이 오는 것에 대비하여 아래 로직을 가지고 있어야 합니다. ​ 1. 자원 API에 접근하기 위해 AccessToken을 헤더에 붙여서 요청 2. 만료시 401 응답 (백엔드 JWTFilter에서 지정해둠) 3. 401 응답을 받으면 프론트 리프레싱 메소드를 호출 4. 리프레싱 메소드는 RefreshToken을 Body에 붙여 백엔드로 부터 AccessToken 재발급 5. 재발급 성공 : 1번 로직 재실행 6. 재발급 실패 : Refresh 만료로 로그인창으로 리디렉션 ​ 위 로직은 매우 긴 코드 구현이 요구됩니다. 따라서 따로 JS 파일을 작성 후 재사용하기 편하도록 설정하겠습니다. ​ fetchUtil.js 작성 ​ fetch (위의 로직) 관련 자바스크립트 메소드를 모아둘 fetchUtil 파일을 작성하겠습니다. ​ - src > util > fetchUtil.js // AccessToken 만료시 Refreshing export async function refreshAccessToken() { // 로컬 스토리지로 부터 RefreshToken 가져옴 const refreshToken = localStorage.getItem("refreshToken"); if (!refreshToken) throw new Error("RefreshToken이 없습니다."); const response = await fetch(`${import.meta.env.VITE_BACKEND_API_BASE_URL}/jwt/refresh`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ refreshToken }), }); if (!response.ok) throw new Error("AccessToken 갱신 실패"); // 성공 새 Token 저장 const data = await response.json(); localStorage.setItem("accessToken", data.accessToken); localStorage.setItem("refreshToken", data.refreshToken); return data.accessToken; } // AccessToken과 함께 fetch export async function fetchWithAccess(url, options = {}) { // 로컬 스토리지로 부터 AccessToken 가져옴 let accessToken = localStorage.getItem("accessToken"); // 옵션에 Header 없는 경우 추가 + AccessToken 부착 if (!options.headers) options.headers = {}; options.headers["Authorization"] = `Bearer ${accessToken}`; // 요청 진행 let response = await fetch(url, options); // AccessToken 만료로 401 뜨면, Refresh로 재발급 if (response.status === 401) { try { accessToken = await refreshAccessToken(); options.headers['Authorization'] = `Bearer ${accessToken}`; // 재요청 response = await fetch(url, options); } catch (err) { // Refreshing이 실패했기 때문에 로컬스토리지 삭제 후, 로그인 페이지로 localStorage.removeItem("accessToken"); localStorage.removeItem("refreshToken"); location.href = '/login'; } } if (!response.ok) { throw new Error(`HTTP 오류 : ${response.status}`); } return response; } ​ 유저 정보 페이지 생성 : UserPage ​ - src > pages > UserPage.jsx import { fetchWithAccess } from "../util/fetchUtil"; // .env로 부터 백엔드 URL 받아오기 const BACKEND_API_BASE_URL = import.meta.env.VITE_BACKEND_API_BASE_URL; function UserPage() { return ( <> ); } export default UserPage; ​ App.jsx에 유저 경로 등록 ​ - src > App.jsx import { BrowserRouter, Routes, Route } from "react-router-dom"; import JoinPage from "./pages/JoinPage"; import LoginPage from "./pages/LoginPage"; import CookiePage from "./pages/CookiePage"; import UserPage from "./pages/UserPage"; import './App.css' function App() { return ( } /> } /> } /> } /> ) } export default App ​ UserPage.jsx 작성 완료 ​ - src > pages > UserPage.jsx import { useEffect, useState } from "react"; import { fetchWithAccess } from "../util/fetchUtil"; // .env로 부터 백엔드 URL 받아오기 const BACKEND_API_BASE_URL = import.meta.env.VITE_BACKEND_API_BASE_URL; function UserPage() { // 정보 const [userInfo, setUserInfo] = useState(null); const [error, setError] = useState(''); // 페이지 방문시 유저 정보 요청 useEffect(() => { const userInfo = async () => { try { const res = await fetchWithAccess(`${BACKEND_API_BASE_URL}/user`, { method: 'GET', credentials: 'include', headers: { 'Content-Type': 'application/json', }, }); if (!res.ok) throw new Error("유저 정보 불러오기 실패"); const data = await res.json(); setUserInfo(data); } catch (err) { setError("유저 정보를 불러오지 못했습니다."); } }; userInfo(); }, []); return (

내 정보

아이디: {userInfo?.username}

닉네임: {userInfo?.nickname}

이메일: {userInfo?.email}

); } export default UserPage; ​ 이전 : 18. 프론트 : 소셜 로그인 페이지 다음 : 20. 프론트 : https://youtu.be/e0G7qWK-F4U 168, 스프링 배치5 프레임워크를 통해 대량의 데이터를 처리하는 기본적인 배치를 구현하는 시리즈입니다. ​ 스프링 배치 5 ​ 1. 실습 목표 2. 스프링 배치 동작 방식 3. 프로젝트 생성 및 의존성 추가 4. DB 연결 Config 클래스 작성 5. 메타데이터 테이블 6. 배치 처리1 : 테이블 to 테이블 7. 배치 처리1 : 실행 및 스케쥴 8. 배치 처리2 : 테이블 조건 9. 배치 처리3 : 영속성별 구현법 10. 배치 처리4 : 엑셀 to 테이블 11. 배치 처리5 : 테이블 to 엑셀 12. ItemStreamReader 13. Step 설정 14. Job 설정 15. JPA 성능 문제와 JDBC 코드 ​ https://github.com/xxxjjhhh/spring_batch_5 169, 스프링 배치 5 > 1. 실습 목표 실습 목표 ​ 스프링 배치 5 프레임워크를 활용하여 스프링 생태계에서 대량의 데이터를 안전하게 처리할 수 있는 기본적인 환경을 구축한다. ​ 배치란? : 아주 간단하게 ​ 우선 사전적 의미는 “일정 시간 동안 대량의 데이터를 한 번에 처리하는 방식”을 의미합니다. 이때 프레임워크를 사용하는 이유는? 아주 많은 데이터를 처리 하는 중간에 프로그램이 멈출 수 있는 상황을 대비해 안전 장치를 마련해야 하기 때문입니다. 10만개의 데이터를 복잡한 JOIN을 걸어 DB간 이동 시키는 도중 프로그램이 멈춰버리면 처음부터 다시 시작할 수 없기 때문에 작업 지점을 기록해야하며, 급여나 은행 이자 시스템의 경우 특정 일 (7월, 오늘, 2020년, 등등)에 했던 처리를 또 하는 중복 불상사도 막아야하는 이유가 있습니다. (다음 영상에서 다른 방면으로도 설명) ​ 구현 : 예상 ​ - 메타 테이블 DB / 운영 테이블 DB 자체를 분리 - 테이블 → 테이블 배치 - 엑셀 → 테이블 배치 - 테이블 → 엑셀 배치 - 웹 API (id) → 테이블 배치 - 스케쥴 (크론식) 기반 실행 - 웹 핸들 기반 실행 ​ 버전 및 의존성 ​ - Spring Boot 3.3.1 - Spring Batch 5.X - Spring Data JPA - MySQL - JDBC API - MySQL - Lombok - Gradle-Groovy - Java 17 ~ ​ 기타 : disclaimer ​ - 우선 제가 배치 프레임워크 경험이 거의 없습니다. 심지어 스프링 배치 프레임워크는 현재 버전인 5만 사용해봤고, 이것도 시리즈를 만든다고 공부한게 전부입니다. - 배치 처리 개념은 과거 부터 알고 있었고, 대량 데이터 처리 때문에 프레임워크를 사용하지 않고 채번(id)을 따로 기록하는 방식으로 배치를 만들었던 경험은 있습니다. (스프링 배치를 공부해보니 거의 비슷한 맥락이고, 장점은 스프링 생태계를 쉽게 활용할 수 있다 입니다.) - 스프링 배치 4 → 배치 5로 버전업이 되면서 많은 변경 사항이 있다고 들었는데 최대한 해당 내용들을 트래킹하려고 하고 있습니다. 배치 5 형식으로 구현하지만, 4의 구현에 대해 물어보신다면 모를 수 있습니다. ​ 다음 : 2. 스프링 배치 동작 방식 https://youtu.be/MNzPsOQ3NJk 170, 스프링 배치 5 > 2. 스프링 배치 동작 방식 배치에서 중요하게 볼 부분 ​ (앞선 영상에 이어) ​ ​ “배치”는 데이터를 효율적으로 빠르게 처리하는 것도 중요하지만, 더 중요하게 생각하는 부분은 아래와 같다고 생각합니다. ​ 1. 내가 하고 있는 작업을 어디 까지 했는지 계속해서 파악 2. 이미 했던일을 중복해서 하지 않게 파악 (배치는 보통 주기적으로 스케쥴러에 잡혀 실행되기 때문에) ​ 즉, 위와 같이 중복이나 놓치는 부분을 파악하기 위해 “기록” 하는 부분이 아주 중요합니다. (앞에서 말한 내용과 같이 기본적인 상황을 지킨 이후에 속도를 높이는 것이 중요합니다.) ​ 배치의 흐름 ​ 위 모식도를 통해 ​ 1. 읽어오기 2. 처리하기 3. 쓰기 를 읽어올 데이터가 없을때 까지 무한 반복합니다. ​ ​ 왜 한 번에 다 읽지 않을까? ​ ​ 한 번에 많은 양을 읽어 버리면 메모리에 올리지 못하거나, 실패 했을때 위험성이 크고 속도적인 문제도 발생하기 때문에 대량의 데이터를 끊어서 읽게 된다. 예를 들어, 2개의 방이 있고 사람이 좌측 방에 있는 책을 외워 나온 뒤 우측 방의 빈 공책에 옮겨적으라는 일이 주어지면, 외울 수 있는 능력과 잊어 버렸을때의 리스크를 고려하기 때문입니다. ​ 위와 같은 동작을 기록하기 위해 : 메타 데이터 ​ 그럼 결국 위 작업을 진행하면서 데이터를 끊어서 읽어야하고, 했던 배치 작업을 주기적으로 또 해야하는데 언급 했던 문제들을 해결하기 위해선 기록이 필요합니다. 배치에서는 내가하고 있는 작업, 했던 작업을 기록하는 테이블을 “메타 데이터”이라고 호칭합니다. ​ 배치 활용 상황 : 메타 데이터 존재 이유 ​ - 은행 이자 시스템 (언제나 등장하는 예시) : 매일 자정 전일 데이터를 기반으로 이자를 계산하여 이자 지급을 수행 오늘 자정 기준에 대한 데이터만 처리해야하고 처리 했던 계좌를 또 처리하면 안되며 (중복 지급시 큰일), 10분이라는 빠른 시간 동안 처리 후 은행 영업에 차질이 없도록 만들어야 한다. ​ - 주기별 회원 권한 조정 : 구독 서비스와 같이 주기별로 권한 변경 ​ - 급여 ​ - 주기별 보고서 ​ - 데이터 삭제 ​ 스프링 배치의 내부 구조도 ​ ​ - JobLauncer : 하나의 배치 작업(Job)을 실행 시키는 시작점 - Job : “읽기 → 처리 → 쓰기” 과정을 정의한 배치 작업 - Step : 실제 하나의 “읽기 → 처리 → 쓰기” 작업을 정의한 부분으로, 1개의 Job에서 여러 과정을 진행할 수 있기 때문에 1 : N의 구조를 가진다. - ItemReader : 읽어오는 부분 - ItemProcessor : 처리하는 부분 - ItemWriter : 쓰는 부분 - JobRepository : 얼만큼 했는지, 특정 일자 배치를 이미 했는지 “메타 데이터”에 기록하는 부분 ​ 참고 자료 ​ https://docs.spring.io/spring-batch/reference/domain.html The Domain Language of Batch :: Spring Batch Spring Batch Documentation / The Domain Language of Batch The Domain Language of Batch To any experienced batch architect, the overall concepts of batch processing used in Spring Batch should be familiar and comfortable. There are “Jobs” and “Steps” and developer-supplied processing units called Ite... docs.spring.io ​ 이전 : 1. 실습 목표 다음 : 3. 프로젝트 생성 및 의존성 추가 https://youtu.be/AdB6Vtgd2DA 171, 스프링 배치 5 > 3. 프로젝트 생성 및 의존성 추가 의존성 ​ https://start.spring.io/ {"_links":{"gradle-project":{"href":"https://start.spring.io/starter.zip?type=gradle-project{&dependencies,packaging,javaVersion,language,bootVersion,groupId,artifactId,version,name,description,packageName}","templated":true},"gradle-project-kotlin":{"href":"https://start.spring.io/starter.zip?type=... start.spring.io ​ - 프로젝트 의존성 - Lombok - Spring Web - JDBC API - Spring Data JPA - MySQL Driver - Spring Batch - build.gradle dependencies { implementation 'org.springframework.boot:spring-boot-starter-batch' implementation 'org.springframework.boot:spring-boot-starter-data-jpa' implementation 'org.springframework.boot:spring-boot-starter-jdbc' implementation 'org.springframework.boot:spring-boot-starter-web' compileOnly 'org.projectlombok:lombok' runtimeOnly 'com.mysql:mysql-connector-j' annotationProcessor 'org.projectlombok:lombok' testImplementation 'org.springframework.boot:spring-boot-starter-test' testImplementation 'org.springframework.batch:spring-batch-test' testRuntimeOnly 'org.junit.platform:junit-platform-launcher' } ​ 배치 자동 실행 방지 ​ 스프링 부트 및 스프링 배치는 1개의 배치 작업에 대해 프로젝트를 실행하면 자동으로 배치 작업이 가동되기 때문에 해당 과정을 막아야 한다. - application.properties spring.batch.job.enabled=false ​ 패키지 생성 : 앞으로 여러 클래스 작성을 위해 ​ - batch - config - controller - entity - repository - schedule ​ 2개의 데이터베이스를 연결 ​ 2개의 데이터베이스를 통해 시리즈 진행 (단일 연결은 단순 변수 셋팅으로 정말 쉽지만, 자주 사용하는 경우가 없을거 같습니다.) ​ ​ - 1 : 메타데이터용 - 배치 작업의 진행 사항 및 내용에 대한 메타데이터를 기록하는 테이블을 위한 DB ​ - 2 : 데이터소스용 - 배치 작업 데이터용 DB ​ 데이터베이스 연결 변수 작성 ​ - application.properties spring.datasource-meta.driver-class-name=com.mysql.cj.jdbc.Driver spring.datasource-meta.jdbc-url=jdbc:mysql://아이피:3306/첫번째디비명?useSSL=false&useUnicode=true&serverTimezone=Asia/Seoul&allowPublicKeyRetrieval=true spring.datasource-meta.username=아이디 spring.datasource-meta.password=비밀번호 spring.datasource-data.driver-class-name=com.mysql.cj.jdbc.Driver spring.datasource-data.jdbc-url=jdbc:mysql://아이피:3306/두번째디비명?useSSL=false&useUnicode=true&serverTimezone=Asia/Seoul&allowPublicKeyRetrieval=true spring.datasource-data.username=아이디 spring.datasource-data.password=비밀번호 ​ 스프링 부트는 하나의 데이터베이스에 대해서만 변수 방식으로 자동 연결을 진행하기 때문에 2개 등록시 등록을 진행하는 Config 클래스를 작성해야 합니다. 따라서 위 변수 값들을 기반으로 다음 영상에서 DB 연결 Config 클래스를 작성하도록 하겠습니다. ​ 이전 : 2. 스프링 배치 동작 방식 다음 : 4. DB 연결 Config 클래스 https://youtu.be/5jYhq28Vri4 172, 스프링 배치 5 > 4. DB 연결 Config 클래스 작성 2개의 DB 연결 ​ ​ spring.datasource-meta.driver-class-name=com.mysql.cj.jdbc.Driver spring.datasource-meta.jdbc-url=jdbc:mysql://아이피:3306/첫번째디비명?useSSL=false&useUnicode=true&serverTimezone=Asia/Seoul&allowPublicKeyRetrieval=true spring.datasource-meta.username=아이디 spring.datasource-meta.password=비밀번호 spring.datasource-data.driver-class-name=com.mysql.cj.jdbc.Driver spring.datasource-data.jdbc-url=jdbc:mysql://아이피:3306/두번째디비명?useSSL=false&useUnicode=true&serverTimezone=Asia/Seoul&allowPublicKeyRetrieval=true spring.datasource-data.username=아이디 spring.datasource-data.password=비밀번호 ​ 스프링 부트에서 2개 이상의 DB를 연결하려면 Config 클래스를 필수적으로 작성해야 하며, 충돌을 방지하여 우선 순위를 위해 @Primary Config를 설정해야 합니다. ​ 이때 스프링 배치의 기본적인 메타데이터는 @Primary로 잡혀 있는 DB 소스에 초기화되게 됩니다. ​ MetaDBConfig : 첫 번째 DB ​ - config > MetaDBConfig.java @Configuration public class MetaDBConfig { @Primary @Bean @ConfigurationProperties(prefix = "spring.datasource-meta") public DataSource metaDBSource() { return DataSourceBuilder.create().build(); } @Primary @Bean public PlatformTransactionManager metaTransactionManager() { return new DataSourceTransactionManager(metaDBSource()); } } ​ DataDBConfig : 두 번째 DB ​ - config > DataDBConfig.java @Configuration @EnableJpaRepositories( basePackages = "com.example.samplebatch.repository", entityManagerFactoryRef = "dataEntityManager", transactionManagerRef = "dataTransactionManager" ) public class DataDBConfig { @Bean @ConfigurationProperties(prefix = "spring.datasource-data") public DataSource dataDBSource() { return DataSourceBuilder.create().build(); } @Bean public LocalContainerEntityManagerFactoryBean dataEntityManager() { LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); em.setDataSource(dataDBSource()); em.setPackagesToScan(new String[]{"com.example.samplebatch.entity"}); em. setJpaVendorAdapter(new HibernateJpaVendorAdapter()); HashMap properties = new HashMap<>(); properties.put("hibernate.hbm2ddl.auto", "update"); properties.put("hibernate.show_sql", "true"); em.setJpaPropertyMap(properties); return em; } @Bean public PlatformTransactionManager dataTransactionManager() { JpaTransactionManager transactionManager = new JpaTransactionManager(); transactionManager.setEntityManagerFactory(dataEntityManager().getObject()); return transactionManager; } } ​ 이전 : 3. 프로젝트 생성 및 의존성 추가 다음 : 5. 메타데이터 테이블 https://youtu.be/OfMM4BbBlpY 173, 스프링 배치 5 > 5. 메타데이터 테이블 메타데이터 테이블이란? ​ 배치에서 중요한 작업에 대한 트래킹을 수행하는 테이블로, 스프링 배치에서도 메타데이터를 관리해야 합니다. ​ 보통은 DB 테이블에 저장하며, application.properties 변수 설정시 @Primary로 설정한 테이블에 테이블을 자동으로 생성할 수 있습니다. ​ 메타데이터 테이블 생성 설정 ​ - application.properties spring.batch.jdbc.initialize-schema=always spring.batch.jdbc.schema=classpath:org/springframework/batch/core/schema-mysql.sql ​ always를 설정하면 batch 설정에서 jdbc를 통해 테이블을 생성하며 생성 쿼리는 연결된 DB를 파악한 뒤 자동으로 찾지만, 혹시 찾지 못하거나 커스텀을 원하는 경우 classpath값을 부여할 수 있습니다. ​ 테이블 ERD ​ ​ https://docs.spring.io/spring-batch/reference/schema-appendix.html Meta-Data Schema :: Spring Batch Spring Batch Documentation / Appendices / Meta-Data Schema Meta-Data Schema # Overview The Spring Batch Metadata tables closely match the domain objects that represent them in Java. For example, JobInstance , JobExecution , JobParameters , and StepExecution map to BATCH_JOB_INSTANCE , BATCH_JOB_EXEC... docs.spring.io ​ 테이블 스크립트 경로 확인하기 ​ External Libararies > Gradle: org.springframework.batch:spring-batch-core:버전 > org.springframework.batch.core ​ ​ DB에서 생성된 테이블 확인 ​ ​ 이전 : 4. DB 연결 Config 클래스 작성 다음 : 6. 배치 처리1 : 테이블 to 테이블 https://youtu.be/1ABbCRZh5v4 174, 스프링 배치 5 > 6. 배치 처리1 : 테이블 to 테이블 배치 처리1 : 기초 테이블 간 데이터 이동 ​ 우리의 첫 번째 배치 작업은 간단하게 2개의 테이블을 정의하고 하나의 테이블에 있는 데이터 전부를 다른 테이블로 이동 시키는 일 입니다. ​ ​ 테이블1 : BeforeEntity ​ - Entity 정의 @Entity @Getter @Setter public class BeforeEntity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String username; } ​ - Repository 정의​ public interface BeforeRepository extends JpaRepository { } ​ 테이블2 : AfterEntity ​ - Entity 정의 @Entity @Getter @Setter public class AfterEntity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String username; } ​ - Repository 정의 public interface AfterRepository extends JpaRepository { } ​ 테이블1에 실습 데이터 넣기 ​ - sql : insert into BeforeEntity INSERT INTO BeforeEntity (username) VALUES ('Alice Johnson'), ('Bob Smith'), ('Charlie Brown'), ('Diana Prince'), ('Edward Davis'), ('Fiona White'), ('George Harris'), ('Hannah Clark'), ('Ian Walker'), ('Jessica Lee'), ('Kevin Robinson'), ('Laura King'), ('Michael Scott'), ('Nina Evans'), ('Oscar Wright'), ('Pamela Adams'), ('Quincy Green'), ('Rachel Baker'), ('Sam Harris'), ('Tina Nelson'), ('Ursula Moore'), ('Victor Young'), ('Wendy Thompson'), ('Xander Garcia'), ('Yara Martinez'), ('Zachary Lewis'), ('Amelia Jones'), ('Benjamin Wilson'), ('Clara Taylor'), ('David Anderson'), ('Emma Martinez'), ('Frank Hernandez'), ('Grace Robinson'), ('Henry Walker'), ('Ivy Young'), ('Jack Scott'), ('Katherine Lee'), ('Liam Brown'), ('Mia Harris'), ('Noah King'), ('Olivia Adams'), ('Paul Nelson'), ('Quinn Green'), ('Riley White'), ('Sophia Davis'), ('Thomas Clark'), ('Uma Evans'), ('Vera Robinson'), ('William Wright'), ('Xena Baker'), ('Yusuf Harris'), ('Zoe Martinez'), ('Aaron Scott'), ('Bella Young'), ('Carlos Robinson'), ('Daisy Thompson'), ('Ethan Moore'), ('Faith Lewis'), ('Gina Clark'), ('Hank Green'), ('Iris Martinez'), ('James Taylor'), ('Kelly Adams'), ('Lucas King'), ('Maggie White'), ('Nathan Wilson'), ('Opal Harris'), ('Peter Scott'), ('Queenie Davis'), ('Ryan Baker'), ('Sandra Green'), ('Travis Johnson'), ('Ulysses Clark'), ('Vivian Martinez'), ('Walter White'), ('Xander Robinson'), ('Yvette King'), ('Zach Smith'), ('Allison Davis'), ('Bradley Moore'), ('Chloe Harris'), ('Daniel Green'), ('Emily Taylor'), ('Freddie Brown'), ('Gabriella Wilson'), ('Henry Scott'), ('Isabella White'), ('Jake Adams'), ('Kaitlyn Robinson'), ('Leo Clark'), ('Madison King'), ('Nina Brown'), ('Owen Martinez'), ('Peyton Harris'), ('Quinton Moore'), ('Rebecca White'), ('Steve Wilson'), ('Tara Scott'), ('Ursula Green'), ('Victor Harris'), ('Wendy Adams'), ('Xander King'), ('Yvonne Davis'), ('Zachary White'); ​ 스프링 배치 모식도 ​ ​ 클래스 생성 및 Job 정의 ​ 기본적으로 하나의 배치 Job을 정의할 클래스를 생성하고 Job 메소드를 등록해야 합니다. 이때 배치 작업시 사용할 Repository 의존성들도 필드에 주입을 받도록 하겠습니다. ​ @Configuration public class FirstBatch { private final JobRepository jobRepository; private final PlatformTransactionManager platformTransactionManager; private final BeforeRepository beforeRepository; private final AfterRepository afterRepository; public FirstBatch(JobRepository jobRepository, PlatformTransactionManager platformTransactionManager, BeforeRepository beforeRepository, AfterRepository afterRepository) { this.jobRepository = jobRepository; this.platformTransactionManager = platformTransactionManager; this.beforeRepository = beforeRepository; this.afterRepository = afterRepository; } @Bean public Job firstJob() { System.out.println("first job"); return new JobBuilder("firstJob", jobRepository) .start(스텝들어갈자리) .build(); } } ​ 순서 생각 및 Step 정의 ​ Job을 정의 했지만, 실제 배치 처리는 Job 아래에 존재하는 하나의 Step에서 수행되게 됩니다. ​ 따라서 Step에서 "읽기 → 처리 → 쓰기" 과정을 구상해야 하며, Step을 등록하기 위한 @Bean을 등록하겠습니다. ​ @Bean public Step firstStep() { System.out.println("first step"); return new StepBuilder("firstStep", jobRepository) . chunk(10, platformTransactionManager) .reader(읽는메소드자리) .processor(처리메소드자리) .writer(쓰기메소드자리) .build(); } ​ 정의한 Step은 Job의 start() 메소드 내부에 firstStep()을 넣어주시면 됩니다. - 청크 : chunk 이때 읽기 → 처리 → 쓰기 작업은 청크 단위로 진행되는데, 대량의 데이터를 얼만큼 끊어서 처리할지에 대한 값으로 적당한 값을 선정해야 합니다. (너무 작으면 I/O 처리가 많아지고 오버헤드 발생, 너무 크면 적재 및 자원 사용에 대한 비용과 실패시 부담이 커짐) ​ Read → Process → Write 작성 ​ - Read : BeforeEntity 테이블에서 읽어오는 Reader @Bean public RepositoryItemReader beforeReader() { return new RepositoryItemReaderBuilder() .name("beforeReader") .pageSize(10) .methodName("findAll") .repository(beforeRepository) .sorts(Map.of("id", Sort.Direction.ASC)) .build(); } ​ 아주 다양한 Reader 인터페이스와 구현체들이 존재하지만, 우리는 JPA를 통한 쿼리를 수행하기 때문에 RepositoryItemReader를 사용합니다. 이때 청크 단위까지만 읽기 때문에 findAll을 하더라도 chunk 개수 만큼 사용하게 됩니다. ​ 따라서 자원 낭비를 방지하기 위해 Sort를 진행하고 pageSize() 단위를 설정해 findAll이 아닌 페이지 만큼 읽어올 수 있도록 설정합니다. - Process : 읽어온 데이터를 처리하는 Process (큰 작업을 수행하지 않을 경우 생략 가능, 지금과 같이 단순 이동은 사실 필요 없음) @Bean public ItemProcessor middleProcessor() { return new ItemProcessor() { @Override public AfterEntity process(BeforeEntity item) throws Exception { AfterEntity afterEntity = new AfterEntity(); afterEntity.setUsername(item.getUsername()); return afterEntity; } }; } (람다식으로 변경 가능) ​ - Write : AfterEntity에 처리한 결과를 저장하는 Writer @Bean public RepositoryItemWriter afterWriter() { return new RepositoryItemWriterBuilder() .repository(afterRepository) .methodName("save") .build(); } ​ Writer 또한 다양한 인터페이스 및 구현체가 존재하지만 JPA를 통한 쿼리를 날리는게 목표로 RepositoryItemWriter를 사용합니다. ​ 전체 코드 ​ @Configuration public class FirstBatch { private final JobRepository jobRepository; private final PlatformTransactionManager platformTransactionManager; private final BeforeRepository beforeRepository; private final AfterRepository afterRepository; public FirstBatch(JobRepository jobRepository, PlatformTransactionManager platformTransactionManager, BeforeRepository beforeRepository, AfterRepository afterRepository) { this.jobRepository = jobRepository; this.platformTransactionManager = platformTransactionManager; this.beforeRepository = beforeRepository; this.afterRepository = afterRepository; } @Bean public Job firstJob() { System.out.println("first job"); return new JobBuilder("firstJob", jobRepository) .start(firstStep()) .build(); } @Bean public Step firstStep() { System.out.println("first step"); return new StepBuilder("firstStep", jobRepository) . chunk(10, platformTransactionManager) .reader(beforeReader()) .processor(middleProcessor()) .writer(afterWriter()) .build(); } @Bean public RepositoryItemReader beforeReader() { return new RepositoryItemReaderBuilder() .name("beforeReader") .pageSize(10) .methodName("findAll") .repository(beforeRepository) .sorts(Map.of("id", Sort.Direction.ASC)) .build(); } @Bean public ItemProcessor middleProcessor() { return new ItemProcessor() { @Override public AfterEntity process(BeforeEntity item) throws Exception { AfterEntity afterEntity = new AfterEntity(); afterEntity.setUsername(item.getUsername()); return afterEntity; } }; } @Bean public RepositoryItemWriter afterWriter() { return new RepositoryItemWriterBuilder() .repository(afterRepository) .methodName("save") .build(); } } ​ 이전 : 5. 메타데이터 테이블 다음 : 7. 배치 처리1 : 실행 및 스케줄 https://youtu.be/vY_UGvWTh0Q 175, 스프링 배치 5 > 7. 배치 처리 1 : 실행 및 스케쥴 배치1 실행 ​ 저번 시간에 작성한 테이블 → 테이블 데이터 이동 배치를 실행시켜야 합니다. 우리는 application.properties에서 배치 자동 실행에 대한 변수 값을 false로 설정 했기 때문에 배치를 실행시키기 위한 jobLauncher를 구현해야 합니다. ​ jobLauncher 및 실행 변수 ​ 정의한 Job을 실행 시키기 위해서는 아래와 같은 구현을 진행해야 합니다. (예시 로직, 실제로 동작하지 않는 슈도 코드) private final JobLauncher jobLauncher; private final JobRegistry jobRegistry; JobParameters jobParameters = new JobParametersBuilder() .addString("date", value) .toJobParameters(); jobLauncher.run(jobRegistry.getJob("firstJob"), jobParameters); ​ 컨트롤러에서 실행 ​ “/first” 경로로 요청이 들어온다면, 배치 1을 실행하도록 설정하겠습니다. 이때 배치 실행에 대한 판단 값도 함께 넘겨줘야 중복 실행 및 실행 스케줄을 확인할 수 있습니다. ​ @Controller @ResponseBody public class MainController { private final JobLauncher jobLauncher; private final JobRegistry jobRegistry; public MainController(JobLauncher jobLauncher, JobRegistry jobRegistry) { this.jobLauncher = jobLauncher; this.jobRegistry = jobRegistry; } @GetMapping("/first") public String firstApi(@RequestParam("value") String value) throws Exception { JobParameters jobParameters = new JobParametersBuilder() .addString("date", value) .toJobParameters(); jobLauncher.run(jobRegistry.getJob("firstJob"), jobParameters); return "ok"; } } ​ 동기적으로 처리되기 때문에 요청 → 처리 → 응답에 대한 딜레이가 발생한다. (callable과 같은 도구로 비동기 처리를 진행해도 좋다.) 스케쥴로 실행 ​ - Main 클래스에 스케쥴 활성화 어노테이션 등록 @SpringBootApplication @EnableScheduling public class SpringBatchApplication { public static void main(String[] args) { SpringApplication.run(SpringBatchApplication.class, args); } } ​ - Schedule Config 클래스 생성​ @Configuration public class FirstSchedule { private final JobLauncher jobLauncher; private final JobRegistry jobRegistry; public FirstSchedule(JobLauncher jobLauncher, JobRegistry jobRegistry) { this.jobLauncher = jobLauncher; this.jobRegistry = jobRegistry; } @Scheduled(cron = "10 * * * * *", zone = "Asia/Seoul") public void runFirstJob() throws Exception { System.out.println("first schedule start"); SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd-hh-mm-ss"); String date = dateFormat.format(new Date()); JobParameters jobParameters = new JobParametersBuilder() .addString("date", date) .toJobParameters(); jobLauncher.run(jobRegistry.getJob("firstJob"), jobParameters); } } ​ JobLauncher에서 JobParameter ​ JobLauncher로 Job 실행시 JobParameter를 주는 이유는 실행한 작업에 대한 일자, 순번등을 부여해 동일한 일자에 대한 작업의 수행 여부를 확인하여 중복 실행 및 미실행을 예방할 수 있습니다. ​ 이전 : 6. 배치 처리1 : 테이블 to 테이블 다음 : 8. 배치 처리2 : 테이블 조건 https://youtu.be/ltKfPkD2wvE 176, 스프링 배치 5 > 8. 배치 처리2 : 테이블 조건 배치 처리 2 : 테이블 조건 확인 후 값 변경 ​ 두 번째 배치 작업은 하나의 테이블에서 조건을 통해 데이터를 읽은 후 데이터를 변경하고 다시 테이블에 저장하는 일 입니다. 이번 작업은 테이블에서 데이터를 읽어 “win” 컬럼 값이 10이 넘으면 “reward” 컬럼에 true 값을 주는 것 입니다. ​ ​ 테이블 : WinEntity ​ - Entity 정의 @Entity @Getter @Setter public class WinEntity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String username; private Long win; private Boolean reward; } ​ - Repository 정의 public interface WinRepository extends JpaRepository { Page findByWinGreaterThanEqual(Long win, Pageable pageable); } ​ 테이블에 실습 데이터 넣기 ​ - sql : insert into WinEntity INSERT INTO WinEntity (id, reward, username, win) VALUES (1, FALSE, 'xxxjjhhh', 10), (2, FALSE, 'devyummi', 1), (3, FALSE, 'jihun', 3), (4, FALSE, 'user4', 20), (5, FALSE, 'user5', 20), (6, FALSE, 'user6', 7), (7, FALSE, 'user7', 13), (8, FALSE, 'user8', 11), (9, FALSE, 'user9', 14), (10, FALSE, 'user10', 0), (11, FALSE, 'user11', 5), (12, FALSE, 'user12', 6), (13, FALSE, 'user13', 13), (14, FALSE, 'user14', 17), (15, FALSE, 'user15', 8), (16, FALSE, 'user16', 3), (17, FALSE, 'user17', 9), (18, FALSE, 'user18', 11), (19, FALSE, 'user19', 13), (20, FALSE, 'user20', 19), (21, FALSE, 'user21', 5), (22, FALSE, 'user22', 3), (23, FALSE, 'user23', 1), (24, FALSE, 'user24', 0), (25, FALSE, 'user25', 0), (26, FALSE, 'user26', 1), (27, FALSE, 'user27', 3), (28, FALSE, 'user28', 4), (29, FALSE, 'user29', 12), (30, FALSE, 'user30', 11), (31, FALSE, 'user31', 10), (32, FALSE, 'user32', 20), (33, FALSE, 'user33', 2), (34, FALSE, 'user34', 5), (35, FALSE, 'user35', 1), (36, FALSE, 'user36', 16), (37, FALSE, 'user37', 7), (38, FALSE, 'user38', 6), (39, FALSE, 'user39', 10), (40, FALSE, 'user40', 20), (41, FALSE, 'user41', 19), (42, FALSE, 'user42', 2), (43, FALSE, 'user43', 3), (44, FALSE, 'user44', 4), (45, FALSE, 'user45', 4), (46, FALSE, 'user46', 14), (47, FALSE, 'user47', 2), (48, FALSE, 'user48', 0), (49, FALSE, 'user49', 19), (50, FALSE, 'user50', 13), (51, FALSE, 'user51', 0), (52, FALSE, 'user52', 12), (53, FALSE, 'user53', 19), (54, FALSE, 'user54', 7), (55, FALSE, 'user55', 9), (56, FALSE, 'user56', 7), (57, FALSE, 'user57', 2), (58, FALSE, 'user58', 20), (59, FALSE, 'user59', 19), (60, FALSE, 'user60', 18), (61, FALSE, 'user61', 12), (62, FALSE, 'user62', 11), (63, FALSE, 'user63', 1), (64, FALSE, 'user64', 0), (65, FALSE, 'user65', 21), (66, FALSE, 'user66', 4), (67, FALSE, 'user67', 5), (68, FALSE, 'user68', 8), (69, FALSE, 'user69', 2), (70, FALSE, 'user70', 3), (71, FALSE, 'user71', 11), (72, FALSE, 'user72', 11), (73, FALSE, 'user73', 11), (74, FALSE, 'user74', 7), (75, FALSE, 'user75', 18), (76, FALSE, 'user76', 19), (77, FALSE, 'user77', 12), (78, FALSE, 'user78', 3), (79, FALSE, 'user79', 7), (80, FALSE, 'user80', 7), (81, FALSE, 'user81', 8), (82, FALSE, 'user82', 5), (83, FALSE, 'user83', 5), (84, FALSE, 'user84', 2), (85, FALSE, 'user85', 1), (86, FALSE, 'user86', 3), (87, FALSE, 'user87', 8), (88, FALSE, 'user88', 9), (89, FALSE, 'user89', 12), (90, FALSE, 'user90', 11), (91, FALSE, 'user91', 1), (92, FALSE, 'user92', 3), (93, FALSE, 'user93', 2), (94, FALSE, 'user94', 19), (95, FALSE, 'user95', 20), (96, FALSE, 'user96', 23), (97, FALSE, 'user97', 1), (98, FALSE, 'user98', 0), (99, FALSE, 'user99', 3), (100, FALSE, 'batchhh100', 8); ​ 스프링 배치 모식도 ​ ​ 클래스 생성 및 Job 정의 ​ 기본적으로 하나의 배치 Job을 정의할 클래스를 생성하고 Job 메소드를 등록해야 합니다. 이때 배치 작업시 사용할 Repository 의존성들도 필드에 주입을 받도록 하겠습니다. ​ @Configuration public class SecondBatch { private final JobRepository jobRepository; private final PlatformTransactionManager platformTransactionManager; private final WinRepository winRepository; public SecondBatch(JobRepository jobRepository, PlatformTransactionManager platformTransactionManager, WinRepository winRepository) { this.jobRepository = jobRepository; this.platformTransactionManager = platformTransactionManager; this.winRepository = winRepository; } @Bean public Job secondJob() { return new JobBuilder("secondJob", jobRepository) .start(스텝들어갈자리) .build(); } } ​ 순서 생각 및 Step 정의 ​ Job을 정의 했지만, 실제 배치 처리는 Job 아래에 존재하는 하나의 Step에서 수행되게 됩니다. ​ 따라서 Step에서 “읽기 → 처리 → 쓰기” 과정을 구성해야 하며, Step을 등록하기 위한 @Bean을 등록하겠습니다. ​ @Bean public Step secondStep() { return new StepBuilder("secondStep", jobRepository) . chunk(10, platformTransactionManager) .reader(winReader()) .processor(trueProcessor()) .writer(winWriter()) .build(); } ​ 정의한 Step은 Job의 start() 메소드 내부에 secondStep()을 넣어주시면 됩니다. - 청크 : chunk 이때 읽기 → 처리 → 쓰기 작업은 청크 단위로 진행되는데, 대량의 데이터를 얼만큼 끊어서 처리할지에 대한 값으로 적당한 값을 선정해야 합니다. (너무 작으면 I/O 처리가 많아지고 오버헤드 발생, 너무 크면 적재 및 자원 사용에 대한 비용과 실패시 부담이 커짐) ​ Read → Process → Write 작성 ​ - Read : WinEntity 테이블에서 읽어오는 Reader @Bean public RepositoryItemReader winReader() { return new RepositoryItemReaderBuilder() .name("winReader") .pageSize(10) .methodName("findByWinGreaterThanEqual") .arguments(Collections.singletonList(10L)) .repository(winRepository) .sorts(Map.of("id", Sort.Direction.ASC)) .build(); } ​ 아주 다양한 Reader 인터페이스와 구현체들이 존재하지만, 우리는 JPA를 통한 쿼리를 수행하기 때문에 RepositoryItemReader를 사용합니다. 이때 데이터는 페이징을 통해 읽기 때문에 Repository에 존재하는 JPA 메소드도 Page<> 타입을 반환하도록 작성해야 합니다. - Process : 읽어온 데이터를 처리하는 Process (큰 작업을 수행하지 않을 경우 생략 가능, 지금과 같이 단순 컬럼값 변경은 필요 없음) @Bean public ItemProcessor trueProcessor() { return item -> { item.setReward(true); return item; }; } ​ - Write : WinEntity에 처리한 결과를 저장 @Bean public RepositoryItemWriter winWriter() { return new RepositoryItemWriterBuilder() .repository(winRepository) .methodName("save") .build(); } 전체 코드 ​ @Configuration public class SecondBatch { private final JobRepository jobRepository; private final PlatformTransactionManager platformTransactionManager; private final WinRepository winRepository; public SecondBatch(JobRepository jobRepository, PlatformTransactionManager platformTransactionManager, WinRepository winRepository) { this.jobRepository = jobRepository; this.platformTransactionManager = platformTransactionManager; this.winRepository = winRepository; } @Bean public Job secondJob() { return new JobBuilder("secondJob", jobRepository) .start(secondStep()) .build(); } @Bean public Step secondStep() { return new StepBuilder("secondStep", jobRepository) . chunk(10, platformTransactionManager) .reader(winReader()) .processor(trueProcessor()) .writer(winWriter()) .build(); } @Bean public RepositoryItemReader winReader() { return new RepositoryItemReaderBuilder() .name("winReader") .pageSize(10) .methodName("findByWinGreaterThanEqual") .arguments(Collections.singletonList(10L)) .repository(winRepository) .sorts(Map.of("id", Sort.Direction.ASC)) .build(); } @Bean public ItemProcessor trueProcessor() { return item -> { item.setReward(true); return item; }; } @Bean public RepositoryItemWriter winWriter() { return new RepositoryItemWriterBuilder() .repository(winRepository) .methodName("save") .build(); } } ​ ​ 이전 : 7. 배치 처리1 : 실행 및 스케쥴 다음 : 9. 배치 처리3 : 영속성별 구현법 https://youtu.be/X1lGjIeNHF8 177, 스프링 배치 5 > 9. 배치 처리3 : 영속성별 구현법 배치 처리 3 : 저장소별 ​ 세 번째 배치 영상은 저장소 및 인터페이스별(MongoDB, Redis, Jdbc) 배치 구현 방법에 대해 스프링 배치 공식 샘플 코드를 살펴보도록 하겠습니다. JPA의 RepositoryItem 방식을 제외한 각각의 구현에 대해 직접 사용한 경험은 없기 때문에 구현에 대한 자세한 설명은 어렵습니다. 우리의 프로젝트에서 JPA가 아닌 다른 구현체를 사용할 경우 해당되는 의존성을 추가로 주입해야 원할하게 동작됩니다. ​ JDBC ​ 스프링 배치 공식 리포지토리 : JDBC 구현 바로가기 spring-batch/spring-batch-samples/src/main/java/org/springframework/batch/samples/jdbc at main · spring-projects/spring-batch Spring Batch is a framework for writing batch applications using Java and Spring - spring-projects/spring-batch github.com ​ JDBC의 reader 부분은 cursor 방식과 paging 방식으로 나뉩니다. - JdbcCursorItemReader @Bean public JdbcCursorItemReader itemReader(DataSource dataSource) { String sql = "select ID, NAME, CREDIT from CUSTOMER"; return new JdbcCursorItemReaderBuilder().name("customerReader") .dataSource(dataSource) .sql(sql) .rowMapper(new CustomerCreditRowMapper()) .build(); } ​ 데이터베이스 자체의 cursor를 사용하여 전체 테이블에서 cursor가 한 칸씩 이동하며 데이터를 가져옵니다. - JdbcPagingItemReader @Bean @StepScope public JdbcPagingItemReader itemReader(DataSource dataSource, @Value("#{jobParameters['credit']}") Double credit) { Map parameterValues = new HashMap<>(); parameterValues.put("statusCode", "PE"); parameterValues.put("credit", credit); parameterValues.put("type", "COLLECTION"); return new JdbcPagingItemReaderBuilder().name("customerReader") .dataSource(dataSource) .selectClause("select NAME, ID, CREDIT") .fromClause("FROM CUSTOMER") .whereClause("WHERE CREDIT > :credit") .sortKeys(Map.of("ID", Order.ASCENDING)) .rowMapper(new CustomerCreditRowMapper()) .pageSize(2) .parameterValues(parameterValues) .build(); } ​ 데이터 테이블에서 묶음 단위로 데이터를 가져오는 방식으로 SQL 구문 생성시 offset과 limit를 배치단에서 자동으로 조합하여 쿼리를 날리게 됩니다. - Processor : 데이터베이스 및 인터페이스에 상관이 없기 때문에 생략 - JdbcBatchItemWriter @Bean public JdbcBatchItemWriter itemWriter(DataSource dataSource) { String sql = "UPDATE CUSTOMER set credit = :credit where id = :id"; return new JdbcBatchItemWriterBuilder().dataSource(dataSource) .sql(sql) .itemSqlParameterSourceProvider(new BeanPropertyItemSqlParameterSourceProvider<>()) .assertUpdates(true) .build(); } ​ MongoTemplate ​ 스프링 배치 공식 리포지토리 : MongoDB 구현 바로가기 MongoTemplate을 통한 방법입니다. - MongoItemReader @Bean public MongoItemReader mongoItemReader(MongoTemplate mongoTemplate) { Map sortOptions = new HashMap<>(); sortOptions.put("name", Sort.Direction.DESC); return new MongoItemReaderBuilder().name("personItemReader") .collection("person_in") .targetType(Person.class) .template(mongoTemplate) .jsonQuery("{}") .sorts(sortOptions) .build(); } ​ - MongoItemWriter​ @Bean public MongoItemWriter mongoItemWriter(MongoTemplate mongoTemplate) { return new MongoItemWriterBuilder().template(mongoTemplate).collection("person_out").build(); } ​ 샘플들 ​ https://github.com/spring-projects/spring-batch/tree/main/spring-batch-samples/src/main/java/org/springframework/batch/samples spring-batch/spring-batch-samples/src/main/java/org/springframework/batch/samples at main · spring-projects/spring-batch Spring Batch is a framework for writing batch applications using Java and Spring - spring-projects/spring-batch github.com ​ 빠르게 구현체에 대한 쿼리를 만드는 방법 ​ 위 여러 구현들을 기반으로 Reader나 Writer를 작성한다고 가정하면, 해당하는 예시 메소드를 복사하여 Chat GPT에 붙여 넣은 후 테이블에 대한 특정 쿼리를 날리고 싶다고 하면 알맞은 구현을 만들어 주게 됩니다. ​ (어느정도 베이스가 되는 구현 샘플, 테이블을 제공하면 정말 정확한 구현을 제공해줍니다.) ​ 이전 : 8. 배치 처리2 : 테이블 조건 다음 : 10. 배치 처리4 : 엑셀 to 테이블 https://youtu.be/5oCpHqYzfU0 178, 스프링 배치 5 > 10. 배치 처리4 : 엑셀 to 테이블 배치 처리4 : 엑셀 to 테이블 ​ 네 번째 배치 작업은 엑셀 파일의 한 시트에서 데이터를 가져와 데이터베이스 테이블로 이동시키는 일 입니다. ​ ​ 엑셀 접근 의존성 추가 ​ - build.gradle implementation 'org.apache.poi:poi-ooxml:5.3.0' ​ 엑셀 시트 정의 ​ - 엑셀 파일 ​ ​ 테이블 : AfterEntity ​ - Entity 정의 @Entity @Getter @Setter public class AfterEntity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String username; } ​ - Repository 정의 public interface AfterRepository extends JpaRepository { } ​ 스프링 배치 모식도 ​ ​ 클래스 생성 및 Job 정의 ​ 하나의 배치 Job을 정의할 클래스를 생성하고 Job 메소드를 등록해야 합니다. 이때 배치 작업시 사용할 Repository 의존성들도 필드에 주입을 받도록 하겠습니다. ​ @Configuration public class FourthBatch { private final JobRepository jobRepository; private final PlatformTransactionManager platformTransactionManager; private final AfterRepository afterRepository; public FourthBatch(JobRepository jobRepository, PlatformTransactionManager platformTransactionManager, AfterRepository afterRepository) { this.jobRepository = jobRepository; this.platformTransactionManager = platformTransactionManager; this.afterRepository = afterRepository; } @Bean public Job fourthJob() { System.out.println("fourth job"); return new JobBuilder("fourthJob", jobRepository) .start(fourthStep()) .build(); } } ​ 순서 생각 및 Step 정의 ​ Job을 정의 했지만, 실제 배치 처리는 Job 아래에 존재하는 하나의 Step에서 수행되게 됩니다. ​ 따라서 Step에서 “읽기 → 처리 → 쓰기” 과정을 구상해야 하며, Step을 등록하기 위한 @Bean을 등록하겠습니다. ​ @Bean public Step fourthStep() { return new StepBuilder("fourthStep", jobRepository) . chunk(10, platformTransactionManager) .reader(excelReader()) .processor(fourthProcessor()) .writer(fourthAfterWriter()) .build(); } ​ 정의한 Step은 Job의 start() 메소드 내부에 fourthStep()을 넣어주시면 됩니다. - 청크 : chunk 이때 읽기 → 처리 → 쓰기 작업은 청크 단위로 진행되는데, 대량의 데이터를 얼만큼 끊어서 처리할지에 대한 값으로 적당한 값을 선정해야 합니다. (너무 작으면 I/O 처리가 많아지고 오버헤드 발생, 너무 크면 적재 및 자원 사용에 대한 비용과 실패시 부담이 커짐) ​ Read → Process → Write 작성 ​ - Read : 엑셀 시트에서 읽어오는 Reader @Bean public ItemStreamReader excelReader() { try { return new ExcelRowReader("C:\\Users\\kim\\Desktop\\yummi.xlsx"); //리눅스나 맥은 /User/형태로 } catch (IOException e) { throw new RuntimeException(e); } } ​ 우선은 excelReader() 메소드를 만들고 실제 구현부는 따로 클래스를 빼도록 하겠습니다. ​ public class ExcelRowReader implements ItemStreamReader { private final String filePath; private FileInputStream fileInputStream; private Workbook workbook; private Iterator rowCursor; private int currentRowNumber; private final String CURRENT_ROW_KEY = "current.row.number"; public ExcelRowReader(String filePath) throws IOException { this.filePath = filePath; this.currentRowNumber = 0; } @Override public void open(ExecutionContext executionContext) throws ItemStreamException { try { fileInputStream = new FileInputStream(filePath); workbook = WorkbookFactory.create(fileInputStream); Sheet sheet = workbook.getSheetAt(0); this.rowCursor = sheet.iterator(); // 동일 배치 파라미터에 대해 특정 키 값 "current.row.number"의 값이 존재한다면 초기화 if (executionContext.containsKey(CURRENT_ROW_KEY)) { currentRowNumber = executionContext.getInt(CURRENT_ROW_KEY); } // 위의 값을 가져와 이미 실행한 부분은 건너 뜀 for (int i = 0; i < currentRowNumber && rowCursor.hasNext(); i++) { rowCursor.next(); } } catch (IOException e) { throw new ItemStreamException(e); } } @Override public Row read() { if (rowCursor != null && rowCursor.hasNext()) { currentRowNumber++; return rowCursor.next(); } else { return null; } } @Override public void update(ExecutionContext executionContext) throws ItemStreamException { executionContext.putInt(CURRENT_ROW_KEY, currentRowNumber); } @Override public void close() throws ItemStreamException { try { if (workbook != null) { workbook.close(); } if (fileInputStream != null) { fileInputStream.close(); } } catch (IOException e) { throw new ItemStreamException(e); } } } ​ - Process : 읽어온 데이터를 처리하는 Process​ @Bean public ItemProcessor fourthProcessor() { return new ItemProcessor() { @Override public AfterEntity process(Row item) { AfterEntity afterEntity = new AfterEntity(); afterEntity.setUsername(item.getCell(0).getStringCellValue()); return afterEntity; } }; } - Write : AfterEntity에 처리한 결과를 저장하는 Writer @Bean public RepositoryItemWriter fourthAfterWriter() { return new RepositoryItemWriterBuilder() .repository(afterRepository) .methodName("save") .build(); } ​ 전체 코드 ​ @Configuration public class FourthBatch { private final JobRepository jobRepository; private final PlatformTransactionManager platformTransactionManager; private final AfterRepository afterRepository; public FourthBatch(JobRepository jobRepository, PlatformTransactionManager platformTransactionManager, AfterRepository afterRepository) { this.jobRepository = jobRepository; this.platformTransactionManager = platformTransactionManager; this.afterRepository = afterRepository; } @Bean public Job fourthJob() { System.out.println("fourth job"); return new JobBuilder("fourthJob", jobRepository) .start(fourthStep()) .build(); } @Bean public Step fourthStep() { return new StepBuilder("fourthStep", jobRepository) . chunk(10, platformTransactionManager) .reader(excelReader()) .processor(fourthProcessor()) .writer(fourthAfterWriter()) .build(); } @Bean public ItemStreamReader excelReader() { try { return new ExcelRowReader("C:\\Users\\kim\\Desktop\\yummi.xlsx"); //리눅스나 맥은 /User/형태로 } catch (IOException e) { throw new RuntimeException(e); } } @Bean public ItemProcessor fourthProcessor() { return new ItemProcessor() { @Override public AfterEntity process(Row item) { AfterEntity afterEntity = new AfterEntity(); afterEntity.setUsername(item.getCell(0).getStringCellValue()); return afterEntity; } }; } @Bean public RepositoryItemWriter fourthAfterWriter() { return new RepositoryItemWriterBuilder() .repository(afterRepository) .methodName("save") .build(); } } ​ public class ExcelRowReader implements ItemStreamReader { private final String filePath; private FileInputStream fileInputStream; private Workbook workbook; private Iterator rowCursor; private int currentRowNumber; private final String CURRENT_ROW_KEY = "current.row.number"; public ExcelRowReader(String filePath) throws IOException { this.filePath = filePath; this.currentRowNumber = 0; } @Override public void open(ExecutionContext executionContext) throws ItemStreamException { try { fileInputStream = new FileInputStream(filePath); workbook = WorkbookFactory.create(fileInputStream); Sheet sheet = workbook.getSheetAt(0); this.rowCursor = sheet.iterator(); // 동일 배치 파라미터에 대해 특정 키 값 "current.row.number"의 값이 존재한다면 초기화 if (executionContext.containsKey(CURRENT_ROW_KEY)) { currentRowNumber = executionContext.getInt(CURRENT_ROW_KEY); } // 위의 값을 가져와 이미 실행한 부분은 건너 뜀 for (int i = 0; i < currentRowNumber && rowCursor.hasNext(); i++) { rowCursor.next(); } } catch (IOException e) { throw new ItemStreamException(e); } } @Override public Row read() { if (rowCursor != null && rowCursor.hasNext()) { currentRowNumber++; return rowCursor.next(); } else { return null; } } @Override public void update(ExecutionContext executionContext) throws ItemStreamException { executionContext.putInt(CURRENT_ROW_KEY, currentRowNumber); } @Override public void close() throws ItemStreamException { try { if (workbook != null) { workbook.close(); } if (fileInputStream != null) { fileInputStream.close(); } } catch (IOException e) { throw new ItemStreamException(e); } } } ​ 중요 포인트 1 ​ ItemStreamReader에서 엑셀 파일은 언제 열릴까에 대한 고민을 하시는게 좋을거 같습니다. Chunk 단위로 수행시 매번 열릴지? 아니면 열린 상태로 존재하고 Chunk 단위로 부분씩 읽어올지가 성능 문제에서도 중요합니다. 정답은 처음 new로 생성시 파일 자체는 open() 메소드에 대해 한 번 열리고 read가 불릴때 마다 행 부분을 나눠 읽어오게 됩니다. 파일이 열리고 닫히는 것은 컴퓨터 자원에 많은 부하를 주기 때문에 구현시 고민을 해야 합니다. ​ 중요 포인트 2 ​ 엑셀 파일에서 데이터를 읽다가 프로그램이 멈춘다면, 다시 실행 했을때 중단점 부터 해당 작업을 수행할 수 있도록 ExecutionContext에서 관리할 수 있도록 하는 부분도 중요합니다. ​ 이전 : 9. 배치 처리3 : 영속성별 구현법 다음 : 11. 배치 처리5 : 테이블 to 엑셀 https://youtu.be/3b3Db8ct31s 179, 스프링 배치 5 > 11. 배치 처리5 : 테이블 to 엑셀 배치 처리 5 : 테이블 to 엑셀 ​ 다섯 번째 배치 작업은 데이터베이스 테이블에서 엑셀 파일 한 시트로 이동시키는 일 입니다. ​ ​ 이전 영상과 차이점 ​ "엑셀 → 테이블"과 “테이블 → 엑셀”의 차이를 생각하면 좋습니다. ​ 앞선 영상인 "엑셀 → 테이블"은 중간에 종료되더라도 중단점부터 실행하면 효율적입니다. ​ 하지만, 이번 작업은 “테이블 → 엑셀”이 실패하면 파일을 새로 만들어야되기 때문에 중단점이 아니라 처음부터 배치를 처리하도록 설정해야 합니다. ​ (상황에 따라 다르겠지만, 파일을 만든다고 가정하면 새로 시작, 파일이 정의되어 있고 이어쓴다면 이어지는 부분 부터 진행하면 좋습니다.) ​ 엑셀 접근 의존성 추가 ​ - build.gradle implementation 'org.apache.poi:poi-ooxml:5.3.0' ​ 테이블 : BeforeEntity ​ - Entity 정의 @Entity @Getter @Setter public class BeforeEntity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String username; } ​ - Repository 정의​ public interface BeforeRepository extends JpaRepository { } ​ 테이블에 실습 데이터 넣기 ​ - sql : insert into BeforeEntity INSERT INTO BeforeEntity (username) VALUES ('Alice Johnson'), ('Bob Smith'), ('Charlie Brown'), ('Diana Prince'), ('Edward Davis'), ('Fiona White'), ('George Harris'), ('Hannah Clark'), ('Ian Walker'), ('Jessica Lee'), ('Kevin Robinson'), ('Laura King'), ('Michael Scott'), ('Nina Evans'), ('Oscar Wright'), ('Pamela Adams'), ('Quincy Green'), ('Rachel Baker'), ('Sam Harris'), ('Tina Nelson'), ('Ursula Moore'), ('Victor Young'), ('Wendy Thompson'), ('Xander Garcia'), ('Yara Martinez'), ('Zachary Lewis'), ('Amelia Jones'), ('Benjamin Wilson'), ('Clara Taylor'), ('David Anderson'), ('Emma Martinez'), ('Frank Hernandez'), ('Grace Robinson'), ('Henry Walker'), ('Ivy Young'), ('Jack Scott'), ('Katherine Lee'), ('Liam Brown'), ('Mia Harris'), ('Noah King'), ('Olivia Adams'), ('Paul Nelson'), ('Quinn Green'), ('Riley White'), ('Sophia Davis'), ('Thomas Clark'), ('Uma Evans'), ('Vera Robinson'), ('William Wright'), ('Xena Baker'), ('Yusuf Harris'), ('Zoe Martinez'), ('Aaron Scott'), ('Bella Young'), ('Carlos Robinson'), ('Daisy Thompson'), ('Ethan Moore'), ('Faith Lewis'), ('Gina Clark'), ('Hank Green'), ('Iris Martinez'), ('James Taylor'), ('Kelly Adams'), ('Lucas King'), ('Maggie White'), ('Nathan Wilson'), ('Opal Harris'), ('Peter Scott'), ('Queenie Davis'), ('Ryan Baker'), ('Sandra Green'), ('Travis Johnson'), ('Ulysses Clark'), ('Vivian Martinez'), ('Walter White'), ('Xander Robinson'), ('Yvette King'), ('Zach Smith'), ('Allison Davis'), ('Bradley Moore'), ('Chloe Harris'), ('Daniel Green'), ('Emily Taylor'), ('Freddie Brown'), ('Gabriella Wilson'), ('Henry Scott'), ('Isabella White'), ('Jake Adams'), ('Kaitlyn Robinson'), ('Leo Clark'), ('Madison King'), ('Nina Brown'), ('Owen Martinez'), ('Peyton Harris'), ('Quinton Moore'), ('Rebecca White'), ('Steve Wilson'), ('Tara Scott'), ('Ursula Green'), ('Victor Harris'), ('Wendy Adams'), ('Xander King'), ('Yvonne Davis'), ('Zachary White'); ​ 스프링 배치 모식도 ​ ​ 클래스 생성 및 Job 정의 ​ 하나의 배치 Job을 정의할 클래스를 생성하고 Job 메소드를 등록해야 합니다. 이때 배치 작업시 사용할 Repository 의존성들도 필드에 주입을 받도록 하겠습니다. ​ @Configuration public class FifthBatch { private final JobRepository jobRepository; private final PlatformTransactionManager platformTransactionManager; private final BeforeRepository beforeRepository; public FifthBatch(JobRepository jobRepository, PlatformTransactionManager platformTransactionManager, BeforeRepository beforeRepository) { this.jobRepository = jobRepository; this.platformTransactionManager = platformTransactionManager; this.beforeRepository = beforeRepository; } @Bean public Job fifthJob() { System.out.println("fifth job"); return new JobBuilder("fifthJob", jobRepository) .start(fifthStep()) .build(); } } ​ 순서 생각 및 Step 정의 ​ Job을 정의 했지만, 실제 배치 처리는 Job 아래에 존재하는 하나의 Step에서 수행되게 됩니다. ​ 따라서 Step에서 “읽기 → 처리 → 쓰기” 과정을 구상해야 하며, Step을 등록하기 위한 @Bean을 등록하겠습니다. ​ @Bean public Step fifthStep() { System.out.println("fifth step"); return new StepBuilder("fifthStep", jobRepository) . chunk(10, platformTransactionManager) .reader(fifthBeforeReader()) .processor(fifthProcessor()) .writer(excelWriter()) .build(); } ​ 정의한 Step은 Job의 start() 메소드 내부에 fourthStep()을 넣어주시면 됩니다. - 청크 : chunk 이때 읽기 → 처리 → 쓰기 작업은 청크 단위로 진행되는데, 대량의 데이터를 얼만큼 끊어서 처리할지에 대한 값으로 적당한 값을 선정해야 합니다. (너무 작으면 I/O 처리가 많아지고 오버헤드 발생, 너무 크면 적재 및 자원 사용에 대한 비용과 실패시 부담이 커짐) ​ Read → Process → Write 작성 ​ - Read : BeforeEntity 테이블에서 읽어오는 Reader @Bean public RepositoryItemReader fifthBeforeReader() { RepositoryItemReader reader = new RepositoryItemReaderBuilder() .name("beforeReader") .pageSize(10) .methodName("findAll") .repository(beforeRepository) .sorts(Map.of("id", Sort.Direction.ASC)) .build(); // 전체 데이터 셋에서 어디까지 수행 했는지의 값을 저장하지 않음 reader.setSaveState(false); return reader; } ​ - Process : 읽어온 데이터를 처리하는 Processor @Bean public ItemProcessor fifthProcessor() { return item -> item; } ​ - Write : 엑셀 시트에 처리한 결과를 저장하는 Writer @Bean public ItemStreamWriter excelWriter() { try { return new ExcelRowWriter("C:\\Users\\kim\\Desktop\\result.xlsx"); //리눅스나 맥은 /User/형태로 } catch (IOException e) { throw new RuntimeException(e); } } ​ 우선은 ExcelWriter() 메소드를 만들고 실제 구현부는 따로 클래스를 빼도록 하겠습니다. ​ public class ExcelRowWriter implements ItemStreamWriter { private final String filePath; private Workbook workbook; private Sheet sheet; private int currentRowNumber; private boolean isClosed; public ExcelRowWriter(String filePath) throws IOException { this.filePath = filePath; this.isClosed = false; this.currentRowNumber = 0; } @Override public void open(ExecutionContext executionContext) throws ItemStreamException { workbook = new XSSFWorkbook(); sheet = workbook.createSheet("Sheet1"); } @Override public void write(Chunk chunk) { for (BeforeEntity entity : chunk) { Row row = sheet.createRow(currentRowNumber++); row.createCell(0).setCellValue(entity.getUsername()); } } @Override public void close() throws ItemStreamException { if (isClosed) { return; } try (FileOutputStream fileOut = new FileOutputStream(filePath)) { workbook.write(fileOut); } catch (IOException e) { throw new ItemStreamException(e); } finally { try { workbook.close(); } catch (IOException e) { throw new ItemStreamException(e); } finally { isClosed = true; } } } } ​ 엑셀 파일 깨짐 오류 ​ ​ 이슈 제보해 주신 성준님께 감사의 인사를 드립니다. 해당 문제가 간헐적으로 발생했고, 배치 어플리케이션을 종료하는 과정에서 이미 close()를 통해 정상적으로 닫힌 파일을 다시 핸들링하여 파일이 깨지는 이슈가 발생했습니다. 위 문제를 해결하기 위해 파일의 상태를 체크하는 필드 변수를 만들었고 변경점에 대해 코드 변경을 완료하였습니다. ​ 전체 코드 ​ @Configuration public class FifthBatch { private final JobRepository jobRepository; private final PlatformTransactionManager platformTransactionManager; private final BeforeRepository beforeRepository; public FifthBatch(JobRepository jobRepository, PlatformTransactionManager platformTransactionManager, BeforeRepository beforeRepository) { this.jobRepository = jobRepository; this.platformTransactionManager = platformTransactionManager; this.beforeRepository = beforeRepository; } @Bean public Job fifthJob() { System.out.println("fifth job"); return new JobBuilder("fifthJob", jobRepository) .start(fifthStep()) .build(); } @Bean public Step fifthStep() { System.out.println("fifth step"); return new StepBuilder("fifthStep", jobRepository) . chunk(10, platformTransactionManager) .reader(fifthBeforeReader()) .processor(fifthProcessor()) .writer(excelWriter()) .build(); } @Bean public RepositoryItemReader fifthBeforeReader() { return new RepositoryItemReaderBuilder() .name("beforeReader") .pageSize(10) .methodName("findAll") .repository(beforeRepository) .sorts(Map.of("id", Sort.Direction.ASC)) .build(); } @Bean public ItemProcessor fifthProcessor() { return item -> item; } @Bean public ItemStreamWriter excelWriter() { try { return new ExcelRowWriter("C:\\Users\\kim\\Desktop\\result.xlsx"); //리눅스나 맥은 /User/형태로 } catch (IOException e) { throw new RuntimeException(e); } } } ​ public class ExcelRowWriter implements ItemStreamWriter { private final String filePath; private Workbook workbook; private Sheet sheet; private int currentRowNumber; private boolean isClosed; public ExcelRowWriter(String filePath) throws IOException { this.filePath = filePath; this.isClosed = false; this.currentRowNumber = 0; } @Override public void open(ExecutionContext executionContext) throws ItemStreamException { workbook = new XSSFWorkbook(); sheet = workbook.createSheet("Sheet1"); } @Override public void write(Chunk chunk) { for (BeforeEntity entity : chunk) { Row row = sheet.createRow(currentRowNumber++); row.createCell(0).setCellValue(entity.getUsername()); } } @Override public void close() throws ItemStreamException { if (isClosed) { return; } try (FileOutputStream fileOut = new FileOutputStream(filePath)) { workbook.write(fileOut); } catch (IOException e) { throw new ItemStreamException(e); } finally { try { workbook.close(); } catch (IOException e) { throw new ItemStreamException(e); } finally { isClosed = true; } } } } ​ 이전 : 10. 배치 처리4 : 엑셀 to 테이블 다음 : 12. ItemStreamReader https://youtu.be/G_yVcism96A 180, 스프링 배치 5 > 12. ItemStreamReader 배치에서 데이터를 읽는 Reader ​ 스프링 배치에서 가장 중요한 부분은 Reader 부분입니다. 현재까지 실행한 부분을 메타데이터에 저장해야하고 처리한 부분은 스킵해야 되기 때문입니다. 스프링 배치에서 다양한 Reader 구현체를 제공합니다. ​ 하지만 내가 원하는 구현체가 없는 경우 직접 작성해야 하는데, 기본적인 Reader 인터페이스에 대한 Reader를 구현 방법에 대해서 간략하게 알아보겠습니다. ​ ItemStreamReader ​ 앞선 엑셀 읽기 부분에서 사용했던 ItemStreamReader입니다. ​ 이 인터페이스는 배치의 초기화 및 상태를 관리할 수 있는 ItemStream과 실제 데이터 처리를 진행하는 ItemReader를 상속 받고 있습니다. ItemStreamReader = ItemStream + ItemReader ​ public interface ItemStreamReader extends ItemStream, ItemReader { } ​ ItemReader<> ​ @FunctionalInterface public interface ItemReader { @Nullable T read() throws Exception, UnexpectedInputException, ParseException, NonTransientResourceException; } ​ - read() 배치 작업시 데이터를 읽기 위한 부분으로 하나의 데이터를 읽어올 때 read() 메소드가 호출됩니다. ​ ItemStream ​ public interface ItemStream { default void open(ExecutionContext executionContext) throws ItemStreamException { } default void update(ExecutionContext executionContext) throws ItemStreamException { } default void close() throws ItemStreamException { } } ​ - open(ExecutionContext executionContext) 배치 처리가 시작되고 Step에서 처음 reader를 부르면 시작되는 부분으로 초기화나 이미 했던 작업의 경우 중단점 까지 건너 뛰도록 설계하는 부분입니다. - update(ExecutionContext executionContext) 배치 작업시 read()와 함께 불려지는 메소드로 read() 호출 후 바로 호출되기 때문에 read()에서 처리한 작업 단위를 기록하는 용도로 사용됩니다. 청크 기반이면 read()가 청크 단위로 먼저 수행된 후, update() 호출 됨 - close() 배치 작업이 완료되고 불려지는 메소드로 파일을 저장하거나 필드 변수를 초기화하는 메소드로 사용됩니다. ​ ExecutionContext ​ ItemStream의 open(), update()에 매개변수로 주입되는 있는 객체로 배치 작업 처리시 기준점을 잡을 변수를 계속하여 트래킹하기 위한 저장소로 사용됩니다. 해당 클래스에서 put으로 값을 넣고, get으로 넣은 값을 가져옵니다. ExecutionContext 데이터는 JdbcExecutionContextDao에 의해 메타데이터 테이블에 저장되며 범위에 따라 아래와 같이 나뉩니다. ​ - BATCH_JOB_EXECUTION_CONTEXT - BATCH_STEP_EXECUTION_CONTEXT ​ 구현 예시 ​ 실제로 동작하는 코드는 아니지만 예시로 작성 했습니다. ​ public class CustomItemStreamReaderImpl implements ItemStreamReader { private final RestTemplate restTemplate; private int currentId; private final String CURRENT_ID_KEY = "current.call.id"; private final String API_URL = "https://www.devyummi.com/page?id="; public CustomItemStreamReaderImpl(RestTemplate restTemplate) { this.currentId = 0; this.restTemplate = restTemplate; } @Override public void open(ExecutionContext executionContext) throws ItemStreamException { if (executionContext.containsKey(CURRENT_ID_KEY)) { currentId = executionContext.getInt(CURRENT_ID_KEY); } } @Override public String read() throws Exception, UnexpectedInputException, ParseException, NonTransientResourceException { currentId++; String url = API_URL + currentId; String response = restTemplate.getForObject(url, String.class); if (response == null) { return null; } return response; } @Override public void update(ExecutionContext executionContext) throws ItemStreamException { executionContext.putInt(CURRENT_ID_KEY, currentId); } @Override public void close() throws ItemStreamException { } } ​ 이전 : 11. 배치 처리5 : 테이블 to 엑셀 다음 : 13. Step 설정 https://youtu.be/4D65kFIPUyo 181, 스프링 배치 5 > 13. Step 설정 목표 ​ 우리는 이미 배치에서 Step을 만들었지만, 마지막으로 간단하게 Step에 대해서 알아보고 추가할 수 있는 안전 장치인 설정들에 대해 알아보겠습니다. ​ Step ​ Step은 배치 작업을 처리하는 하나의 묶음 입니다. 이런 Step은 두 가지 방식 중 하나로 구현됩니다. - Step - Chunk 방식 처리 (Read → Process → Write) - Tasklet 방식 처리 우리는 Chunk 단위 처리에 대해서만 알아보았습니다. Tasklet 방식은 아주 간단한 동작만 하기 때문에 데이터 조건을 걸어 이동하는데는 거의 사용하지 않습니다. (단순 파일 삭제, 값 초기화) 따라서 Chunk 단위에 대해서 집중하면 될 거 같습니다. 아래서 Chunk 처리 과정에 대해서 간략하게 알아보겠습니다. ​ Step : Chunk 단위 처리 과정 ​ 청크 값을 10으로 설정 했다면 (Read) X 10 → (Process) X 10 → Write ​ Skip ​ Skip은 Step의 과정 중 예외가 발생하게 되면 예외를 특정 수 까지 건너 뛸 수 있도록 설정하는 방법입니다. - 예시 @Bean public Step sixthStep() { return new StepBuilder("sixthStep", jobRepository) . chunk(10, platformTransactionManager) .reader(beforeSixthReader()) .processor(middleSixthProcessor()) .writer(afterSixthWriter()) .faultTolerant() .skip(Exception.class) .noSkip(FileNotFoundException.class) .noSkip(IOException.class) .skipLimit(10) .build(); } (skip과 noSkip의 순서는 무방함) ​ - Skip을 조금 더 커스텀 하는 방법 (모든 예외를 허용) @Bean public Step sixthStep() { return new StepBuilder("sixthStep", jobRepository) . chunk(10, platformTransactionManager) .reader(beforeSixthReader()) .processor(middleSixthProcessor()) .writer(afterSixthWriter()) .faultTolerant() .skipPolicy(customSkipPolicy) .noSkip(FileNotFoundException.class) .noSkip(IOException.class) .build(); } ​ @Configuration public class CustomSkipPolicy implements SkipPolicy { @Override public boolean shouldSkip(Throwable t, long skipCount) throws SkipLimitExceededException { return true; } } ​ https://docs.spring.io/spring-batch/reference/step/chunk-oriented-processing/configuring-skip.html Configuring Skip Logic :: Spring Batch Spring Batch Documentation / Configuring a Step / Chunk-oriented Processing / Configuring Skip Logic Configuring Skip Logic There are many scenarios where errors encountered while processing should not result in Step failure but should be skipped instead. This is usually a decision that must be made... docs.spring.io ​ Retry ​ Retry는 Step의 과정 중 예외가 발생하게 되면 예외를 특정 수 까지 반복 할 수 있도록 설정하는 방법입니다. ​ @Bean public Step sixthStep() { return new StepBuilder("sixthStep", jobRepository) . chunk(10, platformTransactionManager) .reader(beforeSixthReader()) .processor(middleSixthProcessor()) .writer(afterSixthWriter()) .faultTolerant() .retryLimit(3) .retry(SQLException.class) .retry(IOException.class) .noRetry(FileNotFoundException.class) .build(); } ​ https://docs.spring.io/spring-batch/reference/step/chunk-oriented-processing/retry-logic.html Configuring Retry Logic :: Spring Batch Spring Batch Documentation / Configuring a Step / Chunk-oriented Processing / Configuring Retry Logic Configuring Retry Logic In most cases, you want an exception to cause either a skip or a Step failure. However, not all exceptions are deterministic. If a FlatFileParseException is encountered while... docs.spring.io ​ Writer 롤백 제어 ​ Writer시 특정 예외에 대해 트랜잭션 롤백을 제외하는 방법 ​ @Bean public Step step1(JobRepository jobRepository, PlatformTransactionManager transactionManager) { return new StepBuilder("step1", jobRepository) .chunk(2, transactionManager) .reader(itemReader()) .writer(itemWriter()) .faultTolerant() .noRollback(ValidationException.class) .build(); } ​ Step listener ​ stepListener는 Step의 실행 전후에 특정 작업을 수행 시킬 수 있는 방법입니다. ​ 로그를 남기거나 다음 Step이 준비가 되었는지, 이번 Step과 다음 Step이 의존되는 경우 변수 정리를 진행할 수 있습니다. ​ @Bean public StepExecutionListener stepExecutionListener() { return new StepExecutionListener() { @Override public void beforeStep(StepExecution stepExecution) { StepExecutionListener.super.beforeStep(stepExecution); } @Override public ExitStatus afterStep(StepExecution stepExecution) { return StepExecutionListener.super.afterStep(stepExecution); } }; } @Bean public Step sixthStep() { return new StepBuilder("sixthStep", jobRepository) . chunk(10, platformTransactionManager) .reader(beforeSixthReader()) .processor(middleSixthProcessor()) .writer(afterSixthWriter()) .listener(stepExecutionListener()) .build(); } ​ 이전 : 12. ItemStreamReader 다음 : 14. Job 설정 https://youtu.be/IRTLwGOCpIw 182, 스프링 배치 5 > 14. Job 설정 목표 ​ 실습 영상에서는 하나의 Step만 가지는 Job을 구성했지만 다양한 Step을 구성하고 조건을 둘 수 있는 방법에 대해 살펴보고, Job에 추가할 수 있는 여러 설정들을 알아보겠습니다. ​ Step flow ​ - 순차적으로 Step 실행 @Bean public Job footballJob(JobRepository jobRepository) { return new JobBuilder("footballJob", jobRepository) .start(playerLoad()) .next(gameLoad()) .next(playerSummarization()) .build(); } ​ 가장 첫 번째 실행될 Step만 start() 메소드로 설정한 뒤, next()로 이어주면 됩니다. ​ 다만 앞선 Step이 실패할 경우 연달아 등장하는 Step 또한 실행되지 않습니다. ​ - 조건에 따라 실행 @Bean public Job job(JobRepository jobRepository, Step stepA, Step stepB, Step stepC, Step stepD) { return new JobBuilder("job", jobRepository) .start(stepA) .on("*").to(stepB) .from(stepA).on("FAILED").to(stepC) .from(stepA).on("COMPLETED").to(stepD) .end() .build(); } ​ https://docs.spring.io/spring-batch/reference/step/controlling-flow.html Controlling Step Flow :: Spring Batch Spring Batch Documentation / Configuring a Step / Controlling Step Flow Controlling Step Flow With the ability to group steps together within an owning job comes the need to be able to control how the job “flows” from one step to another. The failure of a Step does not necessarily mean that the Job ... docs.spring.io ​ Job listener ​ jobListener는 Job의 실행 전후에 특정 작업을 수행 시킬 수 있는 방법입니다. ​ @Bean public JobExecutionListener jobExecutionListener() { return new JobExecutionListener() { @Override public void beforeJob(JobExecution jobExecution) { JobExecutionListener.super.beforeJob(jobExecution); } @Override public void afterJob(JobExecution jobExecution) { JobExecutionListener.super.afterJob(jobExecution); } }; } @Bean public Job sixthBatch() { return new JobBuilder("sixthBatch", jobRepository) .start(sixthStep()) .listener(jobExecutionListener()) .build(); } ​ 이전 : 13. Step 설정 다음 : 15. JPA 성능 문제와 JDBC https://youtu.be/FSjUJYZOtXo 183, 스프링 배치 5 > 15. JPA 성능 문제와 JDBC JPA의 Write 성능 문제 ​ 스프링 배치 read와 write 부분을 JPA로 구성할 경우 JDBC 대비 처리 속도가 엄청나게 저하됩니다. Reader의 경우 큰 영향을 미치진 않지만, Writer의 경우 엄청난 영향을 끼치는 이유는 아래와 같습니다. ​ 성능 저하 이유 : bulk 쿼리 실패 ​ Entity의 Id 생성 전략은 보통 IDENTITY로 설정하게 됩니다. 이 설정은 save() 수행시 DB 테이블을 조회하여 가장 마지막 값 보다 1을 증가 시킨 값을 저장하게 됩니다. 여기서 Batch 처리 청크 단위 bulk insert 수행이 무너지게 됩니다. JDBC 기반으로 작성하게 된다면 청크로 설정한 값이 모이게 된다면 bulk 쿼리로 단 1번의 insert가 수행되지만 ​ JPA의 IDENTITY 전략 때문에 bulk 쿼리 대신 각각의 수만큼 insert가 수행됩니다. ​ 비교 구현 ​ - Reader @Bean public RepositoryItemReader beforeSixthReader() { return new RepositoryItemReaderBuilder() .name("beforeReader") .pageSize(10) .methodName("findAll") .repository(beforeRepository) .sorts(Map.of("id", Sort.Direction.ASC)) .build(); } @Bean public JdbcPagingItemReader beforeSixthReader() { return new JdbcPagingItemReaderBuilder() .name("beforeSixthReader") .dataSource(dataSource) .selectClause("SELECT id, username") .fromClause("FROM BeforeEntity") .sortKeys(Map.of("id", Order.ASCENDING)) .rowMapper(new CustomBeforeRowMapper()) .pageSize(10) .build(); } ​ - Writer @Bean public RepositoryItemWriter afterSixthWriter() { return new RepositoryItemWriterBuilder() .repository(afterRepository) .methodName("save") .build(); } @Bean public JdbcBatchItemWriter afterSixthWriter() { String sql = "INSERT INTO AfterEntity (username) VALUES (:username)"; return new JdbcBatchItemWriterBuilder() .dataSource(dataSource) .sql(sql) .itemSqlParameterSourceProvider(new BeanPropertyItemSqlParameterSourceProvider<>()) .build(); } ​ 성능 측정 ​ Job에 Listener 등록 후 시작 및 종료 시간 차이 측정 순수 데이터 이동 104개 ​ - RepositoryItem 기반 ​ - JDBC 기반 ​ 이전 : 14. Job 설정 https://youtu.be/GVSaAzYzCog 185, 그래프 데이터베이스인 Neo4j를 스프링 부트에서 활용하는 방법 스프링 부트 Neo4j ​ 1. 프로젝트 생성 및 DB 연결 2. 활용 및 컨셉 3. Node, Repository 생성 4. CRUD 5. Node, Relationship API 6. 시각화 ​ 코드 ​ https://github.com/xxxjjhhh/spring_boot_neo4j 187, 스프링 부트 Neo4j > 1. 프로젝트 생성 및 DB 연결 Neo4j 준비 ​ https://youtu.be/2Eus0Sr02n4?si=BvXN_XVB-iMZ_gAP ​ 프로젝트 생성 및 의존성 추가 ​ - 스프링 부트 버전 : 3.5.0 - build.gralde 의존성 부분 dependencies { implementation 'org.springframework.boot:spring-boot-starter-data-neo4j' implementation 'org.springframework.boot:spring-boot-starter-mustache' implementation 'org.springframework.boot:spring-boot-starter-web' compileOnly 'org.projectlombok:lombok' annotationProcessor 'org.projectlombok:lombok' testImplementation 'org.springframework.boot:spring-boot-starter-test' testRuntimeOnly 'org.junit.platform:junit-platform-launcher' } ​ application.properties 연결 ​ - application.properties spring.neo4j.uri=bolt://아이피:7687 spring.neo4j.authentication.username=neo4j spring.neo4j.authentication.password=비밀번호 # 기타 로깅 레벨로 cypher 확인 logging.level.org.neo4j.driver.internal=DEBUG logging.level.org.neo4j.driver=DEBUG ​ bolt 프로토콜 포트인 7687을 사용하고 bolt:// 로 연결해야 합니다. ​ Config 클래스 연결 ​ - config > Neo4jConfig.java import org.neo4j.driver.AuthTokens; import org.neo4j.driver.Driver; import org.neo4j.driver.GraphDatabase; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.neo4j.core.Neo4jClient; import org.springframework.data.neo4j.core.transaction.Neo4jTransactionManager; @Configuration public class Neo4jConfig { @Bean public Driver neo4jDriver() { return GraphDatabase.driver( "bolt://아이피:7687", AuthTokens.basic("neo4j", "비밀번호") ); } // cypher 직접 작성 용 client @Bean public Neo4jClient neo4jClient(Driver driver) { return Neo4jClient.create(driver); } @Bean public Neo4jTransactionManager neo4jTransactionManager(Driver driver) { return new Neo4jTransactionManager(driver); } } ​ 다음 : 2. 활용 및 컨셉 https://youtu.be/_rdR9y7AaO8 188, 스프링 부트 Neo4j > 2. 활용 및 컨셉 그래프 DB ​ ​ 그래프 DB는 노드와 간선으로 이루어집니다. ​ 이때 노드와 간선 모두 하나의 고정된 유형이 아닌 다양한 형태 (label, type)을 가질 수 있습니다. 처음 그래프 DB를 접하며 “RDB로 충분히 구현할 수 있는데 왜 사용해야할까?”라는 의구심을 가졌습니다. (노드에 대한 테이블, 노드간 간선에 대한 테이블) ​ 구현은 가능합니다. 하지만 RDB는 노드를 탐색하는 과정을 수행하기 위해선 JOIN이 필요한데, 여러 홉을 타고 갈 경우 성능이 급격하게 저하 됩니다. ​ Neo4j 클라이언트 ​ http://아이피:7474 를 통해 접근 가능합니다. ​ ​ (로그인 실패시 5분 가량의 계정 락이 발생합니다.) ​ Neo4j 쿼리 : Cypher ​ 간단하게 사람이란 노드에 대해 친구 관계를 만드는 예시를 알려드리겠습니다. - 노드 생성 CREATE (p:Person {name: 'yummi', age: 10}) ​ Person이란 label {} 내부 값은 property ​ - 2개의 노드에 대한 관계 생성 MATCH (a:Person {name: 'yummi'}), (b:Person {name: 'xxxjjhhh'}) CREATE (a)-[:FRIENDS]->(b) ​ 2개의 노드를 찾고, 거기에 대한 관계 생성 ​ - 노드 조회 MATCH (p:Person) RETURN p MATCH (p:Person) WHERE p.age > 5 RETURN p ​ - 관계 조회​ MATCH (a:Person)-[:FRIENDS]->(b:Person) RETURN a, b ​ - 노드 수정 MATCH (p:Person {name: 'yummi'}) SET p.age = 50 ​ - 노드 삭제 MATCH (p:Person {name: 'yummi'}) DETACH DELETE p ​ 연관 관계는 자동 삭제 ​ - 관계 삭제​ MATCH (a:Person {name: 'yummi'})-[r:FRIENDS]->(b:Person {name: 'xxxjjhhh'}) DELETE r ​ - 전체 노드 조회​ MATCH (n) RETURN n ​ - 전체 데이터 삭제 MATCH (n) DETACH DELETE n ​ 쿼리가 다소 복잡하고, 데이터를 찾기도 어려워 보임 ​ text2cypher라는 도구가 있습니다. LLM을 활용하여, 자연어를 Cypher 쿼리로 변환하는 도구로 Neo4j plugin에서도 제공하고 있습니다. 요즘 AI 시대가 부상함에 따라 text2sql, text2cypher를 활용하는 것도 좋습니다. ​ 활용 사례 ​ 1. 시멘틱 질의에 대한 결과를 찾기에 강점을 보임 “도산대로 중식 맛집 추천해줘”라는 쿼리를 가지면, LLM을 응용하여 “중식 → 서울 → 강남구” 형태의 지식 그래프에 대한 cypher를 만들어 찾아가기 쉬움 ​ 2. 완제품 생성을 위한 모듈 및 부품 조립 구조 : 자동차 > 모듈 > 부품과 같이 A 부품이 모듈 a, b, c에 들어가고 각 모듈이 더 큰 모듈을 만드는 구조를 시각적으로 표현하기 좋음 ​ 3. 행동 패턴을 파악한 사기 탐지 활용 ​ 실습 컨셉 ​ 간단하게 SNS 계정 네트워크를 만들어 보겠습니다. “Node 계정”, “Relationship 팔로잉” ​ 이전 : 1. 프로젝트 생성 및 DB 연결 다음 : 3. Node, Repository 생성 https://youtu.be/n_KveACbsbQ 189, 스프링 부트 Neo4j > 3. Node, Repository 생성 스프링과 DB 데이터 매핑 ​ Neo4j 데이터베이스에 존재하는 Node와 Relationship을 스프링 부트 객체로 받기 위한 클래스를 만들어 보겠습니다. ​ Node 생성 ​ - domain > account > AccountNode.java import lombok.Getter; import lombok.Setter; import org.springframework.data.neo4j.core.schema.*; import java.util.HashSet; import java.util.Set; @Node("Account") @Getter @Setter public class AccountNode { @Id @GeneratedValue private Long id; @Property("username") private String username; @Relationship(type = "FOLLOWS", direction = Relationship.Direction.OUTGOING) private Set following = new HashSet<>(); @Relationship(type = "FOLLOWS", direction = Relationship.Direction.INCOMING) private Set followers = new HashSet<>(); } ​ 시리즈 컨셉에 따라 유저 정보를 담을 Node 입니다. ​ ​ 연관 관계의 경우 @Relationship을 선언하고, Set또는 List로 받아줍니다. ​ A Node에서 B Node로 팔로잉을 걸 경우, A에는 following, B에는 followers에 객체가 담기며, 동일한 Relationship이라 동일한 type을 가집니다. (단순하게 INCOMING, OUTGOING 차이) ​ Repository 생성 ​ - domain > account > AccountRepository.java public interface AccountRepository extends Neo4jRepository { } ​ 자체적으로 findBy~ 와 같은 메소드들을 제공하지만, cypher 로그를 찍어보면 1개의 Node를 조회하는 경우도 여러개의 cypher가 날라갑니다. ​ 따라서 추후 사용시 직접 @Query()에 cypher를 작성해야 성능적인 최적화를 볼 수 있습니다. ​ 서비스단 클래스 ​ - domain > account > service > AccountService.java @Service public class AccountService { private final AccountRepository accountRepository; public AccountService(AccountRepository accountRepository) { this.accountRepository = accountRepository; } } ​ 이전 : 2. 활용 및 컨셉 다음 : 4. CRUD https://youtu.be/ZO-ZexpULa4 190, 스프링 부트 Neo4j > 4. CRUD 스프링 부트 Neo4j CRUD ​ 스프링 부트 서비스단에서 Neo4j DB에 Node를 CRUD하고, Relationship을 성립 시켜보도록 하겠습니다. ​ Node Create ​ 앞쪽에서 데이터를 받아 하나의 신규 node를 추가하는 메소드 ​ - domain > account > dto > AccountRequestDTO.java @Getter @Setter public class AccountRequestDTO { private String username; } ​ - domain > account > service > AccountService.java public void createAccount(AccountRequestDTO dto) { AccountNode accountNode = new AccountNode(); accountNode.setUsername(dto.getUsername()); accountRepository.save(newNode); } ​ Node 하나 Read ​ 조건 cypher를 위해 Neo4jRepository 커스텀 cypher를 생성해야 합니다. ​ - domain > account > repository > AccountRepository.java Optional findByUsername(String username); @Query("MATCH (a:Account {username: $username}) RETURN a") Optional findByUsernameCustom(@Param("username") String username); ​ 위의 메소드가 기본 메소드지만 로그를 확인하면 cypher가 필요 없이 많이 날라갑니다. 따라서 아래 @Query로 직접 cypher를 선언하는 커스텀 쿼리를 만들어야 합니다. - domain > account > service > AccountService.java public AccountNode findAccount(String username) { return accountRepository.findByUsernameCustom(username).orElseThrow(); } ​ Node 전체 Read ​ - Node만 읽는 경우 연관 관계도 따라오긴 하지만, 추가 cypher가 발생하는 경우가 허다합니다. @Query("MATCH (a:Account) RETURN a") List findAllAccounts(); ​ - Node 및 연관관계까지 읽는 경우 @Query("MATCH (a:Account) OPTIONAL MATCH (a)-[r:FOLLOWS]->(b:Account) RETURN a, collect(r), collect(b)") List findAllAccountsWithRelationships(); ​ - domain > account > service > AccountService.java​ public List readAllAccounts() { return accountRepository.findAllAccountsWithRelationships(); } ​ Node Relationship 생성 ​ - domain > account > dto > RelationRequestDTO.java @Getter @Setter public class RelationRequestDTO { private String start; private String end; } ​ - domain > account > service > AccountService.java // 계정 팔로잉 (Relationship) public void createRelation(RelationRequestDTO dto) { // 거는 계정 -> 목적 계정 모두 불러오기 AccountNode startNode = accountRepository.findByUsernameCustom(dto.getStart()).orElseThrow(); AccountNode endNode = accountRepository.findByUsernameCustom(dto.getEnd()).orElseThrow(); // 거는 사람 startNode.getFollowing().add(endNode); // 걸리는 사람 // 자동 처리 // 저장 accountRepository.save(startNode); } ​ 이전 : 3. Node, Repository 생성 다음 : 5. Node, Relationship API https://youtu.be/9fL0BRDNi58 191, 스프링 부트 Neo4j > 5. Node, Relationship API NodeApi ​ 노드 등록 및 읽기 api ​ - api > NodeApi.java @RestController public class NodeApi { private final AccountService accountService; public NodeApi(AccountService accountService) { this.accountService = accountService; } @PostMapping("/node") public ResponseEntity createNode(@RequestBody AccountRequestDTO dto) { accountService.createAccount(dto); return new ResponseEntity<>(HttpStatus.OK); } @GetMapping("/node/{username}") public ResponseEntity getNode(@PathVariable String username) { return new ResponseEntity<>(accountService.findAccount(username), HttpStatus.OK); } } ​ RelationApi ​ 2개의 노드에 대한 연관 관계 생성 api ​ - api > RelationApi.java @RestController public class RelationApi { private final AccountService accountService; public RelationApi(AccountService accountService) { this.accountService = accountService; } @PostMapping("/relationship") public ResponseEntity createRelationship(@RequestBody RelationRequestDTO dto) { accountService.createRelation(dto); return new ResponseEntity<>(HttpStatus.OK); } } ​ 노드-연관→노드 조회 문제 ​ 1개의 노드를 조회하면 딸려진 노드가 조회 될 것이라 예상됩니다. 하지만 조회되지 않습니다. - 응답 JSON에 following, followers가 빈 리스트로 온 모습 - 문제 ​ - 문제를 해결하기 위한 @Query() cypher 변경 - 실패 MATCH (a:Account {username: $username}) OPTIONAL MATCH (a)-[r:FOLLOWS]->(b:Account) RETURN a, collect(r), collect(b) ​ 조회는 되나, 연관 관계로 인한 무한 루프 발생 @JsonIgnore를 사용하면 위 cypher를 사용할 필요가 없어짐 ​ - DTO 프로젝션 - 실패 @NoArgsConstructor @AllArgsConstructor @Getter @Setter public class AccountResponseDTO { private String username; private Set following; private Set followers; } @Query(""" MATCH (a:Account {username: $username}) OPTIONAL MATCH (a)-[:FOLLOWS]->(f:Account) OPTIONAL MATCH (a)<-[:FOLLOWS]-(fo:Account) RETURN a.username AS username, collect(DISTINCT f.username) AS following, collect(DISTINCT fo.username) AS followers """) Optional findByUsernameCustom(@Param("username") String username); ​ dto 생성 후 결과 프로젝션, 매핑이 불가능함... ​ - Neo4jClient를 통한 조회 - 성공 public AccountResponseDTO findWithClient(String username) { return neo4jClient.query(""" MATCH (a:Account {username: $username}) OPTIONAL MATCH (a)-[:FOLLOWS]->(f:Account) OPTIONAL MATCH (a)<-[:FOLLOWS]-(fo:Account) RETURN a.username AS username, collect(DISTINCT f.username) AS following, collect(DISTINCT fo.username) AS followers """) .bind(username).to("username") .fetchAs(AccountResponseDTO.class) .mappedBy((t, r) -> new AccountResponseDTO( r.get("username").asString(), new HashSet<>(r.get("following").asList(Value::asString)), new HashSet<>(r.get("followers").asList(Value::asString)) )) .one().orElseThrow(); } ​ ​ 이전 : 4. CRUD 다음 : 6. 시각화 https://youtu.be/Ug68n27g9mg 192, 스프링 부트 Neo4j > 6. 시각화 시각화 ​ neo4j 데이터베이스에 존재하는 모든 노드와 노드간의 연관관계를 VIEW 템플릿에 띄워보겠습니다. ​ Controller에서 2가지 데이터 묶음을 응답합니다. ​ - 모든 Node 데이터 (id 값을 포함) - 모든 Relation 데이터 (2노드의 id 값을 포함) ​ ViewApi ​ - api > ViewApi.java @Controller public class ViewApi { private final AccountService accountService; public ViewApi(AccountService accountService) { this.accountService = accountService; } @GetMapping("/") public String viewPage(Model model) { List accounts = accountService.readAllAccounts(); List> visNodes = new ArrayList<>(); List> visEdges = new ArrayList<>(); for (AccountNode node : accounts) { // 노드 추가 Map nodeMap = new HashMap<>(); nodeMap.put("id", node.getId()); nodeMap.put("username", node.getUsername()); visNodes.add(nodeMap); // 팔로잉 관계로 간선 추가 for (AccountNode following : node.getFollowing()) { Map edgeMap = new HashMap<>(); edgeMap.put("start", node.getId()); edgeMap.put("end", following.getId()); visEdges.add(edgeMap); } } model.addAttribute("nodes", visNodes); model.addAttribute("edges", visEdges); return "graph"; } } ​ graph.mustache ​ 그래프 데이터를 시각화 하기 위한 JS 라이브러리는 많습니다. 대표적으로 D3.js가 아주 유명하지만 사용하기 어렵기 때문에 Vis.js를 사용하겠습니다. ​
​ 이전 : 5. Node, Relationship API https://youtu.be/A6xpz6bf9gg 193, 스프링 부트 프레임워크에서 테스트 주도 개발(TDD)을 하는 방법. ​ TDD란, 어떤 행위를 수행하는 메소드를 개발하는 과정에서 행위 메소드를 바로 개발하는 것이 아니라 테스트를 수행하는 메소드를 먼저 만들고, 그 테스트를 만족 시키도록 반복 구현하는 방법입니다. 단위 테스트 ​ 1. 서비스단 테스트 2. API 컨트롤러 테스트 3. 예외 처리 테스트 4. VIEW 컨트롤러 테스트 5. Util 클래스 테스트 6. 시큐리티 추가시 ​ 통합 테스트 ​ 7. 통합 테스트 8. 테스트 메소드 작성 ​ 194, 스프링 부트 TDD > 1. 서비스단 테스트 도메인 구현 ​ 서비스단 단위 테스트를 진행하겠습니다. “스프링 부트3” 시리즈를 통해 프로젝트 DDD 설계시, 도메인에서 가지는 정보를 “저장”하는 곳은 Entity 정보에 대해 CRUD “행위”는 Service에서 진행했습니다. 설계 과정에 맞춰 도메인이 필요한 “저장”소 Entity를 구현하겠습니다. ​ - PostEntity @Entity @Getter @Setter public class PostEntity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String title; private String content; } ​ - PostRepository public interface PostRepository extends JpaRepository { } ​ - PostRequestDTO @Getter @Setter public class PostRequestDTO { private String title; private String content; } ​ 여정 1 : 서비스단 및 서비스단 테스트 클래스 추가 ​ - PostService @Service public class PostService { private final PostRepository postRepository; public PostService(PostRepository postRepository) { this.postRepository = postRepository; } } ​ - PostServiceTest​ @ExtendWith(MockitoExtension.class) class PostServiceTest { @InjectMocks PostService postService; @Mock PostRepository postRepository; } ​ Command + Shift + T 또는 Ctrl + Shift + T ​ 여정 2 : “행위” 메소드 형태 작성 ​ PostEntity에 대한 CRUD 중 create를 수행할 메소드 틀을 작성합니다. create() 메소드를 설계하면서, 대략적으로 DTO를 받아 저장 후 저장 id 값을 리턴한다고 생각하겠습니다. - PostService @Service public class PostService { private final PostRepository postRepository; public PostService(PostRepository postRepository) { this.postRepository = postRepository; } public Long create(PostRequestDTO dto) { throw new UnsupportedOperationException("작성 중"); } } ​ 아직 구현을 완료하지 않아 exception을 던지도록 합니다. ​ 여정 3 : 작성할 메소드에 대한 테스트 1 ​ 첫 번째 테스트로 DTO를 통해 데이터를 넣으면 id값을 정수로 리턴하는지 체크하는 테스트를 만들겠습니다. - PostServiceTest @ExtendWith(MockitoExtension.class) class PostServiceTest { @InjectMocks PostService postService; @Mock PostRepository postRepository; @Test void create_테스트1() { // given PostRequestDTO requestDTO = new PostRequestDTO(); requestDTO.setTitle("제목1"); requestDTO.setContent("내용1"); // when Long resultId = postService.create(requestDTO); // then assertTrue(resultId instanceof Long) } } ​ 여정 4 : 여정 3을 충족시키기 위한 서비스 create() 구현 ​ - PostService @Service public class PostService { private final PostRepository postRepository; public PostService(PostRepository postRepository) { this.postRepository = postRepository; } public Long create(PostRequestDTO dto) { return 1L; } } ​ create() 메소드가 이행해야하는 일을 하지 않았지만, assertTrue()를 충족시켜 테스트가 통과됩니다. 이 때문에 테스트 케이스를 여러개 작성합니다. ​ 여정 5 : 또 다른 case ​ - PostServiceTest @Test void create_테스트2() { // given PostRequestDTO requestDTO = new PostRequestDTO(); requestDTO.setTitle("제목2"); requestDTO.setContent("내용2"); PostEntity saved = new PostEntity(); ReflectionTestUtils.setField(saved, "id", 1L); saved.setTitle("제목"); saved.setContent("내용"); given(postRepository.save(any(PostEntity.class))).willReturn(saved); // when postService.create(requestDTO); // then verify(postRepository).save(any(PostEntity.class)); } ​ 여정 6 : 2개의 test case를 만족 시키기 위해 ​ - PostService @Service public class PostService { private final PostRepository postRepository; public PostService(PostRepository postRepository) { this.postRepository = postRepository; } public Long create(PostRequestDTO dto) { PostEntity postEntity = new PostEntity(); postEntity.setTitle(dto.getTitle()); postEntity.setContent(dto.getContent()); return postRepository.save(postEntity).getId(); } } ​ 여정 7 : dto 입력값 테스트 ​ - PostServiceTest @Test void create_테스트3() { // given PostRequestDTO requestDTO = new PostRequestDTO(); requestDTO.setTitle(""); requestDTO.setContent("내용"); // when & then assertThrows(IllegalArgumentException.class, () -> { postService.create(requestDTO); }); } ​ - PostService​ if (dto.getTitle().isBlank()) { throw new IllegalArgumentException("빈값 금지"); } ​ 앞으로 ​ 계속 반복... ​ 다음 : 2. API 컨트롤러 테스트 https://youtu.be/CcaaX4_ojxw 기타 : import ​ - PostService package com.example.secondtest.domain.post.service; import com.example.secondtest.domain.post.dto.PostRequestDTO; import com.example.secondtest.domain.post.entity.PostEntity; import com.example.secondtest.domain.post.repository.PostRepository; import org.springframework.stereotype.Service; ​ - PostServiceTest package com.example.secondtest.domain.post.service; import com.example.secondtest.domain.post.dto.PostRequestDTO; import com.example.secondtest.domain.post.entity.PostEntity; import com.example.secondtest.domain.post.repository.PostRepository; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.test.util.ReflectionTestUtils; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.verify; ​ 195, 스프링 부트 TDD > 2. API 컨트롤러 테스트 시나리오 ​ 서비스단 create() 메소드와 연계하여, 게시글 작성 엔드포인트 개발을 진행하겠습니다. ​ - 엔드포인트 : POST : “/post” - JSON Body : title, content ​ 여정 1 : 컨트롤러 및 컨트롤러 테스트 클래스 추가 ​ - PostController @RestController public class PostController { private final PostService postService; public PostController(PostService postService) { this.postService = postService; } } ​ - PostControllerTest @WebMvcTest(controllers = PostController.class) class PostControllerTest { @Autowired MockMvc mockMvc; @MockitoBean PostService postService; } ​ - 스프링 부트 3.4 ~ MockBean Deprecated https://docs.spring.io/spring-boot/api/java/org/springframework/boot/test/mock/mockito/MockBean.html MockBean (Spring Boot 3.5.5 API) Package org.springframework.boot.test.mock.mockito Annotation Interface MockBean @Deprecated ( since ="3.4.0", forRemoval =true) @Target ({ TYPE , FIELD }) @Retention ( RUNTIME ) @Documented @Repeatable ( MockBeans.class ) public @interface MockBean Deprecated, for removal: This API element is subje... docs.spring.io ​ ​ 여정 2 : api 메소드 형태 작성 ​ API 요청을 받을 컨트롤러 메소드 형태를 작성합니다. - PostController @RestController public class PostController { private final PostService postService; public PostController(PostService postService) { this.postService = postService; } @PostMapping("/post") public ResponseEntity postMethod( @RequestBody PostRequestDTO dto ) { throw new UnsupportedOperationException("구현 중"); } } ​ 아직 구현을 완료하지 않아 Exception을 던지도록 합니다. ​ 여정 3 : 작성할 메소드에 대한 테스트 1 ​ 먼저 엔드포인트에 JSON title과 content를 보냈을 때, 200(Ok) 응답이 오는지 확인하겠습니다. - PostControllerTest @WebMvcTest(controllers = PostController.class) class PostControllerTest { @Autowired MockMvc mockMvc; @MockitoBean PostService postService; @Test void post_method_테스트1() throws Exception { // given PostRequestDTO requestDTO = new PostRequestDTO(); requestDTO.setTitle("제목"); requestDTO.setContent("내용"); // when & then mockMvc.perform(post("/post") .contentType(MediaType.APPLICATION_JSON) .content(new ObjectMapper().writeValueAsString(requestDTO))) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON)); } } ​ 여정 4 : 여정 3을 충족 시키기 위한 메소드 구현 ​ - PostController @RestController public class PostController { private final PostService postService; public PostController(PostService postService) { this.postService = postService; } @PostMapping("/post") public ResponseEntity postMethod( @RequestBody PostRequestDTO dto ) { //HTTP header HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.setContentType(new MediaType("application", "json")); return new ResponseEntity<>(httpHeaders, HttpStatus.OK); } } ​ 1강과 같이 postMethod()가 이행해야하는 일을 일부러 시키지 않았지만, 테스트는 성공하도록 만들었습니다. ​ 이런 이유 때문에 여러 테스트 단계를 반복 수행하며 행위 메소드를 완성해야 합니다. ​ 여정 5 : 또 다른 case ​ service 의존성을 호출 했는지, HTTP 응답 body에 저장한 값이 오는지 확인하겠습니다. ​ - PostControllerTest @Test void post_method_테스트2() throws Exception { // given PostRequestDTO requestDTO = new PostRequestDTO(); requestDTO.setTitle("제목"); requestDTO.setContent("내용"); given(postService.create(any(PostRequestDTO.class))).willReturn(1L); // when & then mockMvc.perform(post("/post") .contentType(MediaType.APPLICATION_JSON) .content(new ObjectMapper().writeValueAsString(requestDTO))) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andExpect(jsonPath("$.id").value(1)); verify(postService).create(any(PostRequestDTO.class)); } ​ 여정 6 : 2개의 test case를 만족 시키기 위해 ​ - PostController @PostMapping("/post") public ResponseEntity postMethod( @RequestBody PostRequestDTO dto ) { Long resultId = postService.create(dto); // HTTP body Map responseBody = Map.of("id", resultId); //HTTP header HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.setContentType(new MediaType("application", "json")); return new ResponseEntity<>(responseBody, httpHeaders, HttpStatus.OK); } ​ 빈값은? ​ ControllerAdvice를 통해 진행 이전 : 1. 서비스단 테스트 다음 : 3. 예외 처리 테스트 https://youtu.be/d88Bq8M8E3A 196, 스프링 부트 TDD > 3. 예외 처리 테스트 예외 처리 케이스 ​ API 요청시 빈값을 받거나 잘못된 값을 받는 경우 발생하는 Exception을 핸들링하는 부분은 주로 ControllerAdvice에서 처리하게 됩니다. ​ 이 부분까지 합쳐서 테스트를 진행하겠습니다. ​ 예외처리 ​ 서비스단과 연계하여, title에 빈값을 보낼 경우 IllegalArgumentException이 발생하게 됩니다. 이 경우 400 응답을 리턴하도록하는 테스트 케이스를 작성하겠습니다. - PostControllerTest @Test void post_method_테스트3() throws Exception { // given PostRequestDTO requestDTO = new PostRequestDTO(); requestDTO.setTitle(""); requestDTO.setContent("내용"); given(postService.create(any(PostRequestDTO.class))).willThrow(new IllegalArgumentException()); // when & then mockMvc.perform(post("/post") .contentType(MediaType.APPLICATION_JSON) .content(new ObjectMapper().writeValueAsString(requestDTO))) .andExpect(status().isBadRequest()) .andExpect(content().contentType(MediaType.APPLICATION_JSON)); } ​ RestControllerAdvice ​ 컨트롤러 설계시, 모든 컨트롤러 메소드에서 예외에 대한 처리를 작성하는 반복성을 추가할 수 없기 때문에 ControllerAdvice를 통해 처리합니다. ​ 테스트 케이스에서 작성한 부분도 ControllerAdvice에서 처리되는지 확인하겠습니다. - GlobalExceptionHandler @RestControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(IllegalArgumentException.class) public ResponseEntity illegalArgumentException(IllegalArgumentException ex) { //HTTP header HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.setContentType(new MediaType("application", "json")); return new ResponseEntity<>(httpHeaders, HttpStatus.BAD_REQUEST); } } ​ 이전 : 2. API 컨트롤러 테스트 다음 : 4. VIEW 컨트롤러 테스트 https://youtu.be/4mchqIEv0jc 197, 스프링 부트 TDD > 4. VIEW 컨트롤러 테스트 VIEW 템플릿을 리턴하는 경우 ​ mustache나 thymeleaf와 같은 VIEW를 리턴하는 경우 어떻게 테스트 해야 할까요? 테스트는 API 컨트롤러와 거의 흡사하고 given-when-then시 then 검증에서만 조금 다르게 생겼습니다. 결국 리턴 값이 VIEW 이름과 Model 데이터로 이 2개의 값에 대해 Expect 한다고 보시면 됩니다. ​ VIEW 컨트롤러 ​ 이번엔 VIEW에 대해서만 알아보기 때문에 TDD 설계 흐름과 다르게 Controller 부터 대략적으로 알아보고, 테스트 코드를 확인하겠습니다. (실제 설계는 2강과 같이 테스트 메소드 작성 → 테스트 메소드에 맞게 구현 형태로 진행해야 합니다.) - PageController package com.example.secondtest.api; import com.example.secondtest.domain.post.dto.PostRequestDTO; import com.example.secondtest.domain.post.entity.PostEntity; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import java.util.ArrayList; import java.util.List; @Controller public class PageController { @GetMapping("/page") public String getPage(Model model) { List postEntityList = new ArrayList<>(); model.addAttribute("POSTLIST", postEntityList); return "page"; } @PostMapping("/page") public String postPage(PostRequestDTO dto) { return "redirect:/page"; } } ​ VIEW 컨트롤러용 테스트 코드 예시 ​ - PageControllerTest package com.example.secondtest.api; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.http.MediaType; import org.springframework.test.web.servlet.MockMvc; import static org.junit.jupiter.api.Assertions.*; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; @WebMvcTest(controllers = PageController.class) class PageControllerTest { @Autowired MockMvc mockMvc; @Test void get_method_테스트1() throws Exception { // given // when & then mockMvc.perform(get("/page")) .andExpect(status().isOk()) .andExpect(view().name("page")) .andExpect(model().attributeExists("POSTLIST")); } @Test void post_method_테스트1() throws Exception { // given String title = "제목"; String content = "내용"; // when & then mockMvc.perform(post("/page") .contentType(MediaType.APPLICATION_FORM_URLENCODED) .param("title", title) .param("content", content)) .andExpect(status().is3xxRedirection()) .andExpect(redirectedUrl("/page")); } } ​ 이전 : 3. 예외 처리 테스트 다음 : 5. Util 클래스 테스트 https://youtu.be/4i0VXRSytmQ 198, 스프링 부트 TDD > 5. Util 클래스 테스트 Util 클래스 ​ Util 클래스의 경우 보통 static 메소드로 작성합니다. 이 경우는 mock 없이 직접 호출해서 테스트를 수행하게 됩니다. ​ 시나리오 ​ email 포맷을 검증하는 메소드를 TDD 기반으로 작성하겠습니다. ​ 여정 1 : 클래스 및 테스트 클래스 추가 ​ - ValidationUtil public class ValidationUtil { } ​ - ValidationUtilTest import static org.junit.jupiter.api.Assertions.*; class ValidationUtilTest { } ​ 여정 2 : 메소드 형태 작성 ​ - ValidationUtil public class ValidationUtil { // email valid public static boolean isEmail(String email) { throw new UnsupportedOperationException("구현 중"); } } ​ 여정 3 : 테스트 케이스 작성 ​ - ValidationUtilTest class ValidationUtilTest { @Test void isEmail_테스트1() { // given String email = "test@test.com"; // when boolean result = ValidationUtil.isEmail(email); // then assertTrue(result); } @Test void isEmail_테스트2() { // given String email = "test.com"; // when boolean result = ValidationUtil.isEmail(email); // then assertFalse(result); } } ​ 여정 4 : 구현 ​ - ValidationUtil public class ValidationUtil { // email valid public static boolean isEmail(String email) { return email != null && email.matches("^[A-Za-z0-9+_.-]+@[A-Za-z0-9.-]+$"); } } ​ TDD ​ 설계 목표를 분석해 테스트 시나리오인 테스트 메소드를 작성하고 그것을 만족하기 위한 실제 행위 메소드를 반복 구현하여 메소드의 안정성을 높이는게 주 목적이고, 추가적으로 이미 다 구현한 메소드에 대해 값을 검증하는 역할도 수행합니다. ​ 이전 : 4. VIEW 컨트롤러 테스트 다음 : 6. 시큐리티 추가시 https://youtu.be/tzyCULBgfOE 199, 스프링 부트 TDD > 6. 시큐리티 추가시 스프링 시큐리티 추가시 ​ 스프링 시큐리티 의존성을 추가하고 인가 로직을 설정하는 순간 우리가 작성한 Controller MockMvc 테스트가 실패하게 됩니다. ​ 이 문제를 해결하는 방법과 추가적으로 서비스 레이어에서 SecurityContextHolder를 의존해야하는 문제에 대해서도 확인하겠습니다. ​ 실패 확인 ​ 시큐리티 추가 후 기존에 통과 했던 단위 테스트들이 실패하는 것을 확인하겠습니다. 인가가 필요한 경로에 대해 403 응답이 발생함과 동시에 then 검증에서 테스트가 실패했습니다. 이 문제를 어떻게 해결하고, 추가적으로 role에 따른 테스트 검증은 어떻게 진행할까요? ​ @WithMockUser() 활용 ​ 스프링 시큐리티 테스트 의존성에서 제공하는 @WithMockUser 어노테이션을 통해 단위 테스트시 SecurityContext를 만들어줄 수 있습니다. ​ - build.gradle > dependencies testImplementation 'org.springframework.security:spring-security-test' ​ - Controller 적용 @Test @WithMockUser(username = "admin", roles = {"ADMIN"}) void post_method_테스트1() throws Exception { // given PostRequestDTO requestDTO = new PostRequestDTO(); requestDTO.setTitle("제목"); requestDTO.setContent("내용"); // when & then mockMvc.perform(post("/post") .with(csrf()) .contentType(MediaType.APPLICATION_JSON) .content(new ObjectMapper().writeValueAsString(requestDTO))) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON)); } ​ 인가뿐 아니라, 서비스 레이어에서 SecurityContextHolder의 SecurityContext 값을 참조할 경우 동일한 어노테이션으로 사용할 수 있습니다. ​ - csrf 설정 문제 // when & then mockMvc.perform(post("/post") .with(csrf()) .contentType(MediaType.APPLICATION_JSON) .content(new ObjectMapper().writeValueAsString(requestDTO))) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON)); ​ 중요한 점은 GET을 제외한 POST, PUT, DELETE 메소드로 요청을 보내고, 스프링 시큐리티 SecurityConfig 설정에 따라 csrf() 설정이 enable된 경우 when 요청시 csrf 설정을 추가해야 합니다. ​ 인가 상황에 따른 테스트 케이스 작성 가능 ​ 더 나아가, @WithMockUser별 role 값에 대한 테스트 상황을 만들 수 있습니다. 특정 role값이 필요한 경로에 대해 role에 충족하지 못하는 경우 403 응답이 발생하는지 then 검증하기. ​ 기타 : 테스트 메소드에 대해서 TestSecurityConfig 적용 ​ 아주 간혹 사용하는 방법으로 Test 환경에서는 시큐리티 인가 설정을 모두 허용하는 Config를 작성하는 방법입니다. ​ - TestSecurityConfig package com.example.secondtest.config; import org.springframework.boot.test.context.TestConfiguration; import org.springframework.context.annotation.Bean; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.web.SecurityFilterChain; @TestConfiguration public class TestSecurityConfig { @Bean public SecurityFilterChain testSecurityFilterChain(HttpSecurity http) throws Exception { http .csrf(csrf -> csrf.disable()); http .authorizeHttpRequests(auth -> auth .requestMatchers("/**").permitAll()); return http.build(); } } ​ - 테스트 컨트롤러 클래스에서 Import @Import(TestSecurityConfig.class) ​ 이전 : 5. Util 클래스 테스트 다음 : 7. 통합 테스트 https://youtu.be/7ML_leeU6v4 200, 스프링 부트 TDD > 7. 통합 테스트 단위 테스트의 한계 ​ 목표에 알맞은 메소드를 구현하기 위해 가볍게 사용되는 단위 테스트도 결국 한계점이 등장합니다. ​ - “단위” 테스트라는 뜻처럼 전체 레이어의 연동된 흐름을 테스트하지 못 함 - Mock 객체를 활용하기 때문에 실제 객체의 동작과 다를 수 있음 - 전역적인 Config 설정이 누락되는 경우가 있음 위와 같은 문제 때문에 : 1단계 단위 테스트로 각 레이어 메소드를 생성, 2단계로 엔드포인트 요청 흐름을 따라가는 통합 테스트를 수행하게 됩니다. ​ 통합 테스트 준비 ​ 통합 테스트는 실제 영속성을 사용하기 때문에 테스트 후 찌꺼기가 남게 됩니다. ​ 이 문제를 해결하기 위해 테스트 환경용 설정을 붙이는 방법에 대해 알려드리겠습니다. - application-test.properties spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver spring.datasource.url=jdbc:mysql://:3306/yummi?useSSL=false&useUnicode=true&serverTimezone=Asia/Seoul&allowPublicKeyRetrieval=true spring.datasource.username=root spring.datasource.password= spring.jpa.hibernate.ddl-auto=create-drop spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl spring.jpa.show-sql=true ​ test 용 application.properties를 따로 준비합니다. 이때 DB 같은 경우도 테스트용 DB를 따로 구비한 뒤, application-test.properties 변수에 기재합니다. ​ 테스트용 클래스 작성 ​ 통합 테스트는 컨트롤러 클래스가 가진 엔드포인트를 시점으로 테스트가 수행 된다고 할 수 있습니다. 따라서 클래스별로 테스트 클래스를 작성하시면 됩니다. - PostControllerIntegrationTest @SpringBootTest @AutoConfigureMockMvc @ActiveProfiles("test") @Transactional public class PostControllerIntegrationTest { @Autowired MockMvc mockMvc; } ​ 이전 : 6. 시큐리티 추가시 다음 : 8. 테스트 메소드 작성 https://youtu.be/ZQoyetek7tg 201, 스프링 부트 TDD > 8. 테스트 메소드 작성 create 통합 테스트 ​ - PostControllerIntegrationTest @SpringBootTest @AutoConfigureMockMvc @ActiveProfiles("test") @Transactional public class PostControllerIntegrationTest { @Autowired MockMvc mockMvc; @Test void post_통합테스트1() throws Exception { // given PostRequestDTO dto = new PostRequestDTO(); dto.setTitle("제목"); dto.setContent("내용"); // when & then mockMvc.perform(post("/post") .contentType(MediaType.APPLICATION_JSON) .content(new ObjectMapper().writeValueAsString(dto))) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andExpect(jsonPath("$.id").exists()); } } ​ read 통합 테스트 ​ read를 수행하는 GET : “/post/{id}” 엔드포인트와 서비스 메소드를 작성 했습니다. ​ - PostControllerIntegrationTest @SpringBootTest @AutoConfigureMockMvc @ActiveProfiles("test") @Transactional public class PostControllerIntegrationTest { @Autowired MockMvc mockMvc; @Autowired PostRepository postRepository; @Test void get_통합테스트1() throws Exception { // given PostEntity savedEntity = new PostEntity(); savedEntity.setTitle("제목"); savedEntity.setContent("내용"); Long savedId = postRepository.save(savedEntity).getId(); // when & then mockMvc.perform(get("/post/" + savedId)) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andExpect(jsonPath("$.id").value(savedId)) .andExpect(jsonPath("$.title").value("제목")) .andExpect(jsonPath("$.content").value("내용")); } } ​ 이전 : 7. 통합 테스트 https://youtu.be/mNQtUc79JSQ 202, 스프링 부트에 작성한 엔드포인트를 OpenAPI 3.0 스펙으로 명세서를 생성하고 Swagger UI를 통해 대시보드화하는 방법을 알아보겠습니다. ​ 스프링 부트 Swagger ​ 1. API 명세 2. 엔드포인트 OAS 생성 3. 엔드포인트 그룹화 4. 엔드포인트 명세 5. 시큐리티 추가시 203, 스프링 부트 Swagger > 1. API 명세 엔드포인트 공개 ​ 서버에 존재하는 자원은 API를 통해 End User 또는 다른 개발자들에게 제공됩니다. 이런 API를 사용하기 위해선 “기능, 요청 방법 (세부), 응답 형식”을 파악해야 합니다. ​ 따라서 개발한 API를 잘 활용하도록 API 명세서 (스펙)를 작성해야 합니다. ​ API 명세서 획일화 ​ 하지만 전세계에는 수많은 API가 존재하고 각각의 개발자들이 자신만의 형태로 명세서를 작성하게 된다면 새로운 API를 사용할 때 마다 명세서의 형태를 파악해야 합니다. 이 문제를 해결하기 위해 국제적으로 API 명세 표준을 몇 가지 만들어 두었습니다. - OpenAPI (OAS) - RAML - API Blueprint 이 중 가장 많이 사용되는 명세서 작성 형식은 OpenAPI이며 내부적으로 JSON/YAML 형태의 포맷이 있습니다. ​ OAS ​ OpenAPI는 버전이 존재하며 현재 3.0 이라 불리는 3.X 번대의 버전이 stable하고 많이 사용됩니다. 엔드포인트에 대한 설명을 OAS JSON 구조로 작성하면 아래와 같습니다. ​ - JSON 구조 { "openapi": "3.0.1", "info": { "title": "User API", "version": "1.0.0", "description": "API for managing users" }, "paths": { "/users/{id}": { "get": { "summary": "Get user by ID", "parameters": [ { "name": "id", "in": "path", "required": true, "schema": { "type": "integer" }, "description": "ID of the user to return" } ], "responses": { "200": { "description": "User found", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/User" } } } }, "404": { "description": "User not found" } } } }, "/users": { "post": { "summary": "Create a new user", "requestBody": { "required": true, "content": { "application/json": { "schema": { "$ref": "#/components/schemas/UserInput" } } } }, "responses": { "201": { "description": "User created successfully", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/User" } } } }, "400": { "description": "Invalid input" } } } } }, "components": { "schemas": { "User": { "type": "object", "properties": { "id": { "type": "integer", "example": 1 }, "name": { "type": "string", "example": "John Doe" }, "email": { "type": "string", "example": "john@example.com" } }, "required": ["id", "name", "email"] }, "UserInput": { "type": "object", "properties": { "name": { "type": "string", "example": "Jane Doe" }, "email": { "type": "string", "example": "jane@example.com" } }, "required": ["name", "email"] } } } } (ChatGPT에게 알려달라하면 알려줌.. 작성 방법은 다음 시간에 진행합니다.) ​ OAS를 기반으로 시각화 ​ 이후 작성한 OAS를 Swagger UI에 넣는다면 흔히 Swagger라 부르는 아래와 같은 시각화를 진행할 수 있습니다. ​ ​ 따라서 스프링 부트 Controller Endpoint 기반으로 OAS를 자동으로 생성하고, 그것을 활용하여 시각화하는 방법에 대해 알아보겠습니다. ​ 다음 : 2. 엔드포인트 OAS 생성 https://youtu.be/uu8J5q7xh-E 204, 스프링 부트 Swagger > 2. 엔드포인트 OAS 생성 의존성 추가 ​ 스프링 부트 컨트롤러 기반으로 OpenAPI 명세서를 생성하기 위해 관련된 의존성을 추가하겠습니다. - build.gradle implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.8.8' ​ https://mvnrepository.com/artifact/org.springdoc/springdoc-openapi-starter-webmvc-ui ​ 주로 사용되는 버전은 2.2.0, 2.3.0 입니다. ​ 엔드포인트 ​ - OAS - JSON : /v3/api-docs - YAML : /v3/api-docs.yaml - Swagger UI - /swagger-ui/index.html ​ OAS 설명 설정 ​ 우리의 서버는 이러한 서버라고 OAS에 명시할 수 있습니다. 이는 application.properties 또는 Config 클래스를 통해 진행할 수 있습니다. - OpenApiConfig​ import io.swagger.v3.oas.models.OpenAPI; import io.swagger.v3.oas.models.info.Info; import io.swagger.v3.oas.models.servers.Server; @Configuration public class OpenApiConfig { @Bean public OpenAPI openAPI() { return new OpenAPI() .info(new Info() .title("개발자 유미 API 목록") .description("개발자 유미 스프링 부트 Swagger 시리즈 실습을 위한 API 목록입니다.") .version("v1.0.0")) .servers(List.of( new Server() .url("http://localhost:8080") .description("개발용 서버") )); } } ​ 샘플 엔드포인트 ​ - ContentController @RestController @RequestMapping("/api/v1") public class ContentController { @GetMapping("/content/{id}") public ResponseEntity contentGet( @PathVariable("id")Long id ){ Map resultBody = Map.of( "id", id, "title", "제목" + id, "content", "내용" + id ); HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.setContentType(new MediaType("application", "json")); return new ResponseEntity<>(resultBody, httpHeaders, HttpStatus.OK); } @PostMapping("/content") public ResponseEntity contentPost( @RequestBody ContentRequestDTO dto ) { Map resultBody = Map.of("id", 1L); HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.setContentType(new MediaType("application", "json")); return new ResponseEntity<>(resultBody, httpHeaders, HttpStatus.OK); } @DeleteMapping("/content/{id}") public ResponseEntity contentDelete( @PathVariable("id") Long id ) { HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.setContentType(new MediaType("application", "json")); return new ResponseEntity<>(httpHeaders, HttpStatus.OK); } } ​ 이전 : 1. API 명세 다음 : 3. 엔드포인트 그룹화 https://youtu.be/eYihmV2EQZQ 205, 스프링 부트 Swagger > 3. 엔드포인트 그룹화 엔드포인트 도메인 ​ 서비스가 가지는 엔드포인트는 도메인별로 특징이 있습니다. 게시글 관련 CRUD, 회원 관련 CRUD 따라서 이런 엔드포인트들을 그룹화 하는 방법에 대해 알아보겠습니다. ​ @Tag ​ - ContentController @Tag(name = "Content API", description = "게시글 도메인 API") @RestController @RequestMapping("/api/v1") public class ContentController { } ​ 여러 클래스에 대한 동일 그룹화 ​ 동일한 @Tag를 각 클래스별로 부여하면 적용됩니다. ​ 기타 : 대그룹화 ​ “/api/v1”, “/api/v2”와 같이 버전별 진행하는 방법에 대해 알려드리겠습니다. - OpenApiConfig @Bean public GroupedOpenApi groupedOpenApiV1() { return GroupedOpenApi.builder() .group("v1") .pathsToMatch("/api/v1/**") .build(); } @Bean public GroupedOpenApi groupedOpenApiV2() { return GroupedOpenApi.builder() .group("v2") .pathsToMatch("/api/v2/**") .build(); } ​ 이전 : 2. 엔드포인트 OAS 생성 다음 : 4. 엔드포인트 명세 https://youtu.be/rilYsXImzaw 206, 스프링 부트 Swagger > 4. 엔드포인트 명세 엔드포인트에 대한 명세 ​ @GetMapping("/content/{id}") public ResponseEntity contentGet( @PathVariable("id")Long id ){ Map resultBody = Map.of( "id", id, "title", "제목" + id, "content", "내용" + id ); HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.setContentType(new MediaType("application", "json")); return new ResponseEntity<>(resultBody, httpHeaders, HttpStatus.OK); } ​ 그룹 내부에 있는 위와 같은 엔드포인트에 대한 명세를 작성하겠습니다. 명세는 “엔드포인트 역할”, “요청 방법”, “응답 종류”에 대해 어노테이션 기반으로 작성하시면 됩니다. ​ @Operation ​ 위 명세를 작성할 수 있는 어노테이션은 @Operation입니다. ​ @Operation() ​ - 엔드포인트에 대한 설명 @Operation( summary = "게시글 Read", description = "게시글의 ID를 파라미터로 보내면 해당하는 게시글 조회" ) ​ 요청에 대한 명세 ​ - Query 파라미터 변수 parameters = { @Parameter( name = "id", description = "조회할 게시글 ID", required = true, in = ParameterIn.QUERY ) } ​ - Path 파라미터 변수 parameters = { @Parameter( name = "id", description = "조회할 게시글 ID", required = true, in = ParameterIn.PATH ) } ​ - JSON Body requestBody = @io.swagger.v3.oas.annotations.parameters.RequestBody( description = "게시글 JSON Body 데이터", required = true, content = @Content( mediaType = "application/json", schema = @Schema(implementation = ContentRequestDTO.class) ) ), ​ 응답에 대한 명세 ​ - 상태 코드에 따른 응답 종류 responses = { @ApiResponse( responseCode = "200", description = "성공" ), @ApiResponse( responseCode = "400", description = "실패" ) } ​ - JSON Body @ApiResponse( responseCode = "200", description = "성공", content = @Content( mediaType = "application/json", schema = @Schema(implementation = ContentResponseDTO.class) ) ) ​ 예시 ​ @Tag(name = "ContentAPI", description = "게시글 도메인 API") @RestController @RequestMapping("/api/v1") public class ContentController { @Operation( summary = "게시글 Read", description = "게시글의 ID를 파라미터로 보내면 해당하는 게시글 조회", parameters = { @Parameter( name = "id", description = "조회할 게시글 ID", required = true, in = ParameterIn.PATH ) }, responses = { @ApiResponse( responseCode = "200", description = "성공", content = @Content( mediaType = "application/json", schema = @Schema(implementation = ContentResponseDTO.class) ) ), @ApiResponse( responseCode = "400", description = "실패" ) } ) @GetMapping("/content/{id}") public ResponseEntity contentGet( @PathVariable("id")Long id ){ // 무시 ContentResponseDTO.java 기반으로 응답된다고 가정 Map resultBody = Map.of( "id", id, "title", "제목" + id, "content", "내용" + id ); HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.setContentType(new MediaType("application", "json")); return new ResponseEntity<>(resultBody, httpHeaders, HttpStatus.OK); } @Operation( summary = "게시글 Create", description = "게시글 작성 후 ID 반환", requestBody = @io.swagger.v3.oas.annotations.parameters.RequestBody( description = "게시글 데이터", required = true, content = @Content( mediaType = "application/json", schema = @Schema(implementation = ContentRequestDTO.class) ) ), responses = { @ApiResponse( responseCode = "200", description = "성공", content = @Content( mediaType = "application/json", examples = @ExampleObject( value = "{\"id\":1}" ) ) ), @ApiResponse( responseCode = "400", description = "실패" ) } ) @PostMapping("/content") public ResponseEntity contentPost( @RequestBody ContentRequestDTO dto ) { Map resultBody = Map.of("id", 1L); HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.setContentType(new MediaType("application", "json")); return new ResponseEntity<>(resultBody, httpHeaders, HttpStatus.OK); } } ​ 이전 : 3. 엔드포인트 그룹화 다음 : 5. 시큐리티 추가시 https://youtu.be/NBaBy4sr4Ws 207, 스프링 부트 Swagger > 5. 시큐리티 추가시 시큐리티 추가시 ​ Swagger가 적용된 상태에서 스프링 시큐리티를 추가하게 된다면 몇가지 상황을 고려해야 합니다. ​ Swagger UI 경로 permitAll 적용시 ​ Swagger UI 경로인 “/swagger-ui/index.html”을 모든 사용자에게 공개하기 위해 permitAll을 설정한다면 OAS 경로도 함께 permitAll 해야 합니다. - SecurityConfig 예시 @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http .authorizeHttpRequests(auth -> auth .requestMatchers("/swagger-ui/**", "/v3/api-docs/**").permitAll()); return http.build(); } ​ 요청 헤더에 JWT가 들어가는 경우 명세 작성 ​ 시큐리티에 의해 요청 헤더에 JWT가 필요한 경우 명세서에도 표기해야 합니다. (Swagger 테스트시도 필요) - OpenApiConfig @Bean public OpenAPI openAPI() { return new OpenAPI() .info(new Info() .title("개발자 유미 API 목록") .description("개발자 유미 스프링 부트 Swagger 시리즈 실습을 위한 API 목록입니다.") .version("v1.0.0") ) .servers(List.of( new Server() .url("http://localhost:8080") .description("개발용 서버") )) .components(new Components() .addSecuritySchemes("JWT", new SecurityScheme() .type(SecurityScheme.Type.HTTP) .scheme("bearer") .bearerFormat("JWT") .in(SecurityScheme.In.HEADER) .name("Authorization") ) ); } ​ - 특정 엔드포인트에 대해 : Operation() security = @SecurityRequirement(name = "JWT"), addSecuritySchemes()에 명시된 보안 스킴 name 설정으로 적용 됩니다. ​ 로그인/로그아웃 엔드포인트 문제 ​ 스프링 시큐리티의 인증/인증 해제 엔드포인트는 모두 필터단에서 처리됩니다. 따라서 Swagger 적용이 까다롭습니다. 이 문제를 해결하기 위해 Swagger는 기본 로그인에 대해서 엔드포인트 활성화를 제공합니다. - application.properties 설정 springdoc.show-login-endpoint=true springdoc.show-oauth2-endpoints=true ​ 문제는 로그인 필터를 커스텀하게 된다면 적용되지 않습니다. ​ - 편법 로그인/로그아웃은 모두 필터단에서 처리됩니다. 따라서 해당 엔드포인트에 대한 서블릿 Mapping을 만들어도 도달하지 않습니다. 이를 바탕으로 로그인/로그아웃 가짜 컨트롤러 엔드포인트를 만든 뒤 (실제 동작은 수행하지 않는), Swagger 어노테이션을 붙여 명세가 완성되도록 설정하면 됩니다. ​ 이전 : 4. 엔드포인트 명세 https://youtu.be/ecHwgL6E2CA 208, 스프링 부트에 CKEditor5를 적용하고 CKEditor5에서 작성한 글을 DB(MySQL)에 저장하고 업로드한 사진을 AWS S3에 백업하는 로직을 작성하는 실습 ​ 스프링 부트 + CKEditor5 ​ 1. 실습 환경 및 버전 4. 컨트롤러, 뷰 기본 코드 작성 5. 에디터 페이지 Form 태그 작성 6. CDN 방식 추가 7. 다운로드 (로컬) 방식 추가 8. 글작성 - DTO - 컨트롤러 9. AWS RDS 스프링 부트 연결 10. 글저장 테이블 생성 11. 컨트롤러 - 서비스 - DB 코드 12. 글목록 조회 코드 작성 13. 세부 게시글 조회 14. 게시글 삭제 로직 15. 게시글 수정 로직 16. 이미지 업로드 (프론트) 17. AWS S3 생성 및 스프링 부트 연결 18. 이미지 저장 (백엔드) 19. 오류 및 플러그인 20. 띄어쓰기 한글 자모 분리 문제 ​ ​ 209, 스프링 부트 CKEditor5 > 1. 실습 환경 및 버전 환경 및 버전 ​ - 스프링 부트 3.1.2 (스프링 6.1.2) - Mustache 뷰단 - 스프링 Data JPA - lombok - 자바17, (OpenJDK 18) - Gradle 빌드 도구 - 인텔리제이 - 윈도우 환경 - CKEditor5 (39.0.0, CDN) - AWS RDS MySQL8 - AWS S3 ​ 강의 순서 예상 ​ 대략적인 구상입니다. 스프링 부트 환경 구성 → CKEditor5 뷰단에 부착 → 게시글 작성 및 DB 저장 → 게시글 수정 → 이미지 업로드 및 S3 저장 → ??? ​ ​ 다음 : 4. 컨트롤러, 뷰 기본 코드 작성 https://youtu.be/KDSJFSp4c4I 212, 스프링 부트 CKEditor5 > 4. 컨트롤러, 뷰 기본 코드 작성 작성할 컨트롤러, VIEW ​ 메인창 : 경로 /main | 컨트롤러 O | 뷰단 (페이지) O 에디터 : 경로 /editor | 컨트롤러 O | 뷰단 (페이지) O 글저장 : 경로 /save | 컨트롤러 O | 글목록 : 경로 /list | 컨트롤러 O | 뷰단 (페이지) O 글내용 : 경로 /content | 컨트롤러 O | 뷰단 (페이지) O ​ 현재 DB를 연결하지 않았기 때문에 의존성 주석 처리 ​ DB 의존성을 선언했지만 DB를 연결하지 않을 경우 실행 오류가 발생한다. 따라서 의존성을 주석처리하여 연결하기 전까지 의존성을 분리하자. - build.gradle에서 주석 처리 ​ ​ dependencies에 대해서 Spring Data JPA와 MySQL Connector 드라이버를 각주처리하여 DB를 연결하지 않고 실행되도록 임시 설정 진행 ​ 컨트롤러 작성 ​ 메인창 : 경로 /main | 컨트롤러 O | 뷰단 (페이지) O 에디터 : 경로 /editor | 컨트롤러 O | 뷰단 (페이지) O 글저장 : 경로 /save | 컨트롤러 O | 글목록 : 경로 /list | 컨트롤러 O | 뷰단 (페이지) O 글내용 : 경로 /content | 컨트롤러 O | 뷰단 (페이지) O ​ 필요한 컨트롤러 5개 ​ src/main/java/com/example/demo 경로 아래에 컨트롤러를 담을 Package를 생성한다. ​ 생성한 controller 패키지 아래에 Java Class 생성을 통해 컨트롤러를 생성 ​ 컨트롤러 5개의 이름은 - MainController - EditorController - SaveController - ListController - ContentController 컨트롤러 클래스에 @Controller 어노테이션 선언을 통한 스프링 부트 빈 컨테이너에 등록 ​ VIEW단 작성 : mustache 활용 ​ 메인창 : 경로 /main | 컨트롤러 O | 뷰단 (페이지) O 에디터 : 경로 /editor | 컨트롤러 O | 뷰단 (페이지) O 글저장 : 경로 /save | 컨트롤러 O | 글목록 : 경로 /list | 컨트롤러 O | 뷰단 (페이지) O 글내용 : 경로 /content | 컨트롤러 O | 뷰단 (페이지) O 주소에 대한 뷰 창이 필요한 경우 생성해야 한다. ​ 이후 생성한 뷰 파일을 컨트롤러에서 요청 경로에 따라 응답해주면 그 창을 볼 수 있다. ​ ​ scr/main/resources/templates 경로에 뷰단을 생성해야 한다. templates 우클릭 New → File 클릭 후 파일이름.mustache로 mustache 뷰단을 생성한다. ​ ​ main.mustache의 경우 루트 경로에 접근할 경우 컨트롤러에서 main.mustache를 응답하면 된다. ​ 컨트롤러 - VIEW 연결 ​ 컨트롤러 클래스에서 @GetMapping(”/경로”) 어노테이션을 통해 Get 요청에 대한 응답 메소드를 작성하면 된다. 응답할 뷰 파일이 main.mustache일 경우 return “main”;으로 표기 ​ @Controller public class MainController { @GetMapping("/") public String mainPage() { return "main"; } } ​ 이전 : 1. 실습 환경 및 버전 다음 : 5. 에디터 페이지 Form 태그 작성 https://youtu.be/I1x2MFfeVls 213, 스프링 부트 CKEditor5 > 5. 에디터 페이지 Form 태그 작성 HTML Form 태그 작성 이유 ​ CKEditor는 독립적으로 동작하는 것이 아닌 Form 태그 textarea 요소에 플러그인 형태로 동작하게 된다. 따라서 CKEditor를 추가하기 위한 기본적인 Form틀을 생성해야 한다. ​ HTML Form 코드 ​


​ mustache 한글 깨짐 문제 ​ - application.properties 파일에 아래 변수값 설정 server.servlet.encoding.charset=UTF-8 server.servlet.encoding.force=true ​ 이전 : 4. 컨트롤러, 뷰 기본 코드 작성 다음 : 6. CDN 방식 추가 https://youtu.be/yuoICQAKzYQ 214, 스프링 부트 CKEditor5 > 6. CDN 방식 추가 CKEditor5 CDN 주소 ​ CKEditor 5 - Download Latest Version 바로가기 CKEditor 5 - Download Latest Version Download a ready-to-use CKEditor 5 Build. Install, download or serve a ready-to-use rich text editor of your choice. ckeditor.com ​ ​ Form 태그에 적용 ​


​ 이전 : 5. 에디터 페이지 Form 태그 작성 다음 : 7. 다운로드 (로컬) 방식 추가 https://youtu.be/i-4qbA8upiY 215, 스프링 부트 CKEditor5 > 7. 다운로드 (로컬) 방식 추가 다운로드 공식 주소 ​ CKEditor 5 - Download Latest Version 바로가기 ​ CKEditor5 다운로드 후 압축 풀기 ​ 프로젝트 내부에 저장 ​ 다운로드한 CKEditor5 폴더를 스프링 부트 프로젝트 내부로 옮겨야 한다. 이때 경로는 : resources > static > 폴더넣기 ​ ​ editor.mustache에 스크립트 가져오기 ​ ​ 중요한 사항은 build 폴더 아래에 있는 ckeditor.js를 가져와야 합니다. ​ Form 태그에 에디터 적용 ​


​ 이전 : 6. CDN 방식 추가 다음 : 8. 글작성 - DTO- 컨트롤러 https://youtu.be/BYwLIKxMZS8 216, 스프링 부트 CKEditor5 > 8. 글작성 - DTO - 컨트롤러 에디터로 작성한 글의 행방 ​ ​ 에디터 게시글을 작성한 뒤 전송 버튼을 누르면 글 데이터는 서버측으로 전달된다. ​ 이때 전송 경로는 HTML Form 코드에 작성되어 있는 위치로 전달 된다. ​ ​ 서버측 receive ​ Form 태그에서 전송한 데이터는 서버측 컨트롤러단에서 받아야 한다. ​ 데이터를 받은 후 컨트롤러 - 서비스 - 리포지토리(엔티티) - DB 의 저장 과정을 통해 게시글을 저장한다. 컨트롤러의 경우 에디터로 부터 전송되어 오는 데이터를 DTO 객체에 담아 내부 변수에 데이터를 담은 뒤 컨트롤러의 인자로 받는다. ​ @Controller public class 클래스 { @PostMapping("/save") public String saveFunc(DTO클래스 dto인자) { return "redirect:/" } } ​ DTO 클래스 생성 ​ DTO 클래스들을 담기 위한 com.example.demo 경로 아래에 dto 패키지를 생성한다. ​ DTO 클래스는 Form 태그에서 전송하는 요소들의 name 값과 동일한 이름의 변수를 가지며 Setter 메소드를 필수적으로 가져야 데이터가 담긴다. ​ @Data public class SaveDTO { private String title; private String content; } 요청과 데이터가 담긴 DTO 클래스를 받을 컨트롤러 클래스 ​ @Controller public class SaveController { @PostMapping("/save") public String saveLogic(SaveDTO saveDTO) { System.out.println(saveDTO); return "redirect:/"; } } ​ 앞으로의 과정 ​ 글 데이터를 컨트롤러에서 받은 후 컨트롤러 - 서비스 - 리포지토리(엔티티) - DB 의 과정을 통해 데이터베이스에 저장하면 된다. ​ 이전 : 7. 다운로드 (로컬) 방식 추가 다음 : 9. AWS RDS 스프링 부트 연결 https://youtu.be/-5fC7HHUF6Q 217, 스프링 부트 CKEditor5 > 9. AWS RDS 스프링 부트 연결 스프링 부트 프로젝트 의존성 추가 ​ build.gradle에서 데이터베이스 연결에 관한 의존성 관리 4강에서 주석 처리한 스프링 Data JPA 및 MySQL 드라이버 원상 복구 ​ 주석 제거 후 그레들 버튼을 눌려 재로딩 ​ AWS RDS MySQL 빌리기 ​ ​ 빌린 후 생성까지 약 5분 소요 ​ 생성이 완료된 후 엔드포인트, 포트, username, 비밀번호 기억 ​ RDS를 포함하는 보안그룹 3306 포트 열기 ​ RDS 생성시 데이터베이스 포트를 3306으로 설정했기 때문에 RDS를 포함하는 보안그룹 3306 포트를 외부에서 접근할 수 있도록 열어주어야 한다. AWS 콘솔 > EC2 > 보안그룹 > 인바운드규칙 > 인바운드규칙 편집 (RDS를 포함시킨 보안그룹) ​ ​ 3306포트 Anywhere-IPv4 설정 ​ application.properties에 데이터베이스 정보 추가 ​ 스프링 부트는 하나의 데이터베이스에 대해서 정보값만으로 연결을 지원한다. (두개 이상부터 config 클래스 활용) - application.properties 작성 spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver spring.datasource.url=jdbc:mysql://주소:포트/데이터베이스?useSSL=false&useUnicode=true&serverTimezone=Asia/Seoul&allowPublicKeyRetrieval=true spring.datasource.username=아이디 spring.datasource.password=비밀번호 ​ 이전 : 8. 글작성 - DTO - 컨트롤러 다음 : 10. 글저장 테이블 생성 https://youtu.be/DG4qwH9bUYA 218, 스프링 부트 CKEditor5 > 10. 글저장 테이블 생성 모식도 ​ 테이블 조건 ​ 테이블의 경우 최소 3가지 값이 필요하다. ​ 1. id 2. title 3. content ​ id의 경우 각각의 데이터를 구별할 고유 번호, title은 제목, content는 내용이다. 테이블 생성 방법 ​ 스프링 부트에 연결한 DB 내부에 게시글을 저장할 테이블을 생성해야 한다. ​ 테이블 생성은 sql문을 통해 MySQL 클라이언트에서 진행할 수 있지만 스프링 부트와 Gradle 환경에서는 Entity, Repository 클래스를 통해 테이블을 생성할 수 있다. ​ 따라서 DB에서 테이블을 생성하는 것이 아닌 스프링 부트 코드를 통해 몇가지 설정만으로 테이블을 생성하고 바로 연결할 수 있다. 테이블 생성을 위한 조건 설정 ​ application.properties에서 변수 설정을 통해 Entity에 매핑될 테이블을 DB 내부에 자동 생성할 수 있다. ​ #테이블 생성 조건 spring.jpa.hibernate.ddl-auto=none #테이블 변수 작명법 및 변경법 spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl ​ spring.jpa.hibernate.ddl-auto 설정의 경우 스프링 부트에 존재하는 Entity 클래스와 매핑될 테이블 설정을 진행할 수 있다. 이때 변수에 들어갈 값은 아래와 같다. - none : 아무 설정을 진행하지 않음 - create : 테이블을 새로 생성 (이미 테이블이 존재한다면 제거하고 생성) - update : 변경점 수정 (테이블이 존재한다면 그냥 두거나 변경된 부분만 수정) 테이블에 매핑될 Entity 클래스 작성 ​ @Entity @Data public class ContentEntity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; private String title; private String content; } ​ DB 접근에 사용할 Repository 인터페이스 작성 ​ public interface ContentRepository extends JpaRepository { } ​ 테이블 저장 타입 변경 ​ 테이블을 스프링 부트 ddl-auto 설정을 통해 생성할 경우 String 값에 대해서 varchar(255) 설정이 기본값으로 들어간다. varchar(255)의 경우 영문 기준 255자까지만 저장되기 때문에 게시글의 내용을 저장하기 위해서는 더 큰 저장 타입이 필요하다. 이 경우 테이블의 컬럼 타입 수정 sql문을 통해 content 열에 대한 타입을 LONGTEXT로 변경해야 한다. ​ DESC 테이블명; ALTER TABLE 테이블명 MODIFY 컬럼명 LONGTEXT; ​ 이전 : 9. AWS RDS 스프링 부트 연결 다음 : 11. 컨트롤러 - 서비스 - DB 코드 https://youtu.be/81zU_wvBRpc 219, 스프링 부트 CKEditor5 > 11. 컨트롤러 - 서비스 - DB 코드 프로젝트 계층 ​ ​ 코드 ​ - controller : SaveController (CKEditor Form으로 부터 데이터를 받는 컨트롤러) @Controller public class SaveController { private ContentService contentService; @Autowired public SaveController(ContentService contentService) { this.contentService = contentService; } @PostMapping("/save") public String saveLogic(SaveDTO saveDTO) { contentService.saveContent(saveDTO); return "redirect:/"; } } ​ - service : ContentService @Service public class ContentService { private ContentRepository contentRepository; @Autowired public ContentService(ContentRepository contentRepository) { this.contentRepository = contentRepository; } public void saveContent(SaveDTO saveDTO) { String title = saveDTO.getTitle(); String content = saveDTO.getContent(); ContentEntity content1 = new ContentEntity(); content1.setTitle(title); content1.setContent(content); contentRepository.save(content1); return; } } ​ 이전 : 10. 글저장 테이블 생성 다음 : 12. 글목록 조회 코드 작성 https://youtu.be/lSoMfTgQI1E 220, 스프링 부트 CKEditor5 > 12. 글목록 조회 코드 작성 메인창 : 경로 /main | 컨트롤러 O | 뷰단 (페이지) O 에디터 : 경로 /editor | 컨트롤러 O | 뷰단 (페이지) O 글저장 : 경로 /save | 컨트롤러 O | 글목록 : 경로 /list | 컨트롤러 O | 뷰단 (페이지) O 글내용 : 경로 /content | 컨트롤러 O | 뷰단 (페이지) O 조회 방법 ​ ​ 뷰단 : list.mustache ​ 컨트롤러 : /list ​ 서비스 : ContentService ​ 엔티티 : ContentEntity ​ 리포지토리 : ContentRepository ​ 코드 ​ - ContentService @Service public class ContentService { private ContentRepository contentRepository; @Autowired public ContentService(ContentRepository contentRepository) { this.contentRepository = contentRepository; } public void saveContent(SaveDTO saveDTO) { String title = saveDTO.getTitle(); String content = saveDTO.getContent(); ContentEntity content1 = new ContentEntity(); content1.setTitle(title); content1.setContent(content); contentRepository.save(content1); return; } public List selectContent() { return contentRepository.findAll(); } } ​ - ListController @Controller public class ListController { private ContentService contentService; @Autowired public ListController(ContentService contentService) { this.contentService = contentService; } @GetMapping("/list") public String listPage(Model model) { model.addAttribute("ContentList", contentService.selectContent()); return "list"; } } ​ - list.mustache Document

list

{{#ContentList}} {{title}}
{{/ContentList}} ​ 이전 : 11. 컨트롤러 - 서비스 - DB 코드 다음 : 13. 세부 게시글 조회 https://youtu.be/Nf6pwESESzg 221, 스프링 부트 CKEditor5 > 13. 세부 게시글 조회 조회 로직 생각 ​ ​ 12강에서 사용한 N개의 게시글 목록을 조회하는 list.mustache와 그 뒷단의 로직이다. 세부 게시글 조회 또한 위 로직과 아주 유사하다. 세부 게시글 조회의 경우 단 하나의 게시글 번호에 대한 데이터만 가져오면 된다. URL 요청의 경우 : /content/글번호 형태로 요청하면 Controller단에서 해당 번호에 대한 데이터를 뒷단으로 부터 가져오면 된다. 구체화 ​ 세부글 : 경로 /content/글번호 글 번호의 경우 DB에 저장된 id 값으로 설정 하나의 Controller, content.mustache에서 글번호(id)에 따라 다른 데이터를 넣어주면 됨. ​ 코드 ​ - content.mustache Document

content


{{Content.title}}


{{{Content.content}}}
​ - ContentController​ @Controller public class ContentController { private ContentService contentService; @Autowired public ContentController(ContentService contentService) { this.contentService = contentService; } @GetMapping("/content/{id}") public String contentPage(@PathVariable("id")String id, Model model) { System.out.println(id); model.addAttribute("Content", contentService.selectOneContent(id)); return "content"; } } ​ - ContentService @Service public class ContentService { private ContentRepository contentRepository; public ContentService(ContentRepository contentRepository) { this.contentRepository = contentRepository; } public void saveContent(SaveDTO saveDTO) { String title = saveDTO.getTitle(); String content = saveDTO.getContent(); ContentEntity content1 = new ContentEntity(); content1.setTitle(title); content1.setContent(content); contentRepository.save(content1); return; } public List selectContent() { return contentRepository.findAll(); } public ContentEntity selectOneContent(String id) { int to = Integer.parseInt(id); return contentRepository.findById(to); } } ​ - ContentRepository​ public interface ContentRepository extends JpaRepository { ContentEntity findById(int id); } ​ 이전 : 12. 글목록 조회 코드 작성 다음 : 14. 게시글 삭제 로직 https://youtu.be/Zy6sdwpwD_A 222, 스프링 부트 CKEditor5 > 14. 게시글 삭제 로직 메인창 : 경로 /main | 컨트롤러 O | 뷰단 (페이지) O 에디터 : 경로 /editor | 컨트롤러 O | 뷰단 (페이지) O 글저장 : 경로 /save | 컨트롤러 O | 글삭제 : 경로 /delete | 컨트롤러 O | 글목록 : 경로 /list | 컨트롤러 O | 뷰단 (페이지) O 글내용 : 경로 /content | 컨트롤러 O | 뷰단 (페이지) O 글 삭제 경로 ​ /delete/{글번호} ​ 삭제 로직 ​ 삭제 요청을 받는 컨트롤러 (글번호를 변수로 받음) → 변수에 대해 리포지토리를 조작하는 서비스 → Delete 메소드를 실행하는 리포지토리 ​ 코드 ​ - DeleteController​ @Controller public class DeleteController { private ContentService contentService; public DeleteController(ContentService contentService) { this.contentService = contentService; } @GetMapping("/delete/{id}") public String deleteC(@PathVariable("id")String id) { contentService.deleteOneContent(id); return "redirect:/list"; } } ​ - ContentService​ @Service public class ContentService { private ContentRepository contentRepository; @Autowired public ContentService(ContentRepository contentRepository) { this.contentRepository = contentRepository; } public void saveContent(SaveDTO saveDTO) { String title = saveDTO.getTitle(); String content = saveDTO.getContent(); ContentEntity content1 = new ContentEntity(); content1.setTitle(title); content1.setContent(content); contentRepository.save(content1); return; } public List selectContent() { return contentRepository.findAll(); } public ContentEntity selectOneContent(String id) { int to = Integer.parseInt(id); return contentRepository.findById(to); } public void deleteOneContent(String id) { int to = Integer.parseInt(id); contentRepository.deleteById(to); } } ​ - ContentRepository public interface ContentRepository extends JpaRepository { ContentEntity findById(int id); } ​ 이전 : 13. 세부 게시글 조회 다음 : 15. 게시글 수정 로직 https://youtu.be/-OV1zGW61mA 223, 스프링 부트 CKEditor5 > 15. 게시글 수정 로직 게시글 수정의 흐름 ​ 에디터 : 경로 /editor : 새글 작성 에디터 : 경로 /editor/번호 : 게시글 수정 ​ 불러오는 로직 ​ 1. /editor/번호 경로로 요청 2. EditorController에서 번호를 받은 뒤 서비스단에 요청 3. ContentService단에서 게시글 번호에 대한 테이블 데이터 조회 메소드 작성 4. EditorController에서 DB로 부터 온 데이터 Model 객체를 통해 에디터에 추가 5. 이후 저장 로직 작성 ​ 수정을 마친 글 저장 URL ​ 글저장 : 경로 /save : 새글 저장 글저장 : 경로 /save/글번호 : 게시글 수정 ​ ​ 수정 후 저장 로직 ​ 1. 기존 데이터 삭제 후 새로 넣기 1.1. ContentService단에서 기존 id에 해당하는 데이터 삭제 1.2. 앞단에서 들어온 수정된 데이터 save 2. 기존 데이터에 덮어 쓰기 2.1. ContentService에서 앞단에서 들어온 수정된 데이터 덮어쓰기 ​ 덮어쓰는 메소드 ​ 스프링 Data JPA에서는 save() 메소드를 통해 업데이트와 생성이 가능하다. save() 메소드는 테이블 PK 값에 대해서 이미 존재하는 PK 값 데이터가 들어올 경우 덮어쓰는 update 구문을 실행한다. ​ 코드 ​ - content.mustache : (단순하게 URL 요청을 위해 하이퍼 링크만 넣음) Document

content


{{Content.title}}

게시글 수정   게시글 삭제


{{{Content.content}}}
​ - EditorController @Controller public class EditorController { private ContentService contentService; public EditorController(ContentService contentService) { this.contentService = contentService; } @GetMapping("/editor") public String editorPage() { return "editor"; } @GetMapping("/editor/{id}") public String updatePage(@PathVariable("id")String id, Model model) { model.addAttribute("data", contentService.selectOneContent(id)); return "editor"; } } ​ - ContentService @Service public class ContentService { private ContentRepository contentRepository; @Autowired public ContentService(ContentRepository contentRepository) { this.contentRepository = contentRepository; } public void saveContent(SaveDTO saveDTO) { String title = saveDTO.getTitle(); String content = saveDTO.getContent(); ContentEntity content1 = new ContentEntity(); content1.setTitle(title); content1.setContent(content); contentRepository.save(content1); return; } public List selectContent() { return contentRepository.findAll(); } public ContentEntity selectOneContent(String id) { int to = Integer.parseInt(id); return contentRepository.findById(to); } public void deleteOneContent(String id) { int to = Integer.parseInt(id); contentRepository.deleteById(to); } public void updateOneContent(SaveDTO saveDTO, String id) { int to = Integer.parseInt(id); ContentEntity content1 = new ContentEntity(); content1.setId(to); content1.setTitle(saveDTO.getTitle()); content1.setContent(saveDTO.getContent()); contentRepository.save(content1); } } ​ - editor.mustache Document editor


​ - SaveController @Controller public class SaveController { private ContentService contentService; @Autowired public SaveController(ContentService contentService) { this.contentService = contentService; } @PostMapping("/save") public String saveLogic(SaveDTO saveDTO) { contentService.saveContent(saveDTO); return "redirect:/"; } @PostMapping("/save/{id}") public String updateLogic(SaveDTO saveDTO, @PathVariable("id")String id) { contentService.updateOneContent(saveDTO, id); return "redirect:/content/" + id; } } ​ 이전 : 14. 게시글 삭제 로직 다음 : 16. 이미지 업로드 (프론트) https://youtu.be/M5TTsIsPhE4 224, 스프링 부트 CKEditor5 > 16. 이미지 업로드 (프론트) 이미지 업로드 원리 ​ ​ 1. CKEditor에서 이미지 업로드 2. CKEditor가 동작하는 프론트단에서 특정 서버 경로로 이미지 파일을 보냄 3. 컨트롤러가 이미지 파일을 받음 4. 서비스단으로 이미지 파일을 넘긴 후 5. 서버 로컬에 저장 6. 로컬 이미지를 S3로 백업 7. 로컬 이미지 삭제 8. S3에 저장된 이미지 주소 리턴 9. 컨트롤러에서 key:value 형태로 완료 메시지와 이미지 주소 응답 ​ 필수 플러그인 ​ CDN의 경우 포함되어 있음 ​ 다운로드 방식의 경우 : CKFinder upload adapter ​ ​ https://ckeditor.com/ckeditor-5/download/ CKEditor 5 - Download Latest Version Download a ready-to-use CKEditor 5 Build. Install, download or serve a ready-to-use rich text editor of your choice. ckeditor.com ​ CKEditor 설정 (프론트단) ​ - editor.mustache Document editor


​ 이전 : 15. 게시글 수정 로직 다음 : 17. AWS S3 생성 및 스프링 부트 연결 https://youtu.be/9qABD8mf1w8 225, 스프링 부트 CKEditor5 > 17. AWS S3 생성 및 스프링 부트 연결 AWS 버킷 생성 ​ ​ 버킷 접근 권한 ​ 읽기 : 모두 가능 쓰기 : 계정 주인만 IAM S3 접근 계정 만들기 ​ 1. 그룹 생성 2. 그룹 내부에 사용자 생성 ​ 그룹 권한의 경우 S3FullAccess 스프링 부트 변수 설정 : application.properties ​ - application.properties cloud.aws.s3.bucket=버킷이름 cloud.aws.stack.auto=false cloud.aws.region.static=ap-northeast-2 cloud.aws.credentials.access-key=IAM계정 cloud.aws.credentials.secret-key=IAM비밀번호 ​ 스프링 부트 S3 연결 Config 클래스 작성 ​ - build.gradle : 의존성 implementation 'org.springframework.cloud:spring-cloud-starter-aws:2.2.6.RELEASE' ​ - S3Config.java import com.amazonaws.auth.AWSStaticCredentialsProvider; import com.amazonaws.auth.BasicAWSCredentials; import com.amazonaws.services.s3.AmazonS3Client; import com.amazonaws.services.s3.AmazonS3ClientBuilder; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class S3Config { @Value("${cloud.aws.credentials.access-key}") private String accessKey; @Value("${cloud.aws.credentials.secret-key}") private String secretKey; @Value("${cloud.aws.region.static}") private String region; @Bean public AmazonS3Client amazonS3Client() { BasicAWSCredentials awsCredentials = new BasicAWSCredentials(accessKey, secretKey); return (AmazonS3Client) AmazonS3ClientBuilder .standard() .withRegion(region) .withCredentials(new AWSStaticCredentialsProvider(awsCredentials)) .build(); } } ​ 이전 : 16. 이미지 업로드 (프론트) 다음 : 18. 이미지 저장 (백엔드) https://youtu.be/BqTXiqK7qDo 226, 스프링 부트 CKEditor5 > 18. 이미지 저장 (백엔드) 이미지 저장 과정 ​ 1. 프론트단에서 이미지를 보내준 경로에 컨트롤러 작성 2. 컨트롤러에서 이미지 파일 받은 후 서비스단으로 전달 3. 서비스단에서 로컬 환경에 이미지 저장 4. 로컬 환경 이미지를 S3로 전송 5. S3로 부터 전송 저장 경로 받기 6. 로컬 환경 이미지 삭제 7. 저장 경로 컨트롤러단으로 전달 8. 컨트롤러 단에서 key : value 형태로 전송 경로 에디터로 전달 ​ 컨트롤러단에서 이미지 받기 ​ - 이미지 전송 경로 POST : /image/upload ​ - 컨트롤러 @Controller public class ImageController { private ImageService imageService; @Autowired public ImageController(ImageService imageService) { this.imageService = imageService; } @PostMapping("/image/upload") @ResponseBody public Map imageUpload(MultipartRequest request) throws Exception { Map responseData = new HashMap<>(); try { String s3Url = imageService.imageUpload(request); responseData.put("uploaded", true); responseData.put("url", s3Url); return responseData; } catch (IOException e) { responseData.put("uploaded", false); return responseData; } } } ​ 서비스단에서 이미지 저장 ​ @Service public class ImageService { private S3Config s3Config; @Autowired public ImageService(S3Config s3Config) { this.s3Config = s3Config; } @Value("${cloud.aws.s3.bucket}") private String bucket; private String localLocation = "로컬환경경로"; public String imageUpload(MultipartRequest request) throws IOException { MultipartFile file = request.getFile("upload"); String fileName = file.getOriginalFilename(); String ext = fileName.substring(fileName.indexOf(".")); String uuidFileName = UUID.randomUUID() + ext; String localPath = localLocation + uuidFileName; File localFile = new File(localPath); file.transferTo(localFile); s3Config.amazonS3Client().putObject(new PutObjectRequest(bucket, uuidFileName, localFile).withCannedAcl(CannedAccessControlList.PublicRead)); String s3Url = s3Config.amazonS3Client().getUrl(bucket, uuidFileName).toString(); localFile.delete(); return s3Url; } } ​ 이전 : 17. AWS S3 생성 및 스프링 부트 연결 다음 : 19. 오류 및 플러그인 https://youtu.be/IvWPLV4-8bc 227, 스프링 부트 CKEditor5 > 19. 오류 및 플러그인 게시글 저장 오류 ​ 게시글 저장 테이블의 content(내용)을 저장하는 컬럼 데이터 타입이 작게 설정되어 있을 경우 게시글 저장시 오류 발생 LONGTEXT로 설정 ​ ​ //테이블 변수 타입 확인 DESC 테이블명; //테이블 특정 컬럼 타입 변경 ALTER TABLE 테이블명 MODIFY 컬럼명 타입; //예시 ALTER TABLE 테이블명 MODIFY content LONGTEXT; ​ 에디터 높이 설정시 오류 ​ 기존 에디터의 경우 기본 높이값이 너무 낮다. ​ ​ CSS에서 클래스에 대해서 높이 설정이 가능하다. ​ - 비추천 방법 .ck-editor__editable { height: 450px; } ​ 위 방식으로하면 높이는 지정되지만 에디터 내부에 이미지나 테이블을 넣을 경우 이미지, 테이블등 여러 요소들 값이 동일한 클래스명을 가지고 있어 강제로 높이가 바뀐다. ​ - 추천 방법 .ck-editor__editable:not(.ck-editor__nested-editable) { height: 450px; } ​ 작성 후 게시글 볼때 줄바꿈 안됨 ​ html { word-break : break-all; } ​ 이미지 사이즈 변경 플러그인 ​ - CDN의 경우 없음 - 직접 다운로드 방식의 경우 ​ ​ 에디터에서 소스코드 수정 ​ - CDN의 경우 없음 - 직접 다운로드 방식의 경우 ​ ​ 이전 : 18. 이미지 저장 (백엔드) 다음 : 20. 띄어쓰기 한글 자모 분리 문제 https://youtu.be/92RoFOQX4B4 228, 스프링 부트 CKEditor5 > 20. 띄어쓰기 한글 자모 분리 문제 한글 입력시 띄어쓰기 후 자모 분리 문제 ​ CKEditor5 버전 37.x ~ 38.x (다른 버전은 테스트하지 않음)을 사용하였고 안드로이드 환경에서 에디터 사용시 띄어쓰기 후 자모 분리 문제 발생 ​ - 원하는 결과 안녕하세요 저는 개발자 유미입니다. ​ - 오류로 인한 결과 안녕하세요 ㅈㅓ는 ㄱㅐ발자 ㅇㅠ미입니다. ​ 오류의 원인 ​ 한글의 경우 초성 + 중성 + 종성 또는 초성 + 중성으로 하나의 글자를 이루기 때문에 항상 다음 글자를 통해 글자가 마무리 되었는지 확인해야 한다. ​ 이 때문에 모든 IME에는 isComposing() 메소드가 동작을하는데 띄어쓰기 이후 isComposing() 메소드가 update 상태로 동작하는 바람에 자모가 분리되는 형상이 발생한다. ​ 해결 방법 ​ CKEditor5를 다운로드 받은 후 다음 경로의 ckeditor.js 파일을 수정 /build/ckeditor.js ​ 위 경로에 접근하면 CKEditor5의 자바스크립트 소스코드를 확인할 수 있다. 이 코드 중 아래 구간에서 - 기존 코드 { if(t==="insert"){ vc(n,c,r[c]); c++ } else if(t==="update"){ Gf(i[c],r[c].data); c++ } else if(t==="equal"){ this._markDescendantTextToSync(this.domConverter.domToView(r[c])); c++ } } ​ - 수정 코드 { if(t==="insert"){ vc(n,c,r[c]); c++ } else if(t==="update"){ if(!this.isComposing){ Gf(i[c],r[c].data); } c++ } else if(t==="equal"){ this._markDescendantTextToSync(this.domConverter.domToView(r[c])); c++ } } ​ 종성이 닫히지 않은 상태인 update 상태에서 IME의 isComposing 함수가 true여도 Gf() 메소드가 동작하지 않도록 조건문을 추가하여 수정할 수 있다. ​ 버전 별 ​ - 39.x 버전에서 메소드명이 변경되었다. 테스트는 하지 않았지만 제대로 동작될 수 있음 (2023.09.26 기준) if(t==="insert"){Cc(n,c,r[c]);c++}else if(t==="update"){_m(i[c],r[c].data);c++}else if(t==="equal"){this._markDescendantTextToSync(this.domConverter.domToView(r[c]));c++} ​ 이전 : 19. 오류 및 플러그인 https://youtu.be/6yaY5GbruEk 229, JPA 표준 스펙에 의해, 상황에 따라 발생하는 1+N 문제 트러블 슈팅 시리즈입니다. JPA 1+N 문제 ​ 1. 실습 목표 2. 실습 환경 3. 1+N 발생 상황 4. Lazy, Eager 5. 연관 관계 쿼리 단일화 6. join fetch, left join fetch 7. 다중 OneToMany 문제 8. 페이지네이션 문제 ​ 코드 ​ https://github.com/xxxjjhhh/jpa_1plusN 230, JPA 1+N 문제 > 1. 실습 목표 실습 목표 ​ 자바에서 DB에 접근할 때, JPA를 자주 사용하게 됩니다. JPA는 추상화와 데이터를 객체 지향적으로 다룰 수 있다는 장점이 존재하지만, JPA 표준 스펙에 의해 상황에 따라 “1+N”이라는 문제를 접하게 됩니다. 1+N 문제는, 2개 이상의 JOIN 된 테이블에서 연관된 데이터를 조회할 때, 하나의 쿼리로 조회가 가능한 상황이지만, JPA 구현체는 1개 + N개의 쿼리로 조회하는 문제입니다. 이 문제를 해결하여 자원 소모를 줄여봅시다. ​ 필수 요건 ​ 기본적으로 “Spring Data JPA”, “JPA”에 대한 기본 지식과 연관 관계 및 Lazy, Eager 로딩을 숙지하셔야 합니다. 환경 ​ - 자바 : 스프링 부트 3 기반 - Spring Data JPA + JPA - JPA 구현부는 Hibernate - MySQL 8 ​ 예상 목차 ​ 1. OneToMany 연관 관계 프로젝트 작성 2. OneToMany : 양방향, 단방향에 따른 1+N 발생 시점 확인 3. Lazy Case 4. 해결 방법 ​ 다음 : 2. 실습 환경 https://youtu.be/ve-jybNzZHE 231, JPA 1+N 문제 > 2. 실습 환경 실습 환경 ​ - 스프링 부트 3.4.4 - Spring Data JPA - MySQL ​ 프로젝트 다운로드 ​ https://github.com/xxxjjhhh/jpa_1plusN GitHub - xxxjjhhh/jpa_1plusN: 개발자 유미 : JPA 1+N 문제 개발자 유미 : JPA 1+N 문제. Contribute to xxxjjhhh/jpa_1plusN development by creating an account on GitHub. github.com ​ 연관 관계 구조 ​ 연습용 연관 관계는 “국가” : “도시” = 1 : N 형태의 JOIN 입니다. 따라서 “korea”라는 하나의 CountryEntity에 “seoul”, “busan”과 같은 CityEntity가 연관됩니다. ​ 프로젝트 구조 ​ ​ application.properties ​ spring.application.name=1plusNtest spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver spring.datasource.url=jdbc:mysql://:3316/yummi?useSSL=false&useUnicode=true&serverTimezone=Asia/Seoul&allowPublicKeyRetrieval=true spring.datasource.username=root spring.datasource.password= spring.jpa.hibernate.ddl-auto=update spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl spring.jpa.show-sql=true ​ 데이터 넣기 ​ korea : seoul, busan, daegu france : paris usa : newyork, chicago ​ 이전 : 1. 실습 목표 다음 : 3. 1+N 발생 상황 https://youtu.be/6RpdVHOdB0A 232, JPA 1+N 문제 > 3. 1+N 발생 상황 연관 관계 데이터 확인 case ​ ​ OneToMany 연관 관계예서 데이터를 확인하는 케이스를 살펴보겠습니다. (CountryEntity : CityEntity) - One쪽 조회 - 연관된 Many 접근 안함 - 연관된 Many 접근 함 - Many쪽 조회 (주인) - 연관된 One 접근 안함 - 연관된 One 접근 함 ​ 데이터 ​ korea : seoul, busan, daegu france : paris usa : newyork, chicago ​ Case1 : One쪽 조회 ​ - One 조회 후 연관된 Many 접근 안함 단, 한 번의 쿼리 - One 조회 후 연관된 Many 접근 함 One용 쿼리 한 번 + List를 순회하며 각각의 연관된 CityEntity들을 확인할 쿼리 N번 Case2 : Many쪽 조회 (주인쪽) ​ - Many 조회 후 연관된 One 접근 안함 CityEntity 쿼리 한 번 및 mappedBy용 쿼리 한 번 (총 2번) - Many 조회 후 연관된 One 접근 함 CityEntity 쿼리 한 번 및 mappedBy용 쿼리 한 번 (총 2번) 1+N ​ 위 케이스들을 통해 확인한 결과. ​ 연관 관계의 두 Entity에 대해 두 Entity의 정보가 보고 싶은 경우 RDB SQL에서는 한 번의 구문으로 쿼리가 가능하지만, ​ JPA는 각각의 Entity를 각각 조회합니다. 주인이 되는 Many쪽에서 연관된 One을 조회하는 건, 그나마 2번의 쿼리로 큰 문제가 없지만, ​ List쪽에서 각각의 One에 대한 Many를 조회할 경우 List<>의 size 만큼 쿼리가 발생하는 것이 확인되며 size가 커질수록 문제가 IO적 문제가 발생함이 예상됩니다. ​ 위험 예시 케이스 ​ - 프로젝트별 유저목록 깃허브와 같은 프로젝트 리포지토리 List이 존재하고, 각각의 리포지토리별 유저가 Many로 JOIN된 상태에서, 전체 리포지토리 목록과 목록별 참여 인원을 확인 케이스. - 관리자 대시보드 유저별 데이터 관리자 대시보드에서 전체 유저에 List 대한 각각의 게시글, 주문목록과 같은 유저의 데이터를 확인하는 케이스. ​ 이전 : 2. 실습 환경 다음 : 4. Lazy, Eager https://youtu.be/K4a6RbLu62s 233, JPA 1+N 문제 > 4. Lazy, Eager 연관 관계 접근에 따른 쿼리 ​ JPA의 find 관련 메소드들은 해당 Entity 테이블 데이터만 가져오도록 설계되어 있습니다. 따라서 find로 찾은 특정 Entity의 연관된 다른 테이블 Entity는 접근시 무조건 추가 조회를 통해 가져옵니다. (연관 데이터를 사용할지 모르는 상황에서 가져오는 것은 자원적 소모가 있음) 의문점은 ​ 3강에서 각 case별 쿼리 개수 테스트를 수행할 때, 가져온 Entity에서 연관된 Entity에 접근하지 않는 상황에 대해 아래와 같은 의문이 있었습니다. ​ - ManyToOne : 접근하지 않아도 연관쪽 쿼리가 날라감 - OneToMany : 접근하지 않으면 연관쪽은 안날라감 이 상황에 대해 살펴보겠습니다. Lazy, Eager ​ 동일하게 접근하지 않았지만, 추가 쿼리의 발생 여부는 JPA Lazy, Eager 로딩 설정 때문입니다. - Lazy 로딩 : 연관에 접근하지 않는다면 가져오지 않음 - Eager 로딩 : 연관에 접근하지 않아도 추가 쿼리로 먼저 가져옴 JPA JOIN별 default 값 ​ - OneToOne : Eager - ManyToOne : Eager - OneToMany : Lazy ManyToOne Lazy 명시 ​ 기존 Eager가 default인 ManyToOne Lazy 설정을 해보겠습니다. - CityEntity @ManyToOne(fetch = FetchType.LAZY) private CountryEntity countryEntity; ​ 기타 ​ Lazy, Eager 설정 모두 연관에 대한 추가 쿼리를 나중에 할 지 지금 할 지 결정하는 것으로 1+N 쿼리를 1 쿼리로 대체할 수 있는 것은 아닙니다. ​ 다음 영상에서 실제 연관 데이터를 1 쿼리로 수행하도록 하는 구현에 대해 알아보겠습니다. ​ 이전 : 3. 1+N 발생 상황 다음 : 5. 연관 관계 쿼리 단일화 https://youtu.be/MR4_oVzzgy4 234, JPA 1+N 문제 > 5. 연관 관계 쿼리 단일화 JPA 쿼리 단일화 ​ JPA에서 Entity 조회 후 연관된 Entity 접근시 발생하는 추가 쿼리를 단건의 쿼리로 단일화 시키겠습니다. 단일화 방법은 여러가지가 존재하지만, 장단점이 있습니다. - JPQL @Query로 JOIN FETCH 작성 - QueryDSL로 fetchJoin() - @EntityGraph - Lazy 쪽 조회시 Batch 설정을 통한 IN절 이 중 가장 많이 사용되는 JPQL @Query 작성에 대해 알아보겠습니다. ​ JPQL ​ JPQL은 JPA에서 Entity(객체) 기반으로 SQL 쿼리를 사용할 수 있는 방법입니다. ​ Spring Data JPA 의존성에서 @Query() 어노테이션을 통해 Repository에서 JPQL을 쉽게 다룰 수 있습니다. ​ @Query("") ​ JPQL JOIN FETCH 쿼리 작성 ​ - 쿼리 작성 @Query("SELECT co FROM CountryEntity co " + "JOIN FETCH co.cityEntities ci") List findAllFetch(); ​ - 서비스단 사용 public List readCountryFetch() { return countryRepository.findAllFetch(); } ​ - 컨트롤러단 수정 @GetMapping("/read/one/child") public String readOneChild(Model model) { model.addAttribute("COUNTRYLIST", countryService.readCountryFetch()); return "readOneChild"; } ​ 테스트 ​ - 기존 One쪽 findAll → 연관 Many쪽 접근 ​ - JPQL JOIN FETCH ​ 이전 : 4. Lazy, Eager 다음 : 6. join fetch, left join fetch https://youtu.be/xiwgE-UIvdo 235, JPA 1+N 문제 > 6. join fetch, left join fetch JOIN FETCH 데이터 누락 ​ JOIN FETCH 구문 작성시 누락되는 데이터가 존재합니다. ​ OneToMany와 같은 JOIN 상황에서 One은 존재하지만, 연관된 Many가 0개인 경우입니다. 이 경우 One쪽도 함께 조회되지 않는 데이터 누락 문제가 발생합니다. - 예시 우리의 예제 케이스에서 CountryEntity데이터에 물린 CityEntity가 없는 경우 findAll (JPQL로 작성)로 찾은 List에 해당 CountryEntity가 포함되지 않음 상황 만들기 ​ 간단하게 기존 CountryEntity에 "germany" 국가 데이터를 추가하고 연관된 City는 추가하지 않겠습니다. 해결 방법 ​ - 기존 SQL 구문 @Query("SELECT co FROM CountryEntity co " + "JOIN FETCH co.cityEntities ci") List findAllFetch(); ​ - 변경 LEFT 추가 @Query("SELECT co FROM CountryEntity co " + "LEFT JOIN FETCH co.cityEntities ci") List findAllFetch(); ​ 원리 ​ - JOIN FETCH INNER JOIN으로 연관된게 있는 교집합이어야 조회 됨 - LEFT JOIN FETCH LEFT OUTER JOIN으로 부모 + 교집합이면 조회 됨 이전 : 5. 연관 관계 쿼리 단일화 다음 : 7. 다중 OneToMany 문제 https://youtu.be/guaUdNip8fw 236, JPA 1+N 문제 > 7. 다중 OneToMany 문제 DB 설계시 ​ DB 테이블 설계시 하나의 Entity에 대해 OneToMany가 2개 이상 들어갈 경우가 많습니다. - Entity 예시 @Entity @Getter @Setter public class CountryEntity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(unique = true) private String country; @OneToMany(mappedBy = "countryEntity") private List cityEntities = new ArrayList<>(); public void addCityEntity(CityEntity cityEntity) { cityEntities.add(cityEntity); cityEntity.setCountryEntity(this); } @OneToMany(mappedBy = "countryEntity") private List religionEntities = new ArrayList<>(); public void addReligionEntity(ReligionEntity religionEntity) { religionEntities.add(religionEntity); religionEntity.setCountryEntity(this); } } ​ FETCH 조회시 문제 ​ 그리고 2개 이상의 OneToMany를 FETCH 조회할 경우도 생깁니다. - JPQL @Query("SELECT co FROM CountryEntity co " + "LEFT JOIN FETCH co.cityEntities ci " + "LEFT JOIN FETCH co.religionEntities re") List findAllFetch(); ​ 이때 findAllfetch() 메소드 동작시 아래와 같은 예외가 발생합니다. ​ ​ - 문제는 JPA 구현체 중 하나인 Hibernate는 2개 이상의 OneToMany fetch를 강제로 막고 있습니다. - 이유는 CountryEntity를 기준으로 : City, Religion Entity가 각각 OneToMany로 연관되어 있고 실제 데이터는 아래와 같다고 가정하겠습니다. ​ ​ Country : 1개 City : 3개 Religion : 2개 이를 SQL로 JOIN해서 가져온 결과는 어떻게 될까요? Country를 기준으로 나머지 Religion, Country, City 데이터가 곱셈 복제가 됩니다. ​ ​ Hibernate는 가져온 이 SQL 데이터를 JAVA 객체로 변환 시키는 과정에서 중복을 제거해야 하는데, 중복을 제거하는 조건이 까다로워 이 자체를 막아둡니다. - 1개의 OneToMany fetch는 하는데? 기준인 CountryEntity를 id 기반 (hashCode 및 equals)로 처리 후 CityEntity는 중복이 있을 수 없음 하지만, OneToMany가 2개 이상인 경우 CityEntity에 중복이 있을 수 있음 (하나의 OneToMany 연관이라면 CountryEntity 중복을 제거 시키고 연관된 CityEntity는 어차피 중복이 없음, 하지만 OneToMany가 2개라면 CityEntity가 ReligionEntity 때문에 중복이 생겨 있음) (하이버네이트는 List에 대해 설계 원칙을 위반하지 못하기 때문에 List에 대해 중복 제거를 못함) ​ 해결 1 : Set ​ 권장하는 방법은 아닙니다. 기준 Entity의 OneToMany 연관 필드를 List<>가 아닌 Set<> 화 시키는 방법입니다. ​ @OneToMany(mappedBy = "countryEntity") private Set cityEntities = new HashSet<>(); @OneToMany(mappedBy = "countryEntity") private Set religionEntities = new HashSet<>(); 단점으로는 Set의 특성을 이해하면 됩니다. 1. Set은 순서 보장 불가 2. Set을 호출하며 발생하는 중복 제거 체킹 자원 발생 3. 정확한 Id기반 hashCode equals 구현 필요 추가적으로 데이터 소멸 문제가 있다고는 하지만, 제가 개인적으로 외주한 프로젝트에서는 아직 큰 문제는 없습니다. (데이터 5만 건 이상) ​ 해결 2 : 한쪽만 fetch 나머지 in절 ​ 우선 한쪽 OneToMany는 기존과 같이 fetch로 유지합니다. ​ 나머지쪽은 단순 Lazy로 두면 1+N 문제가 동일하게 발생하기 때문에 Batch 설정을 통한 IN 절 처리를 수행합니다. ​ @BatchSize(size = 250) ​ 이렇게 하면 1+N 쿼리는 아니지만 1+소수 개의 쿼리로 문제를 해결할 수 있습니다. (배치 사이즈는 250~500) ​ 이전 : 6. join fetch, left join fetch 다음 : 8. 페이지네이션 문제 https://youtu.be/MeqMdv22qSg 237, JPA 1+N 문제 > 8. 페이지네이션 문제 OneToMany fetch시 페이지네이션 ​ 대량의 데이터를 한 페이지에 로딩하기 하기 어렵기 때문에 페이지네이션을 활용하게 됩니다. - 페이지네이션 예시 (테스트용 코드) import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; Pageable pageable = PageRequest.of(0, 5); ​ - Repository에도 @Query("SELECT co FROM CountryEntity co " + "LEFT JOIN FETCH co.cityEntities ci") List findAllFetch(Pageable pageable); ​ 문제는 One쪽 Entity 기준으로 OneToMany fetch시 페이지네이션을 함께 수행하면 아래와 같은 경고가 발생합니다. WARN 1496 --- [1plusNtest] [nio-8080-exec-5] org.hibernate.orm.query : HHH90003004: firstResult/maxResults specified with collection fetch; applying in memory ​ 위 WARN 경고는 페이지네이션을 SQL : LIMIT OFFSET 절로 수행하는 것이 아니라, 스프링 측에 모든 데이터를 다 가져온 뒤 진행한다는 의미입니다. (자원 낭비) ​ fetch시 페이지네이션 문제 해결 방법 ​ 우선 OneToMany 기준으론 없습니다. @Query("")에 직접 LIMIT OFFSET 구문을 주는 방법도 불가능 합니다. (번역 불가로 지원 안함) 그래서 매번 전체 데이터를 스프링단으로 로딩 후, 스프링에서 페이지네이션 값 만큼 가져와야 합니다. ​ 해결 : batch in절 ​ 해결 방법은 join fetch를 걷어내고 batch in 절을 사용하는 방법입니다. ​ batch in 절은 1+N 개의 쿼리 중 N개의 쿼리에 대해 batch 단위로 묶어 1+소수개의 쿼리로 성능을 최적화 하는 방법입니다. ​ @BatchSize(size = 250) ​ 그럼.. ​ 갑자기 애매해졌습니다.. join fetch를 통해 1+N 문제를 해결하려 했지만, 여러 문제로 IN절을 더 많이 사용하게 되었습니다. 따라서 상황에 따라 아래 case별로 잘 사용해야 합니다. (전제는 OneToMany 상황에서 List 기준입니다.) 1. 단순하게 List 목록만 보여주고 연관된 Many 접근 안함 접근 안하기 때문에 Lazy 로딩 사용해도 무방 2. List 목록 및 각 연관 Many 접근 함 케이스가 나뉩니다. - 페이지네이션이 들어감 @BatchSize를 통한 IN절 쿼리 수행 - 다중 OneToMany 상황에서 각각의 OneToMany 데이터가 다 필요함 하나만 join fetch 나머지는 @BatchSize를 통한 IN절 쿼리 수행 또는 전체 @BatchSize를 통한 IN절 쿼리 수행 - SQL 조건으로 가져온 데이터가 다 필요한 경우 또는 List의 size가 작고 연관 접근 케이스 join fetch 사용 ​ 이전 : 7. 다중 OneToMany 문제 https://youtu.be/qVfdBHn-rsc 238, AMQP를 구현한 오픈 소스 메시지 브로커인 RabbitMQ에 대한 기초적인 설치 및 사용 방법 프로젝트입니다. ​ RabbitMQ ​ 1. 실습 목표 및 동작 원리 2. 239, RabbitMQ > 1. 실습 목표 및 동작 원리 실습 목표 ​ RabbitMQ라는 메시지 브로커 소프트웨어를 설치하고 활용하는 시리즈로 최종적으로 스프링부트 프레임워크나 파이썬 환경에서 큐에 메시지를 넣고 받아오는 작업을 수행하겠습니다. ​ 큐의 사용 이유 ​ - 비동기 메시지 처리 및 서버 과부화 방지 - 분산 및 복제 - 다양한 소프트웨어 통합 및 안정성 확보 RabbitMQ vs Kafka ​ 가장 고민되는 부분입니다. ​ 다음 : 2. 240, 토이 프로젝트나 실무에 처음 투입된 스프링 개발자를 위한 깃허브 인텔리제이 프로젝트 활용 방법 시리즈입니다. ​ GitHub IntelliJ 실무 가이드 ​ 1. 리포지토리 생성 및 init 2. 기능 개발 : 브랜치, 커밋 3. ​ 241, GitHub IntelliJ 실무 가이드 > 1. 리포지토리 생성 및 init 팀장 입장에서 ​ 프로젝트를 주도하는 팀장 입장에서, 코드 공유를 위해 프로젝트를 진행할 리포지토리를 생성해야 합니다. 리포지토리 생성 ​ ​ 웬만하면 README file은 추가하면 안됩니다. ​ (스프링 프로젝트를 리포지토리에 처음 push 하면 README 때문에 push 충돌이 발생합니다.) ​ collaborators 추가 ​ 함께 프로젝트를 진행할 팀원들에게 리포지토리 접근 권한을 부여합니다. ​ ​ 이슈(티켓) 종류 생성 ​ 프로젝트를 진행하면 “새로운 기능 개발”, “버그 수정”, “리팩터링”, “공지” 등등 다양한 이슈 사항이 존재합니다. 우리 프로젝트에서 발생할 이슈들을 전체적으로 카테고리화 시킬 이슈 목록을 만들겠습니다. ​ ​ ​ 스프링 프로젝트 업로드 ​ ​ ​ ​ 다음 : 2. 기능 개발 : 브치, 커밋 242, GitHub IntelliJ 실무 가이드 > 2. 기능 개발 : 브랜치, 커밋 ​ ​ ​ ​ 이전 : 1. 리포지토리 생성 및 init 다음 : 3. 243, 스프링 프레임워크를 활용한 MSA ​ 스프링 클라우드 MSA ​ 1. MSA란 2. 스프링에서 MSA 3. Config 깃허브 리포지토리 4. Config Server 구축 5. Config 클라이언트 설정 기타. JetBrains Space Config 리포지토리 6. Eureka 서버 구축 7. Eureka 클라이언트 설정 8. 스프링 클라우드 게이트웨이 9. 게이트웨이 라우팅 설정 10. 게이트웨이 Eureka 로드밸런싱 11. 게이트웨이 라우팅 추가 (actuator) 12. 게이트웨이 글로벌 필터 13. 게이트웨이 지역 필터 244, 스프링 클라우드 MSA > 1. MSA란 MSA : Micro Service Architecture ​ MSA는 마이크로 서비스 아키텍처의 약자로 특정 서비스를 구축하는 방식을 의미한다. ​ 서비스 구축 방법 ​ - 모놀로식 과거 부터 현재까지 주로 이용되는 서비스 구축 방식으로 하나의 프로젝트에 모든 비즈니스 로직과 설정 데이터들을 넣어 개발하는 방식이다. - MSA 모놀리식 서비스에서 각각의 비즈니스 로직을 분리하여 개별 프로젝트로 생성한 뒤 가장 앞단에서 API Gateway와 같은 분배기를 통해 각 서비스 서버에 요청을 분산하여 관리한다. 모놀리식과 MSA ​ 서비스가 대형화되고 클라우드 서비스가 활성화된 요즘 모놀로식 방식에서 MSA 방식으로 구조 변경을 진행한다. ​ MSA 장단점 ​ - 장점 1. 서비스별 스케일링 가능 2. 서비스별 다른 프레임워크 사용 가능 3. 하나의 서비스가 off 되더라도 나머지 동작 가능 4. 부분적으로 로직 업데이트 가능 - 단점 1. 초기 구성의 난이도 2. 시스템이 돌아가지만 특정 서비스가 off되면 재기능을 못할 수 있음 3. 서버간 호출 비용 4. 분산 관리 ​ MSA의 여러 요소 ​ - 로직 - 게이트웨이 - 모니터링 서버 - 변수관리 서버 ​ https://spring.io/cloud Cloud Level up your Java code and explore what Spring can do for you. spring.io ​ 스프링 프레임워크에서의 MSA ​ 스프링 프레임워크도 MSA를 지원하기 위해 MSA 관련 의존성들을 제공한다. 추천 ​ Vingle의 AWS 기반 서버리스 마이크로 서비스 구현 사례 - 이상현 TechnicalLeader (빙글) 바로가기 ​ ​ 다음 : 2. 스프링에서 MSA https://youtu.be/O1un1Nf810Y 245, 스프링 클라우드 MSA > 2. 스프링에서 MSA 스프링에서 MSA 모식도 ​ 대중적인 스프링 클라우드 MSA 구성 환경 ​ ​ 스프링 부트 ​ 비지니스 로직 처리를 담당하기 위한 어플리케이션 서버 즉 특정 경로에 대한 컨트롤러를 통해 요청 처리를 진행한다. Spring Cloud Gateway : SCG ​ URL 주소에 대해서 아래 세부 경로에 따라 각각의 스프링 부트 어플리케이션에 분배하는 분배기 역할을 수행 Spring Cloud Eureka Server ​ 모니터링 서버로 Eureka Client 설정을 해둔 서버를 Eureka Server에 띄워 줌 모니터링 기능과 함께 추가적으로 Spring Cloud Gateway에 목록을 전달하여 Gateway가 로드밸런싱 대상을 설정하도록 작업 Spring Cloud Eureka Client ​ Eureka Server에 등록되는 요소로 스프링 부트 어플리케이션과 같은 여러 스프링 프레임워크 서버에 설정이 가능하다. Spring Config Server ​ 변수 값들을 제공하는 서버로 특정 경로로 접근하면 미리 사전에 설정해둔 변수 값들을 제공 받을 수 있다. MSA를 구축하면 각각의 스프링 부트 어플리케이션에 application.properties에 값을 명시하는 것이 아닌 config server로 부터 데이터를 받아서 사용한다. Config Repository ​ Config Server는 단순하게 데이터를 전달하는 매개체로 실제 데이터는 Config Server 뒷단에 깃허브 리포지토리와 같은 저장소를 물려서 사용한다. Spring Config Client ​ Config Server로 부터 변수 데이터를 받기 위한 Client 서버 설정 ​ 이전 : 1. MSA란 다음 : 3. Config 깃허브 리포지토리 https://youtu.be/VoonWkCJxcQ 246, 스프링 클라우드 MSA > 3. Config 깃허브 리포지토리 Config 저장소의 종류 ​ Config Server는 데이터를 전달하는 매개체 역할만 수행하고 실제 설정 정보를 담을 영속성의 경우 DB, 파일, Git Service를 사용한다. Config 영속성의 종류 - Git Service - RDB - Document NoSQL - Redis - File - Vault - 등등.. 여러 영속성 도구 중 Git Service를 가장 많이 사용한다. 깃허브 리포지토리 생성 ​ 리포지토리는 비공개로 생성 (개인 계정, Organization 모두 가능) 설정 파일 생성 ​ 생성한 비공개 리포지토리 내부에 Config Server가 읽어갈 설정 파일을 생성하자. 이때 파일 명의 경우 아래와 같은 규칙이 필수적이다. 이름-환경.properties 이름-환경.yml ​ 파일명은 대시(-)로 되어 있는 구분자를 필수로 넣어야 한다. 이름은 사용자가 식별할 수 있는 이름을 사용하고 환경은 dev, prod 와 같은 특정한 환경을 명시하면 된다. ​ 리포지토리 외부 접속을 위한 비대칭 키 생성 ​ 리포지토리를 외부에서 접속할 수 있도록 비대칭 키를 생성하며 public키를 깃허브 리포지토리에 등록해야 한다. 이때 쉘 환경에서 ssh-keygen 명령어를 통해 비대칭키를 생성해야 한다. - 맥 환경의 경우 터미널 - 윈도우의 경우 git bash ​ #!/bin/bash ssh-keygen -m PEM -t rsa -b 4096 -C "코멘트(계정명 넣어도 됨)" 생성이 완료되면 /사용자/.ssh 경로에 생성 됨 cd ~/.ssh ​ ​ 생성된 비대칭 키 중 public 키 내용을 복사하여 깃허브 리포지토리에 등록 ​ Public 키 등록 ​ 생성한 리포지토리 - Settings - Depoly keys - Add Depoly key ​ ​ 이전 : 2. 스프링에서 MSA 다음 : 4. Config Server 구축 https://youtu.be/2EVLFqleV7w 247, 스프링 클라우드 MSA > 4. Config Server 구축 Config 저장소 주소와 접속 private 키 준비 ​ - 리포지토리 주소 : SSH ​ - 비대칭키 중 private 키 내용 가져오기 ​ cat 키이름 ​ 프로젝트 생성과 의존성 추가 ​ - 필수 의존성 - Config Server - Spring Security ​ Main 클래스 어노테이션 등록 ​ @EnableConfigServer ​ Config 저장소 연결 ​ application.properties 파일을 통해 Config 저장소를 연결한다. ​ - application.properties server.port=9000 spring.cloud.config.server.git.uri=주소 spring.cloud.config.server.git.ignoreLocalSshSettings=true spring.cloud.config.server.git.private-key=비밀키내용 ​ Config 서버 시큐리티 설정 ​ 기본적으로 Config Client와 Config Server간 통신시 내부망을 사용하지만 추가적인 보안을 위해 HttpBasic 보안 설정을 권장한다. 따라서 Security Config 설정을 통해 모든 경로에 대해서 HttpBasic 보안 설정을 진행한다. - Security Config 클래스 생성 @Configuration @EnableWebSecurity public class SecurityConfig { @Bean public BCryptPasswordEncoder bCryptPasswordEncoder() { return new BCryptPasswordEncoder(); } @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http .csrf((auth) -> auth.disable()); http .authorizeHttpRequests((auth) -> auth.anyRequest().authenticated()); http .httpBasic(Customizer.withDefaults()); return http.build(); } @Bean public UserDetailsService userDetailsService() { UserDetails user1 = User.builder() .username("아이디") .password(bCryptPasswordEncoder().encode("비밀번호")) .roles("ADMIN") .build(); return new InMemoryUserDetailsManager(user1); } } ​ 접근 주소 ​ 설정 정보 데이터를 얻기 위해 Config Client가 Config Server에 접근하는 주소는 아래와 같다. ​ http://ip:port/저장소이름/저장소환경 ​ IP와 포트는 Config Server의 값을 입력해주지만 저장소이름과 저장소환경 경로는 Config Repository에 해당하는 깃허브 리포지토리 내부 파일 명을 넣어야 한다. 이때 파일명에 대한 주소 변환은 아래와 같다. ​ 이름-환경.properties 이름-환경.yml /이름/환경 ​ 이전 : 3. Config 깃허브 리포지토리 다음 : 5. Config 클라이언트 설정 https://youtu.be/qeQPBImEGec 248, 스프링 클라우드 MSA > 5. Config 클라이언트 설정 Config 클라이언트란 ​ 단순하게 서비스 로직을 수행하는 스프링 부트 어플리케이션이다. 스프링 부트 어플리케이션에 Config Client 설정을 통해 Config Server에서 보내주는 데이터를 받을 수 있다. 프로젝트에 클라이언트 의존성 추가 ​ - 필수 의존성 - Config Client - build.gradle ext { set('springCloudVersion', "2022.0.4") } dependencies { implementation 'org.springframework.cloud:spring-cloud-starter-config' } dependencyManagement { imports { mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}" } } ​ Config 서버와 연결 ​ application.properties 파일을 통해 Config 서버에 연결 가능 ​ spring.application.name=이름 spring.profiles.active=환경 spring.config.import=optional:configserver:http://아이디:비밀번호@아이피:포트 서버로 부터 데이터 받기 ​ - application.properties server.port=${server.port} ​ 이전 : 4. Config Server 구축 다음 : 기타. JetBrains Space Config 리포지토리 https://youtu.be/EQ31GAYxqSk 249, 스프링 클라우드 MSA > 기타. JetBrains Space Config 리포지토리 JetBrains Space ​ JetBrains Space 바로가기 JetBrains사가 제공하는 Space는 Git 서비스, CI/CD, 온라인 IDE, 이슈 트래킹, 채팅등을 지원하는 Developmtent 플랫폼이다. Space Repository를 Config 서버 저장소로 사용하는 방법 ​ 기존 GitHub Repository를 Config 서버 저장소로 사용하는 방법 : 3. Config 깃허브 리포지토리 바로가기 Space에도 Repository가 존재하는데 이 Repository를 Config 저장소로 사용할 수 있다. 연결 방법은 SSH와 비대칭키가 아닌, HTTPS와 Space의 계정 아이디, 비밀번호를 통해 연결을 진행할 수 있다. 따라서 스프링 Config 서버의 application.properteis 설정은 아래와 같이 진행하면 된다. ​ spring.cloud.config.server.git.uri=리포지토리HTTPS주소 spring.cloud.config.server.git.username=아이디 spring.cloud.config.server.git.password=비밀번호 ​ 이전 : 5. Config 클라이언트 설정 다음 : 6. Eureka 서버 구축 250, 스프링 클라우드 MSA > 6. Eureka 서버 구축 Eureka 서버의 역할 ​ Eureka 서버는 단순하게 MSA를 구성하는 마이크로 서비스들을 모니터링하는 감시자 서버의 역할을 한다고 볼 수 있지만. 깊게 보면 현재 존재하는 마이크로 서비스들을 Gateway에게 알려주어 시간과 부하에 따라 유동적으로 스케일 아웃되는 서버들을 모두 가용할 수 있도록 하는 역할을 수행한다. 따라서 Eureka 서버는 가동되는 서버를 확인 후 Gateway에게 그 목록을 알려주는 역할을 수행한다. 프로젝트 생성과 의존성 추가 ​ - 필수 의존성 - Eureka Server - Spring Security Main 클래스 어노테이션 등록 ​ @SpringBootApplication @EnableEurekaServer public class EurekaServerApplication { public static void main(String[] args) { SpringApplication.run(EurekaServerApplication.class, args); } } ​ Eureka 서버 설정 ​ application.properties 또느 application.yml 파일에 설정을 통해 Eureka 서버 생성을 진행할 수 있다. server.port=8761 eureka.client.register-with-eureka=false eureka.client.fetch-registry=false ​ 시큐리티 설정 ​ Eureka 서버는 내부망에서만 존재해야 된다. 하지만 외부망에 구축하거나 내부망에서도 보안을 중요시 해야하기 때문에 스프링 시큐리티 설정을 진행한다. ​ 시큐리티는 httpBasic 방식 코드를 작성하면 된다. ​ @Configuration @EnableWebSecurity public class SecurityConfig { @Bean public BCryptPasswordEncoder bCryptPasswordEncoder() { return new BCryptPasswordEncoder(); } @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http .csrf((auth) -> auth.disable()); http .authorizeHttpRequests((auth) -> auth.anyRequest().authenticated()); http .httpBasic(Customizer.withDefaults()); return http.build(); } @Bean public UserDetailsService userDetailsService() { UserDetails user1 = User.builder() .username("아이디") .password(bCryptPasswordEncoder().encode("비밀번호")) .roles("ADMIN") .build(); return new InMemoryUserDetailsManager(user1); } } 이전 : 기타. JetBrains Space Config 리포지토리 다음 : 7. Eureka 클라이언트 설정 https://youtu.be/OXDwOYxKvWA 251, 스프링 클라우드 MSA > 7. Eureka 클라이언트 설정 Eureka 클라이언트란 ​ MSA를 구성하는 요소들 중 Eureka 서버에서 모니터링 및 관리를 원하는 요소를 Eureka 클라이언트 설정을 진행해서 등록할 수 있다. Eureka 클라이언트 설정을 위한 의존성 추가 ​ - 필수 의존성 - Eureka Discovery Client - build.gradle ext { set('springCloudVersion', "2022.0.4") } dependencies { implementation 'org.springframework.cloud:spring-cloud-starter-netflix-eureka-client' } dependencyManagement { imports { mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}" } } ​ 어노테이션 등록 ​ 스프링 부트 메인 클래스에 Eureka 클라이언트로 동작하기 위한 어노테이션을 등록해야 한다. ​ @EnableDiscoveryClient Eureka 서버와 연결 ​ application.properties 변수 설정을 통해 Eureka 서버에 등록할 수 있다. ​ server.port=8080 spring.application.name=ms1 eureka.client.register-with-eureka=true #유레카 서버에 등록할지 여부 eureka.client.fetch-registry=true #유레카 서버의 정보를 가져올지 여부 eureka.client.service-url.defaultZone=http://아이디:비밀번호@아이피:8761/eureka #유레카 서버 주소 이전 : 6. Eurek 서버 구축 다음 : 8. 스프링 클라우드 게이트웨이 https://youtu.be/h1c3Rqt26kQ 252, 스프링 클라우드 MSA > 8. 스프링 클라우드 게이트웨이 https://spring.io/projects/spring-cloud-gateway Spring Cloud Gateway Level up your Java code and explore what Spring can do for you. spring.io Spring Cloud Gateway란? ​ 스프링 클라우드 게이트웨이는 MSA 가장 앞단에서 클라이언트들로 부터 오는 요청을 받은 후 경로와 조건에 알맞은 마이크로서비스 로직에 요청을 전달하는 게이트웨이이다. 게이트웨이는 개념적으로는 아주 단순하지만 가장 앞단에서 무중지 상태로 모든 요청을 받아야하기 때문에 설정하기에 까다롭다. Spring Cloud Gateway의 특성 ​ 기존에 제작했던 스프링 부트, Eureka, Config와 같은 서비스들을 블로킹 기반으로 모두 톰캣 엔진을 사용했다. ​ 하지만 게이트 웨이의 경우 비즈니스 로직 처리 보단 단순하게 지나가는 통로 즉, I/O 처리를 중점적으로 진행하기 때문에 논 블로킹 방식으로 동작하는 WebFlux와 네티엔진을 사용한다. WebFlux는 기존에 스프링 부트에서 사용했던 JPA와 같은 블로킹 방식의 의존성들을 모두 사용하지 못하기 때문에 구현에 앞서 많은 학습이 필요하다. 프로젝트 생성과 의존성 추가 ​ - 필수 의존성 - Gateway 게이트 웨이 설정 방식 ​ - 설정 파일 방식 - application.properties - application.yml - 클래스 방식 이전 : 7. Eureka 클라이언트 설정 다음 : 9. 게이트웨이 라우팅 설정 https://youtu.be/AoPuwW2uz5s 253, 스프링 클라우드 MSA > 9. 게이트웨이 라우팅 설정 application.properties를 통한 경로 설정 ​ server.port=8080 spring.cloud.gateway.routes[0].id=ms1 spring.cloud.gateway.routes[0].predicates[0].name=Path spring.cloud.gateway.routes[0].predicates[0].args.pattern=/ms1/** spring.cloud.gateway.routes[0].uri=http://localhost:8081 spring.cloud.gateway.routes[1].id=ms2 spring.cloud.gateway.routes[1].predicates[0].name=Path spring.cloud.gateway.routes[1].predicates[0].args.pattern=/ms2/** spring.cloud.gateway.routes[1].uri=http://localhost:8082 ​ application.yml를 통한 경로 설정 ​ server: port: 8080 spring: cloud: gateway: routes: - id: ms1 uri: http://localhost:8081 predicates: - Path=/ms1/** - id: ms2 uri: http://localhost:8082 predicates: - Path=/ms2/** ​ Config 클래스를 활용한 경로 설정 ​ @Configuration public class RouteConfig { @Bean public RouteLocator ms1Route(RouteLocatorBuilder builder) { return builder.routes() .route("ms1", r -> r.path("/ms1/**") .uri("http://localhost:8081")) .route("ms2", r -> r.path("/ms2/**") .uri("http://localhost:8082")) .build(); } } ​ 이전 : 8. 스프링 클라우드 게이트웨이 다음 : 10. 게이트웨이 Eureka 로드밸런싱 https://youtu.be/MAy3QTUS5VM 254, 스프링 클라우드 MSA > 10. 게이트웨이 Eureka 로드밸런싱 게이트웨이와 Eureka 서버 연동 ​ Eureka 서버는 각각의 비즈니스 로직 처리를 담당하는 스프링 부트 어플리케이션 목록들을 가지고 있다. ​ MSA를 구성하는 요소는 자동으로 오토 스케일링되기 때문에 새로 생긴 서버의 IP를 게이트웨이가 알지 못한다. 따라서 Eureka 서버가 해당 목록들을 관리하며 Gateway에게 전달한다. ​ 스프링 클라우드 게이트웨이 Eureka 클라이언트 설정 ​ - build.gradle ext { set('springCloudVersion', "2022.0.4") } dependencies { implementation 'org.springframework.cloud:spring-cloud-starter-netflix-eureka-client' } dependencyManagement { imports { mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}" } } ​ - application.properties 설정​ eureka.client.register-with-eureka=true eureka.client.fetch-registry=true eureka.client.service-url.defaultZone=http://아이디:비밀번호@아이피:8761/eureka ​ 게이트웨이 라우팅 유레카 로드 밸런싱 - application.properties spring.cloud.gateway.routes[0].id=ms1 spring.cloud.gateway.routes[0].predicates[0].name=Path spring.cloud.gateway.routes[0].predicates[0].args.pattern=/ms1/** spring.cloud.gateway.routes[0].uri=lb://MS1 ​ 이전 : 9. 게이트웨이 라우팅 설정 다음 : 11. 게이트웨이 라우팅 추가 (actuator) https://youtu.be/bL7bakWi6Vg 255, 스프링 클라우드 MSA > 11. 게이트웨이 라우팅 추가 (actuator) 게이트웨이의 특성 ​ 스프링 클라우드 게이트웨이는 퍼블릭 엔드포인트에서 게이트웨이 역할을 수행하기 때문에 서비스를 시작한 후 항상 가동 상태여야 한다. 라우팅의 추가와 삭제 ​ 항상 가동 상태로 유지되어야 하는 게이트웨이 특성상 서버 스크립트를 중지 후 코드를 수정하고 재배포하면 서비스의 실시간성을 보장하지 못한다. 스프링 클라우드 게이트웨이의 경우 가동 중 새로운 비즈니스 로직(경로)이 추가될 경우 해당 주소에 대한 라우팅을 즉시 추가하고 삭제할 수 있는 여러 기능을 제공한다. Actuator ​ Actuator는 스프링 어플리케이션의 기능을 엔드 포인트로 제공하는 의존성이다. 이 Actuator를 활용하여 가동중인 스프링 클라우드 게이트웨이에 새로운 라우팅을 추가하고 삭제할 수 있다. 프로젝트 생성과 의존성 추가 ​ - 필수 의존성 - Gateway - Spring Boot Actuator Actuator 설정 ​ - application.properties management.endpoint.gateway.enabled=true management.endpoints.web.exposure.include=gateway ​ 라우팅 명령어 ​ - 존재하는 라우팅 확인 GET : /actuator/gateway/routes ​ - 라우터 추가 POST Body에 JSON 타입으로 데이터를 추가해야 한다. ​ - 리프래시 POST : /actuator/gateway/refresh ​ - 라우터 제거 DELETE : /actuator/gateway/routes/{id} ​ - 특정 라우터 확인 GET : /actuator/gateway/routes/{id} ​ - 글로벌 필터 목록 GET : /actuator/gateway/globalfilters ​ - 특정 라우터 필터 목록 GET : /actuator/gateway/routefilters/{id} ​ 라우팅 추가 실습 ​ - 현재 라우팅 목록 확인 GET : /actuator/gateway/routes ​ - 라우팅 추가 POST : /actuator/gateway/routes/{이름} 라우팅 JSON Body { "predicate": "Paths: [/ms1/**]", "filters": [], "uri": "http://localhost:8081", "order": 0 } ​ - 추가 후 refresh POST : /actuator/gateway/refresh ​ 이전 : 10. 게이트웨이 Eureka 로드밸런싱 다음 : 12. 게이트웨이 글로벌 필터 https://youtu.be/G2D3m8qhNiI 256, 스프링 클라우드 MSA > 12. 게이트웨이 글로벌 필터 글로벌 필터 ​ 스프링 클라우드 게이트웨이에서 글로벌 필터는 모든 라우팅에 대해서 적용되는 필터이다. 따라서 필터만 구현하면 특별한 설정 없이 적용된다. 클라이언트의 요청은 필터 → 마이크로서비스 → 필터 형태로 이동되며 같은 필터라도 마이크로서비스를 접근하기 이전이면 pre, 이후면 post라고 명명한다. 각각의 필터는 Order 값을 가질 수 있으며 pre 필터의 경우 Order 값이 작을수록 빠르게 동작하며, post 필터의 경우 Order 값이 작을수록 늦게 동작한다. ​ 글로벌 필터 작성 ​ package com.example.scg.component; import org.springframework.cloud.gateway.filter.GatewayFilterChain; import org.springframework.cloud.gateway.filter.GlobalFilter; import org.springframework.core.Ordered; import org.springframework.stereotype.Component; import org.springframework.web.server.ServerWebExchange; import reactor.core.publisher.Mono; @Component public class G1Filter implements GlobalFilter, Ordered { @Override public Mono filter(ServerWebExchange exchange, GatewayFilterChain chain) { System.out.println("pre global filter order -1"); return chain.filter(exchange) .then(Mono.fromRunnable(() -> { System.out.println("post global filter order -1"); })); } @Override public int getOrder() { return -1; } } ​ Order 설정시 ​ 각각의 마이크로서비스에 요청을 전달하는 라우팅 테이블이 Order 0으로 설정된 경우가 많기 때문에 필터의 경우 음수 설정이 지향된다. ​ Baeldung Spring Cloud Gateway 커스텀 필터 참조 바로가기 Writing Custom Spring Cloud Gateway Filters | Baeldung Learn how to write custom Spring Cloud Gateway filters. www.baeldung.com 이전 : 11. 게이트웨이 라우팅 추가 (actuator) 다음 : 13. 게이트웨이 지역 필터 https://youtu.be/TgbUGQ-jO2I 257, 스프링 클라우드 MSA > 13. 게이트웨이 지역 필터 지역 필터 ​ 스프링 클라우드 게이트웨이에서 지역 필터는 특정 마이크로서비스 라우팅에 대해서만 동작을 진행하는 필터이다. ​ 프로젝트 필수 의존성 ​ - Gateway - Lombok 지역 필터 작성 ​ package com.example.scg.component; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import org.springframework.cloud.gateway.filter.GatewayFilter; import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory; import org.springframework.stereotype.Component; import reactor.core.publisher.Mono; @Component public class L1Filter extends AbstractGatewayFilterFactory { public L1Filter() { super(Config.class); } @Override public GatewayFilter apply(Config config) { return (exchange, chain) -> { if (config.isPre()) { System.out.println("pre local filter 1"); } return chain.filter(exchange) .then(Mono.fromRunnable(() -> { if (config.isPost()) { System.out.println("post local filter 1"); } })); }; } @NoArgsConstructor @AllArgsConstructor @Data public static class Config { private boolean pre; private boolean post; } } ​ 특정 라우팅에 지역 필터 등록 ​ - application.properties spring.cloud.gateway.routes[0].filters[0].name=L1Filter spring.cloud.gateway.routes[0].filters[0].args.pre=true spring.cloud.gateway.routes[0].filters[0].args.post=true ​ - appliction.yml server: port: 8080 spring: cloud: gateway: routes: - id: ms1 uri: http://localhost:8081 predicates: - Path=/ms1/** filters: - name: L1Filter args: pre: true post: true - id: ms2 uri: http://localhost:8082 predicates: - Path=/ms2/** ​ - config 클래스 @Configuration public class RouteConfig { @Bean public RouteLocator ms1Route(RouteLocatorBuilder builder) { return builder.routes() .route("ms1", r -> r.path("/ms1/**") .filters(f -> f.filter(L1Filter.apply(new L1Filter.Config(true, true)))) .uri("http://localhost:8081") ) .route("ms2", r -> r.path("/ms2/**") .uri("http://localhost:8082") ) .build(); } } ​ 이전 : 12. 게이트웨이 글로벌 필터 https://youtu.be/Tg5_6XW61sQ 258, OAuth2 프로토콜을 통해 제 3자 플랫폼에게 우리 서비스의 자격 증명을 공유하지 않고 리소스에 접근할 수 있는 자격을 부여하는 인가 서버를 구축하는 프로젝트입니다. 앞서 네이버와 구글이 제공하는 OAuth2 규격에 맞춰 클라이언트가 되어 보았지만, 이번엔 그 서비스를 제공하는 “스프링 OAuth2 인가 서버” + “스프링 OAuth2 리소스 서버”에 대해 다뤄 보려고 합니다. ​ 스프링 OAuth2 인가 서버 ​ 1. 실습 목표 및 간단 동작 원리 2. 프로젝트 생성 및 의존성 추가 3. 기본 로그인 구성 4. 인가 서버 Bean 등록 5. Register 등록부 6. Register 사용부 7. Authorization 과정 저장 8. 코드 발급부 9. 토큰 발급부 10. 시연 ​ 코드 ​ https://github.com/xxxjjhhh/spring_oauth2_authorization_server GitHub - xxxjjhhh/spring_oauth2_authorization_server: 개발자 유미 : 스프링 OAuth2 인가 서버 개발자 유미 : 스프링 OAuth2 인가 서버. Contribute to xxxjjhhh/spring_oauth2_authorization_server development by creating an account on GitHub. github.com 기타 ​ applyDefaultSecurity deprecated 대처 내부 구조 ​ 11. 체인 구조 ​ 259, 스프링 OAuth2 인가 서버 > applyDefaultSecurity deprecated 대처 감사합니다. ​ ​ deprecated 제보 감사드립니다. ​ deprecated ​ “OAuth2 Authorization Server” 의존성 버전이 1.4.1로 올라감에 따라 기존 메소드 applyDefaultSecurity가 deprecated 되었습니다. 따라서 우리 “스프링 OAuth2 인가 서버” 시리즈 4강 인가 서버 Bean 등록 부분에서 구현 error가 발생합니다. ​ ​ 해결 방법 ​ - 기존 코드 @Bean @Order(Ordered.HIGHEST_PRECEDENCE) public SecurityFilterChain authorizationServer(HttpSecurity http) throws Exception { OAuth2AuthorizationServerConfiguration.applyDefaultSecurity(http); http .getConfigurer(OAuth2AuthorizationServerConfigurer.class) .oidc(withDefaults()); http .exceptionHandling((exceptions) -> exceptions .defaultAuthenticationEntryPointFor( new LoginUrlAuthenticationEntryPoint("/login"), new MediaTypeRequestMatcher(MediaType.TEXT_HTML) ) ); return http.build(); } ​ - 대체 코드 import org.springframework.security.oauth2.server.authorization.config.annotation.web.configurers.OAuth2AuthorizationServerConfigurer; @Bean @Order(Ordered.HIGHEST_PRECEDENCE) public SecurityFilterChain authorizationServer(HttpSecurity http) throws Exception { OAuth2AuthorizationServerConfigurer authorizationServerConfigurer = OAuth2AuthorizationServerConfigurer.authorizationServer().oidc(Customizer.withDefaults()); http .securityMatcher(authorizationServerConfigurer.getEndpointsMatcher()) .with(authorizationServerConfigurer, Customizer.withDefaults()) .authorizeHttpRequests((authorize) -> authorize.anyRequest().authenticated()) .exceptionHandling((exceptions) -> exceptions.defaultAuthenticationEntryPointFor( new LoginUrlAuthenticationEntryPoint("/login"), new MediaTypeRequestMatcher(MediaType.TEXT_HTML))); return http.build(); } ​ https://docs.spring.io/spring-authorization-server/reference/configuration-model.html Configuration Model :: Spring Authorization Server Spring Authorization Server / Configuration Model Configuration Model # Default configuration OAuth2AuthorizationServerConfiguration is a @Configuration that provides the minimal default configuration for an OAuth2 authorization server. OAuth2AuthorizationServerConfiguration uses OAuth2Authorization... docs.spring.io ​ https://youtu.be/Od_0cBkGwKE 260, 스프링 OAuth2 인가 서버 > 11. 체인 구조 구조 ​ OAuth2 인가 서버는 SecurityConfig 설정에 따라 2개의 SecurityFilterChain이 등록됩니다. - 인가 서버용 시큐리티 필터 체인 @Bean @Order(Ordered.HIGHEST_PRECEDENCE) public SecurityFilterChain authorizationServer(HttpSecurity http) throws Exception {} ​ 이 중 인가 서버용 SecurityFilterChain의 경우 OAuth2AuthorizationConfigurer이 가지고 있는 getEndpointsMatcher()에 따라 oauth2용 엔드포인트에만 활성화 됩니다. ​ ​ ​ “OAuth2 인가 서버용”, “자체 로그인용”을 분리하는 이유는 2개의 성격이 “OAuth2 인가를 위한 외부 API 제공”과 “자체 인증/인가”로 다르기 때문입니다. (각기 다른 인증 API로 예외 및 인터페이스를 달리 처리해야 되기 때문) OAuth2 인가 서버 SecurityFilterChain ​ DelegatingFilterProxy에 등록되어 있는 인가 서버용 SecurityFilterChain을 확인하겠습니다. ​ ​ 스프링 시큐리티 내부 구조 ​ https://www.youtube.com/playlist?list=PLJkjrxxiBSFCFM0pjDwm6F98veieD0MER 스프링 시큐리티 내부 구조 스프링 시큐리티 내부 동작 원리와 구조를 학습하는 시리즈입니다. www.youtube.com ​ https://youtu.be/UCIFv0w3bag 261, 스프링 OAuth2 인가 서버 > 1. 실습 목표 및 간단 동작 원리 실습 목표 ​ OAuth2 Authorization 서버와 스프링 시큐리티 6 프레임워크를 활용하여 자격 증명 과정을 공유하지 않고도 제 3자 플랫폼이 우리의 리소스에 접근할 수 있는 OAuth2 인가 서버를 구축하는 것이 목표입니다. OAuth2 방식은 Code Grant 방식입니다. 구현 ​ 이번 시리즈 : OAuth2 인가 서버 (네이버나 구글의 OAuth2 로그인을 제공하는 것과 동일한 개념) ​ 다음 시리즈 : OAuth2 리소스 서버 (위에서 인가 JWT를 발급 받은 후 유저와 같은 데이터를 받는 부분) ​ 다음 시리즈 : OAuth2 클라이언트를 통해 우리가 구현한 위 서버에 연결 (스프링 OAuth2 클라이언트 세션 시리즈를 통해 우리가 직접 만든 OAuth2 서버에 사용 신청) OAuth2 객체간 상호 작용 ​ OAuth2 인가 서버, OAuth2 리소스 서버, OAuth2 클라이언트 간의 상호 작용 ​ ​ OAuth2 인가 서버 동작 원리 ​ 기본적으로 “스프링 시큐리티 세션”과 함께 맞물려 동작하기 때문에 “스프링 시큐리티” 시리즈의 이해도가 필요합니다. ​ ​ (전반적인 동작 원리를 이해하기 위한 모식도로, 정확한 내부 구조는 아닙니다.) ​ 버전 및 의존성 ​ - 스프링 부트 : 3.3.3 - 스프링 Authorization Server : 1.3.2 - 스프링 시큐리티 : 6.3.3 - 스프링 Data JPA - MySQL Driver - 스프링 JDBC API - Lombok - Mustache ​ 예상 목차 ​ 1. 프로젝트 생성 2. 세션 기반 스프링 시큐리티 작성 : UserEntity 3. OAuth2 Authorization Server Config 작성 4. OAuth2 사용자 등록을 위한 로직 작성 5. AuthorizationEntity 작성 6. 테스트 7. 로직 설명 ​ 기타 ​ - 인가 서버는 다중 SecurityFilterChain을 사용하기 때문에 “스프링 시큐리티 내부 구조” 시리즈를 미리 시청하신 뒤 대략적인 내부 로직을 확인 부탁드립니다. - “스프링 OAuth2 클라이언트 세션/JWT” 서비스를 구성하며 네이버와 구글 OAuth2 신청을 했을때 네이버 및 구글은 어떤 과정으로 그 서비스를 제공 했을까를 생각하시면 좋을거 같습니다. - 스프링 인가 서버는 인증과정에서 세션이 꼭 필요하기 때문에 STATELESS 구성을 진행할 경우 로그인이 실패합니다. (파훼법이 있긴 하지만 비추천됩니다.) - 인가 서버와 리소스 서버를 하나의 프로젝트에서 구성할 수 있지만, 분리해서 구현하겠습니다. ​ 다음 : 2. 프로젝트 생성 및 의존성 추가 https://youtu.be/7fMVxohRvl0 262, 스프링 OAuth2 인가 서버 > 2. 프로젝트 생성 및 의존성 추가 의존성 ​ https://start.spring.io/ {"_links":{"gradle-project":{"href":"https://start.spring.io/starter.zip?type=gradle-project{&dependencies,packaging,javaVersion,language,bootVersion,groupId,artifactId,version,name,description,packageName}","templated":true},"gradle-project-kotlin":{"href":"https://start.spring.io/starter.zip?type=... start.spring.io ​ - 시리즈 의존성 - Lombok - Spring Web - Mustache - Spring Security - OAuth2 Authorization Server - JDBC API - Spring Data JPA - MySQL Driver ​ application.properites 설정 ​ - 포트 설정 server.port=9000 ​ - 데이터베이스 설정​ spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver spring.datasource.url=jdbc:mysql://아이피:포트/세부디비명?useSSL=false&useUnicode=true&serverTimezone=Asia/Seoul&allowPublicKeyRetrieval=true spring.datasource.username=아이디 spring.datasource.password=비밀번호 spring.jpa.hibernate.ddl-auto=update spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl spring.jpa.show-sql=true ​ 이전 : 1. 실습 목표 및 간단 동작 원리 다음 : 3. 기본 로그인 구성 https://youtu.be/_z_bGZwuBMY 263, 스프링 OAuth2 인가 서버 > 3. 기본 로그인 구성 유저 도메인 ​ 우리 서비스가 가지고 있는 유저 정보를 기반으로 외부에 OAuth2 소셜 로그인을 제공하기 때문에 우리 서비스에서 기본적인 유저 로그인, 회원 가입 로직이 필요합니다. 예시로 네이버의 경우도 OAuth2 소셜 로그인 (네아로) 서비스의 경우 3자 플랫폼에서 소셜 로그인 요청을 한다면 네이버 유저로 로그인을 진행한 뒤 CODE와 JWT 발급 흐름이 발생하기 때문입니다. (당연한 이야기..) 따라서 ​ “스프링 시큐리티” 시리즈와 동일한 기본적인 세션 로그인 및 회원 가입 로직을 만들겠습니다. 다만 중요한 부분은 CustomUserDetailsService와 회원가입 로직에서 “스프링 시큐리티” 시리즈와 조금 다른 구현이 요구됩니다. UserEntity ​ - UserEntity @Entity @Getter @Setter public class UserEntity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String username; private String password; private String role; private String nickname; private String phone; } ​ - UserRepository​ public interface UserRepository extends JpaRepository { Optional findByUsername(String username); } ​ SecurityConfig ​ - SecurityConfig @Configuration @EnableWebSecurity public class SecurityConfig { @Bean public BCryptPasswordEncoder bCryptPasswordEncoder() { return new BCryptPasswordEncoder(); } @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http .csrf((csrf) -> csrf.disable()); http .authorizeHttpRequests((auth) -> auth .anyRequest().permitAll()); http .formLogin(withDefaults()); return http.build(); } } ​ 회원 가입 로직 ​ - UserDTO @Getter @Setter public class UserDTO { private String username; private String password; private String role; private String nickname; private String phone; } ​ - UserService​ @Service public class UserService { private final UserRepository userRepository; private final BCryptPasswordEncoder bCryptPasswordEncoder; public UserService(UserRepository userRepository, BCryptPasswordEncoder bCryptPasswordEncoder) { this.userRepository = userRepository; this.bCryptPasswordEncoder = bCryptPasswordEncoder; } public void join(UserDTO dto) { UserEntity entity = new UserEntity(); entity.setUsername(dto.getUsername()); entity.setPassword(bCryptPasswordEncoder.encode(dto.getPassword())); entity.setNickname(dto.getUsername()); entity.setPhone(dto.getPhone()); entity.setRole("ADMIN"); userRepository.save(entity); } } ​ 회원가입시 ROLE_ 접두사는 생략합니다. ​ - JoinController package com.example.spring_oauth_server.controller; import com.example.spring_oauth_server.dto.UserDTO; import com.example.spring_oauth_server.service.UserService; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; @Controller public class JoinController { private final UserService userService; public JoinController(UserService userService) { this.userService = userService; } @GetMapping("/join") public String joinPage() { return "joinPage"; } @PostMapping("/join") @ResponseBody public String join(UserDTO dto) { userService.join(dto); return "ok"; } } ​ - joinPage.mustache Join Page

Join Page






​ 로그인 로직 ​ - UserDetailsService @Service public class CustomUserDetailsService implements UserDetailsService { private final UserRepository userRepository; public CustomUserDetailsService(UserRepository userRepository) { this.userRepository = userRepository; } @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { UserEntity entity = userRepository.findByUsername(username).orElseThrow(); UserDetails userDetails = User.builder() .username(entity.getUsername()) .password(entity.getPassword()) .roles(entity.getRole()) .build(); return userDetails; } } ​ 기존 “스프링 시큐리티” 시리즈에서는 CustomUserDetails를 만들었지만 “Authorization Server” 의존성을 추가하면 함께 추가되는 SecurityJackson2 모듈에 의해 역직열화 문제 발생으로 커스텀을 진행하면 안됩니다. ​ 따라서 기장 기본적인 User.Builder로 UserDetails 타입을 만들어서 응답해야 앞으로 소셜 로그인 인가 서버 동작 과정에서 오류 없이 동작할 수 있습니다. ​ (특정 필드에 대한 직렬화 제외, mixin 설정, 직렬화 커스텀등 다양한 트러블 슈팅을 진행했지만, 오류가 연쇄적으로 터져서 일단은 불가능합니다.) 관련 이슈가 정말 많습니다. 깃허브 이슈 바로가기 회원 가입 진행 ​ 회원가입 테스트 진행 ​ 이전 : 2. 프로젝트 생성 및 의존성 추가 다음 : 4. 인가 서버 Bean 등록 https://youtu.be/-8r17mOeLLw 264, 스프링 OAuth2 인가 서버 > 4. 인가 서버 Bean 등록 인가 서버 Config ​ 저번 시간까지 “스프링 시큐리티”를 통한 기본적인 자체 로그인 로직을 구성했고, 이번 시간부터 “스프링 OAuth2 인가 서버”에 필요한 구성들을 작성하겠습니다. ​ ​ Register, 코드 요청 엔드포인트, JWT 요청 엔드포인트와 같이 소셜 로그인을 수행하기 위한 여러 엔드포인트를 활성화 시키기 위한 SecurityConfig에 Bean 등록이 요구됩니다. ​ AuthorizationServerSettings ​ OAuth2 인가 서버의 기본 설정을 정의하는 Bean으로 활성화시 기본값으로 설정되며 커스텀을 진행 할수도 있습니다. - 기본 설정 @Bean public AuthorizationServerSettings authorizationServerSettings() { return AuthorizationServerSettings.builder() .build(); } ​ - 커스텀 설정​ @Bean public AuthorizationServerSettings authorizationServerSettings() { return AuthorizationServerSettings.builder() .issuer("http://localhost:9000") .authorizationEndpoint("/oauth2/v1/authorize") .tokenEndpoint("/oauth2/v1/token") .tokenIntrospectionEndpoint("/oauth2/v1/introspect") // 토큰 상태 .tokenRevocationEndpoint("/oauth2/v1/revoke") // 토큰 폐기 RFC 7009 .jwkSetEndpoint("/oauth2/v1/jwks") // 공개키 확인 .oidcLogoutEndpoint("/connect/v1/logout") .oidcUserInfoEndpoint("/connect/v1/userinfo") // 리소스 서버 유저 정보 연관 .oidcClientRegistrationEndpoint("/connect/v1/register") // OAuth2 사용 신청 .build(); } ​ https://docs.spring.io/spring-authorization-server/reference/configuration-model.html#configuring-authorization-server-settings Configuration Model :: Spring Authorization Server Spring Authorization Server / Configuration Model Configuration Model # Default configuration OAuth2AuthorizationServerConfiguration is a @Configuration that provides the minimal default configuration for an OAuth2 authorization server. OAuth2AuthorizationServerConfiguration uses OAuth2Authorization... docs.spring.io ​ SecurityFilterChain ​ 기존의 로그인용 SecurityFilterChain이 등록되어 있지만 OAuth2 인가 서버용 SecurityFilterChain의 등록도 요구됩니다. 이 상황은 2개의 SecurityFilterChain이 등록되는 다중 SecurityFilterChain 상황으로 2개의 SecurityFilterChain에 대한 우선 순위 설정이 필요하며, 그 중 OAuth2 인가 서버용 SecurityFilterChain에 우선 순위를 부여해야 합니다. SecurityFilterChain 및 다중 등록 관련 자세한 설명 - authorizationServerFilterChain @Bean @Order(Ordered.HIGHEST_PRECEDENCE) public SecurityFilterChain authorizationServer(HttpSecurity http) throws Exception { OAuth2AuthorizationServerConfiguration.applyDefaultSecurity(http); http .getConfigurer(OAuth2AuthorizationServerConfigurer.class) .oidc(withDefaults()); http .exceptionHandling((exceptions) -> exceptions .defaultAuthenticationEntryPointFor( new LoginUrlAuthenticationEntryPoint("/login"), new MediaTypeRequestMatcher(MediaType.TEXT_HTML) ) ); return http.build(); } ​ exceptionHandling 등록하지 않으면 OAuth2 로그인 요청시 로그인 페이지가 발생하지 않습니다. ​ applyDefaultSecurity deprecated 오류 대처 ​ OAuth2 Authorization Server 의존성이 1.4.1 버전으로 올라감에 따라 applyDefaultSecurity 메소드 deprecated 에러 대처 방법 ​ https://cafe.naver.com/xxxjjhhh/259 스프링 OAuth2 인가 서버 > applyDefaultSecurity deprecated 대처 스프링 OAuth2 인가 서버 > applyDefaultSecurity deprecated 대처 감사합니다. deprecated 제보 감사드립니다. deprecated “... cafe.naver.com ​ 이전 : 3. 기본 로그인 구성 다음 : 5. Register 등록부 https://youtu.be/TjKpnKcro-c 265, 스프링 OAuth2 인가 서버 > 5. Register 등록부 모식도 ​ ​ Register에 해당하는 3자 플랫폼이 우리 서비스의 OAuth2 소셜 로그인을 사용하기 위한 신청 로직을 작성하겠습니다. (네이버의 경우도 소셜 로그인 서비스인 네아로를 사용하기 위해 네이버 개발자 센터에서 신청하듯 그 부분에 해당한다고 보시면 됩니다.) 사용 신청을 하는 이유 ​ 소셜 로그인 사용 신청을 진행하는 이유는 결국 3자가 우리의 자원(리소스)에 접근을 하기 때문에 어떤 플랫폼이 접근하고 우리의 정보를 가져가는지 트래킹을 진행해야 합니다. 또 우리 서비스도 요청을 하는 아무 플랫폼에게 주는 것이 아닌 사용 신청을 한 플랫폼에게만 인가를 주도록 구성해야 합니다. 사용 신청시 요구되는 필드 ​ - 예시 네이버 ​ - 우리가 사용할 필드 - ClientName : 3자 플랫폼이 설정한 어플리케이션 이름 - ClientId : 서비스측에서 랜덤값 (PK) - ClientSecret : 서비스측에서 랜덤값 - ClientIssuedAt : ClientId 생성 시점 - ClientSecretExpiresAt : ClientSecret 만료시간 (보통 부여 안함) - ClientAuthenticationMethods : 3자 플랫폼이 사용할 인증 방식 - AuthoriationGrantTypes : OAuth2 인증 방식 4종류 중 한가지 - RedirectUris : 3자 플랫폼이 코드를 받기 위해 허용 uri - PostLogoutRedirectUris : OAuth2 로그아웃 후 리디렉션 장소 - Scopes : 3자 플랫폼이 가질 권한 범위 - ClientSettings : 첫 로그인시 동의 표시와 같은 설정을 JSON으로 보관 - TokenSettings : CODE나 JWT 활성 시간과 같은 설정을 JSON으로 보관 ​ Entity 작성 ​ - RegisterEntity @Entity @Table(name = "oauth2_register") @Getter @Setter public class RegisterEntity { @Id private String id; private String clientId; private Instant clientIdIssuedAt; private String clientSecret; private Instant clientSecretExpiresAt; private String clientName; @Column(length = 1000) private String clientAuthenticationMethods; @Column(length = 1000) private String authorizationGrantTypes; @Column(length = 1000) private String redirectUris; @Column(length = 1000) private String postLogoutRedirectUris; @Column(length = 1000) private String scopes; @Column(length = 2000) private String clientSettings; @Column(length = 2000) private String tokenSettings; } ​ 위 테이블의 경우 Spring Security에서 공식으로 올려둔 테이블 기반으로 작성된 Entity입니다. - RegisterRepository public interface RegisterRepository extends JpaRepository { Optional findByClientId(String clientId); } 추후 등록부가 아닌 조회부에서 사용할 findByClientId() JPA 커스텀 메소드도 필수적으로 등록이 필요합니다. ​ DTO ​ 3자 플랫폼 사용 신청자의 Form으로 부터 데이터를 받을 DTO도 구현합니다. Entity가 가진 모든 필드를 가지고 있을 필요가 없기 때문에 필요한 요소만 사용하겠습니다. - RegisterDTO @Getter @Setter public class RegisterDTO { private String clientName; private String redirectUris; private String postLogoutRedirectUris; private String scopes; } ​ 서비스단 ​ 3자 플랫폼이 소셜 로그인 등록 Form으로 부터 등록을 하면 실제 우리의 RegisterEntity에 해당 값을 저장하는 로직. 앞단에서 RegisterDTO로 넘겨온 데이터 및 서비스단에서 만든 데이터를 RegisterEntity에 넣어서 저장하면 됩니다. ​ @Service public class RegisterService { private final RegisterRepository registerRepository; private final BCryptPasswordEncoder bCryptPasswordEncoder; public RegisterService(RegisterRepository registerRepository, BCryptPasswordEncoder bCryptPasswordEncoder) { this.registerRepository = registerRepository; this.bCryptPasswordEncoder = bCryptPasswordEncoder; } public RegisterEntity register(RegisterDTO dto) { RegisterEntity entity = new RegisterEntity(); entity.setId(UUID.randomUUID().toString()); entity.setClientId(UUID.randomUUID().toString()); entity.setClientIdIssuedAt(Instant.now()); entity.setClientSecret(bCryptPasswordEncoder.encode(UUID.randomUUID().toString())); entity.setClientAuthenticationMethods("client_secret_basic"); entity.setAuthorizationGrantTypes("refresh_token,authorization_code"); entity.setClientName(dto.getClientName()); entity.setRedirectUris(dto.getRedirectUris()); entity.setPostLogoutRedirectUris(dto.getPostLogoutRedirectUris()); entity.setScopes(dto.getScopes()); entity.setClientSettings("{\"@class\":\"java.util.Collections$UnmodifiableMap\",\"settings.client.require-proof-key\":false,\"settings.client.require-authorization-consent\":true}"); entity.setTokenSettings("{\"@class\":\"java.util.Collections$UnmodifiableMap\",\"settings.token.reuse-refresh-tokens\":true,\"settings.token.x509-certificate-bound-access-tokens\":false,\"settings.token.id-token-signature-algorithm\":[\"org.springframework.security.oauth2.jose.jws.SignatureAlgorithm\",\"RS256\"],\"settings.token.access-token-time-to-live\":[\"java.time.Duration\",300.000000000],\"settings.token.access-token-format\":{\"@class\":\"org.springframework.security.oauth2.server.authorization.settings.OAuth2TokenFormat\",\"value\":\"self-contained\"},\"settings.token.refresh-token-time-to-live\":[\"java.time.Duration\",3600.000000000],\"settings.token.authorization-code-time-to-live\":[\"java.time.Duration\",300.000000000],\"settings.token.device-code-time-to-live\":[\"java.time.Duration\",300.000000000]}"); return registerRepository.save(entity); } } ​ 컨트롤러 및 VIEW ​ - RegisterController @Controller public class RegisterController { private final RegisterService registerService; public RegisterController(RegisterService registerService) { this.registerService = registerService; } @GetMapping("/register") public String registerPage() { return "register"; } @PostMapping("/register") @ResponseBody public RegisterEntity register(RegisterDTO dto) { return registerService.register(dto); } } ​ - register.mustache



​ register 사용 등록 - clientName : 아무 값 - redirectUris : http://localhost:8080/login/oauth2/code/yummi - postLogoutRedirectUris : http://localhost:8080 - scopes : openid,profile​ ​ 이전 : 4. 인가 서버 Bean 등록 다음 : 6. Register 사용부 https://youtu.be/EMZ-oisNLR0 266, 스프링 OAuth2 인가 서버 > 6. Register 사용부 모식도 ​ ​ 저번 시간 구성한 Register 등록부 및 RegisterEntity 테이블을 기반으로, OAuth2 인가 서버 Config가 해당 자원들을 사용할 수 있도록 Register 사용부를 구현하겠습니다. ​ RegisteredClientRepository ​ 사용부의 경우 RegisteredClientRepository 인퍼테이스를 구현하면 됩니다. (구현부를 Bean 등록하면 인가 Config가 찾아서 사용) - 기본 제공 구현부 - InmemoryRegisteredClientRepository - 기본적으로 제공하는 두가지 구현체가 있지만, 인메모리의 경우 메모리 오버플로우 및 스케일 아웃 문제, Jdbc는 쿼리를 날리기는 편하지만 JPA를 다루는 입장에서 모르기 때문에 커스텀으로 Jpa 구현부를 만들겠습니다. JpaRegisterdClientRepository 구현 ​ RegisteredClientRepository가 요구하는 메소드만 오버라이딩 하시면 됩니다. ​ import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.Module; import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.security.jackson2.SecurityJackson2Modules; import org.springframework.security.oauth2.core.AuthorizationGrantType; import org.springframework.security.oauth2.core.ClientAuthenticationMethod; import org.springframework.security.oauth2.server.authorization.client.RegisteredClient; import org.springframework.security.oauth2.server.authorization.client.RegisteredClientRepository; import org.springframework.security.oauth2.server.authorization.jackson2.OAuth2AuthorizationServerJackson2Module; import org.springframework.security.oauth2.server.authorization.settings.ClientSettings; import org.springframework.security.oauth2.server.authorization.settings.TokenSettings; import org.springframework.stereotype.Component; import org.springframework.util.StringUtils; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Set; @Component public class JpaRegisteredClientRepository implements RegisteredClientRepository { private final RegisterRepository registerRepository; private final ObjectMapper objectMapper = new ObjectMapper(); public JpaRegisteredClientRepository(RegisterRepository registerRepository) { this.registerRepository = registerRepository; ClassLoader classLoader = JpaRegisteredClientRepository.class.getClassLoader(); List securityModules = SecurityJackson2Modules.getModules(classLoader); this.objectMapper.registerModules(securityModules); this.objectMapper.registerModule(new OAuth2AuthorizationServerJackson2Module()); } @Override public void save(RegisteredClient registeredClient) { registerRepository.save(toEntity(registeredClient)); } @Override public RegisteredClient findById(String id) { return registerRepository.findById(id).map(this::toObject).orElse(null); } @Override public RegisteredClient findByClientId(String clientId) { return registerRepository.findByClientId(clientId).map(this::toObject).orElse(null); } private RegisteredClient toObject(RegisterEntity entity) { Set clientAuthenticationMethods = StringUtils.commaDelimitedListToSet(entity.getClientAuthenticationMethods()); Set authorizationGrantTypes = StringUtils.commaDelimitedListToSet(entity.getAuthorizationGrantTypes()); Set redirectUris = StringUtils.commaDelimitedListToSet(entity.getRedirectUris()); Set postLogoutRedirectUris = StringUtils.commaDelimitedListToSet(entity.getPostLogoutRedirectUris()); Set clientScopes = StringUtils.commaDelimitedListToSet(entity.getScopes()); RegisteredClient.Builder builder = RegisteredClient.withId(entity.getId()) .clientId(entity.getClientId()) .clientIdIssuedAt(entity.getClientIdIssuedAt()) .clientSecret(entity.getClientSecret()) .clientSecretExpiresAt(entity.getClientSecretExpiresAt()) .clientName(entity.getClientName()) .clientAuthenticationMethods(authenticationMethods -> clientAuthenticationMethods.forEach(authenticationMethod -> authenticationMethods.add(resolveClientAuthenticationMethod(authenticationMethod)))) .authorizationGrantTypes((grantTypes) -> authorizationGrantTypes.forEach(grantType -> grantTypes.add(resolveAuthorizationGrantType(grantType)))) .redirectUris((uris) -> uris.addAll(redirectUris)) .postLogoutRedirectUris((uris) -> uris.addAll(postLogoutRedirectUris)) .scopes((scopes) -> scopes.addAll(clientScopes)); Map clientSettingsMap = parseMap(entity.getClientSettings()); builder.clientSettings(ClientSettings.withSettings(clientSettingsMap).build()); Map tokenSettingsMap = parseMap(entity.getTokenSettings()); builder.tokenSettings(TokenSettings.withSettings(tokenSettingsMap).build()); return builder.build(); } private RegisterEntity toEntity(RegisteredClient registeredClient) { List clientAuthenticationMethods = new ArrayList<>(registeredClient.getClientAuthenticationMethods().size()); registeredClient.getClientAuthenticationMethods().forEach(clientAuthenticationMethod -> clientAuthenticationMethods.add(clientAuthenticationMethod.getValue())); List authorizationGrantTypes = new ArrayList<>(registeredClient.getAuthorizationGrantTypes().size()); registeredClient.getAuthorizationGrantTypes().forEach(authorizationGrantType -> authorizationGrantTypes.add(authorizationGrantType.getValue())); RegisterEntity entity = new RegisterEntity(); entity.setId(registeredClient.getId()); entity.setClientId(registeredClient.getClientId()); entity.setClientIdIssuedAt(registeredClient.getClientIdIssuedAt()); entity.setClientSecret(registeredClient.getClientSecret()); entity.setClientSecretExpiresAt(registeredClient.getClientSecretExpiresAt()); entity.setClientName(registeredClient.getClientName()); entity.setClientAuthenticationMethods(StringUtils.collectionToCommaDelimitedString(clientAuthenticationMethods)); entity.setAuthorizationGrantTypes(StringUtils.collectionToCommaDelimitedString(authorizationGrantTypes)); entity.setRedirectUris(StringUtils.collectionToCommaDelimitedString(registeredClient.getRedirectUris())); entity.setPostLogoutRedirectUris(StringUtils.collectionToCommaDelimitedString(registeredClient.getPostLogoutRedirectUris())); entity.setScopes(StringUtils.collectionToCommaDelimitedString(registeredClient.getScopes())); entity.setClientSettings(writeMap(registeredClient.getClientSettings().getSettings())); entity.setTokenSettings(writeMap(registeredClient.getTokenSettings().getSettings())); return entity; } private Map parseMap(String data) { try { return this.objectMapper.readValue(data, new TypeReference>() { }); } catch (Exception ex) { throw new IllegalArgumentException(ex.getMessage(), ex); } } private String writeMap(Map data) { try { return this.objectMapper.writeValueAsString(data); } catch (Exception ex) { throw new IllegalArgumentException(ex.getMessage(), ex); } } private static AuthorizationGrantType resolveAuthorizationGrantType(String authorizationGrantType) { if (AuthorizationGrantType.AUTHORIZATION_CODE.getValue().equals(authorizationGrantType)) { return AuthorizationGrantType.AUTHORIZATION_CODE; } else if (AuthorizationGrantType.CLIENT_CREDENTIALS.getValue().equals(authorizationGrantType)) { return AuthorizationGrantType.CLIENT_CREDENTIALS; } else if (AuthorizationGrantType.REFRESH_TOKEN.getValue().equals(authorizationGrantType)) { return AuthorizationGrantType.REFRESH_TOKEN; } return new AuthorizationGrantType(authorizationGrantType); } private static ClientAuthenticationMethod resolveClientAuthenticationMethod(String clientAuthenticationMethod) { if (ClientAuthenticationMethod.CLIENT_SECRET_BASIC.getValue().equals(clientAuthenticationMethod)) { return ClientAuthenticationMethod.CLIENT_SECRET_BASIC; } else if (ClientAuthenticationMethod.CLIENT_SECRET_POST.getValue().equals(clientAuthenticationMethod)) { return ClientAuthenticationMethod.CLIENT_SECRET_POST; } else if (ClientAuthenticationMethod.NONE.getValue().equals(clientAuthenticationMethod)) { return ClientAuthenticationMethod.NONE; } return new ClientAuthenticationMethod(clientAuthenticationMethod); } } ​ 기본 제공 구현부 사용 방법 ​ 만약 Jpa 구현부를 직접 구현하기 귀찮으신 분들은 아래와 같은 방법으로 기본 제공 구현부를 사용할 수 있습니다. SecurityConfig 클래스에서 Bean 등록 진행 - InmemoryRegisteredClientRepository @Bean public RegisteredClientRepository registeredClientRepository() { return new InMemoryRegisteredClientRepository(); } ​ - JdbcRegisteredClientRepository @Bean public RegisteredClientRepository registeredClientRepository() { return new JdbcRegisteredClientRepository(); } ​ 이전 : 5. Register 등록부 다음 : 7. Authorization 과정 저장 https://youtu.be/lY0j_o03H5U 267, 스프링 OAuth2 인가 서버 > 7. Authroization 과정 저장 모식도 ​ ​ '사용 등록' 부분은 완료 했습니다. 이제 3자 플랫폼이 사용 등록 후, 1번과 2번에 해당하는 엔드포인트로 접근하여 각각의 데이터를 받아갑니다. 이제 1번, 2번에 해당하는 Bean들을 구현해야 합니다. 하지만 그전에 1번, 2번이 동작하며 발생하는 결과물들을 (발급한 코드, 토큰, 발급 받아간 3자 플랫폼, 유저) 저장하고 관리하는 시스템이 필요하며 해당 로직은 AuthorizationEntity를 기반으로 동작합니다. 따라서 AuthorizationEntity 및 서비스단을 구현하겠습니다. (JPA 방식으로 구현합니다.) AuthorizationEntity ​ - AuthorizationEntity @Entity @Table(name = "oauth2_authorization") @Getter @Setter public class AuthorizationEntity { @Id @Column private String id; private String registeredClientId; private String principalName; private String authorizationGrantType; @Column(columnDefinition = "TEXT") private String authorizedScopes; @Column(columnDefinition = "TEXT") private String attributes; @Column(length = 500) private String state; @Column(columnDefinition = "TEXT") private String authorizationCodeValue; private Instant authorizationCodeIssuedAt; private Instant authorizationCodeExpiresAt; private String authorizationCodeMetadata; @Column(columnDefinition = "TEXT") private String accessTokenValue; private Instant accessTokenIssuedAt; private Instant accessTokenExpiresAt; @Column(length = 2000) private String accessTokenMetadata; private String accessTokenType; @Column(length = 1000) private String accessTokenScopes; @Column(columnDefinition = "TEXT") private String refreshTokenValue; private Instant refreshTokenIssuedAt; private Instant refreshTokenExpiresAt; @Column(length = 2000) private String refreshTokenMetadata; @Column(columnDefinition = "TEXT") private String oidcIdTokenValue; private Instant oidcIdTokenIssuedAt; private Instant oidcIdTokenExpiresAt; @Column(length = 2000) private String oidcIdTokenMetadata; @Column(length = 2000) private String oidcIdTokenClaims; @Column(columnDefinition = "TEXT") private String userCodeValue; private Instant userCodeIssuedAt; private Instant userCodeExpiresAt; @Column(length = 2000) private String userCodeMetadata; @Column(columnDefinition = "TEXT") private String deviceCodeValue; private Instant deviceCodeIssuedAt; private Instant deviceCodeExpiresAt; @Column(length = 2000) private String deviceCodeMetadata; } ​ - AuthorizationRepository public interface AuthorizationRepository extends JpaRepository { Optional findByState(String state); Optional findByAuthorizationCodeValue(String authorizationCode); Optional findByAccessTokenValue(String accessToken); Optional findByRefreshTokenValue(String refreshToken); Optional findByOidcIdTokenValue(String idToken); Optional findByUserCodeValue(String userCode); Optional findByDeviceCodeValue(String deviceCode); @Query("select a from AuthorizationEntity a where a.state = :token" + " or a.authorizationCodeValue = :token" + " or a.accessTokenValue = :token" + " or a.refreshTokenValue = :token" + " or a.oidcIdTokenValue = :token" + " or a.userCodeValue = :token" + " or a.deviceCodeValue = :token" ) Optional findByStateOrAuthorizationCodeValueOrAccessTokenValueOrRefreshTokenValueOrOidcIdTokenValueOrUserCodeValueOrDeviceCodeValue(@Param("token") String token); } ​ OAuth2AuthorizationService 구현 ​ 위에서 작성한 Entity Repository를 OAuth2 인가 Config가 사용할 수 있도록 OAuth2AuthorizationService 인터페이스를 구현해야 합니다. OAuth2AuthorizationService 인터페이스의 기본 제공 구현부는 InMemoryOAuth2AuthorizationService, JdbcOAuth2AuthorizationService가 존재하지만 JPA 방식을 직접 커스텀해서 구현하겠습니다. ​ import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.Module; import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.dao.DataRetrievalFailureException; import org.springframework.security.jackson2.SecurityJackson2Modules; import org.springframework.security.oauth2.core.*; import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames; import org.springframework.security.oauth2.core.oidc.OidcIdToken; import org.springframework.security.oauth2.core.oidc.endpoint.OidcParameterNames; import org.springframework.security.oauth2.server.authorization.OAuth2Authorization; import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationCode; import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationService; import org.springframework.security.oauth2.server.authorization.OAuth2TokenType; import org.springframework.security.oauth2.server.authorization.client.RegisteredClient; import org.springframework.security.oauth2.server.authorization.client.RegisteredClientRepository; import org.springframework.security.oauth2.server.authorization.jackson2.OAuth2AuthorizationServerJackson2Module; import org.springframework.stereotype.Component; import org.springframework.util.StringUtils; import java.time.Instant; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.function.Consumer; @Component public class JpaOAuth2AuthorizationService implements OAuth2AuthorizationService { private final AuthorizationRepository authorizationRepository; private final RegisteredClientRepository registeredClientRepository; private final ObjectMapper objectMapper = new ObjectMapper(); public JpaOAuth2AuthorizationService(AuthorizationRepository authorizationRepository, RegisteredClientRepository registeredClientRepository) { this.authorizationRepository = authorizationRepository; this.registeredClientRepository = registeredClientRepository; ClassLoader classLoader = JpaOAuth2AuthorizationService.class.getClassLoader(); List securityModules = SecurityJackson2Modules.getModules(classLoader); this.objectMapper.registerModules(securityModules); this.objectMapper.registerModule(new OAuth2AuthorizationServerJackson2Module()); } @Override public void save(OAuth2Authorization authorization) { authorizationRepository.save(toEntity(authorization)); } @Override public void remove(OAuth2Authorization authorization) { authorizationRepository.deleteById(authorization.getId()); } @Override public OAuth2Authorization findById(String id) { return authorizationRepository.findById(id).map(this::toObject).orElse(null); } @Override public OAuth2Authorization findByToken(String token, OAuth2TokenType tokenType) { Optional result; if (tokenType == null) { result = this.authorizationRepository.findByStateOrAuthorizationCodeValueOrAccessTokenValueOrRefreshTokenValueOrOidcIdTokenValueOrUserCodeValueOrDeviceCodeValue(token); } else if (OAuth2ParameterNames.STATE.equals(tokenType.getValue())) { result = this.authorizationRepository.findByState(token); } else if (OAuth2ParameterNames.CODE.equals(tokenType.getValue())) { result = this.authorizationRepository.findByAuthorizationCodeValue(token); } else if (OAuth2ParameterNames.ACCESS_TOKEN.equals(tokenType.getValue())) { result = this.authorizationRepository.findByAccessTokenValue(token); } else if (OAuth2ParameterNames.REFRESH_TOKEN.equals(tokenType.getValue())) { result = this.authorizationRepository.findByRefreshTokenValue(token); } else if (OidcParameterNames.ID_TOKEN.equals(tokenType.getValue())) { result = this.authorizationRepository.findByOidcIdTokenValue(token); } else if (OAuth2ParameterNames.USER_CODE.equals(tokenType.getValue())) { result = this.authorizationRepository.findByUserCodeValue(token); } else if (OAuth2ParameterNames.DEVICE_CODE.equals(tokenType.getValue())) { result = this.authorizationRepository.findByDeviceCodeValue(token); } else { result = Optional.empty(); } return result.map(this::toObject).orElse(null); } private OAuth2Authorization toObject(AuthorizationEntity entity) { RegisteredClient registeredClient = this.registeredClientRepository.findById(entity.getRegisteredClientId()); if (registeredClient == null) { throw new DataRetrievalFailureException( "The RegisteredClient with id '" + entity.getRegisteredClientId() + "' was not found in the RegisteredClientRepository."); } OAuth2Authorization.Builder builder = OAuth2Authorization.withRegisteredClient(registeredClient) .id(entity.getId()) .principalName(entity.getPrincipalName()) .authorizationGrantType(resolveAuthorizationGrantType(entity.getAuthorizationGrantType())) .authorizedScopes(StringUtils.commaDelimitedListToSet(entity.getAuthorizedScopes())) .attributes(attributes -> attributes.putAll(parseMap(entity.getAttributes()))); if (entity.getState() != null) { builder.attribute(OAuth2ParameterNames.STATE, entity.getState()); } if (entity.getAuthorizationCodeValue() != null) { OAuth2AuthorizationCode authorizationCode = new OAuth2AuthorizationCode( entity.getAuthorizationCodeValue(), entity.getAuthorizationCodeIssuedAt(), entity.getAuthorizationCodeExpiresAt()); builder.token(authorizationCode, metadata -> metadata.putAll(parseMap(entity.getAuthorizationCodeMetadata()))); } if (entity.getAccessTokenValue() != null) { OAuth2AccessToken accessToken = new OAuth2AccessToken( OAuth2AccessToken.TokenType.BEARER, entity.getAccessTokenValue(), entity.getAccessTokenIssuedAt(), entity.getAccessTokenExpiresAt(), StringUtils.commaDelimitedListToSet(entity.getAccessTokenScopes())); builder.token(accessToken, metadata -> metadata.putAll(parseMap(entity.getAccessTokenMetadata()))); } if (entity.getRefreshTokenValue() != null) { OAuth2RefreshToken refreshToken = new OAuth2RefreshToken( entity.getRefreshTokenValue(), entity.getRefreshTokenIssuedAt(), entity.getRefreshTokenExpiresAt()); builder.token(refreshToken, metadata -> metadata.putAll(parseMap(entity.getRefreshTokenMetadata()))); } if (entity.getOidcIdTokenValue() != null) { OidcIdToken idToken = new OidcIdToken( entity.getOidcIdTokenValue(), entity.getOidcIdTokenIssuedAt(), entity.getOidcIdTokenExpiresAt(), parseMap(entity.getOidcIdTokenClaims())); builder.token(idToken, metadata -> metadata.putAll(parseMap(entity.getOidcIdTokenMetadata()))); } if (entity.getUserCodeValue() != null) { OAuth2UserCode userCode = new OAuth2UserCode( entity.getUserCodeValue(), entity.getUserCodeIssuedAt(), entity.getUserCodeExpiresAt()); builder.token(userCode, metadata -> metadata.putAll(parseMap(entity.getUserCodeMetadata()))); } if (entity.getDeviceCodeValue() != null) { OAuth2DeviceCode deviceCode = new OAuth2DeviceCode( entity.getDeviceCodeValue(), entity.getDeviceCodeIssuedAt(), entity.getDeviceCodeExpiresAt()); builder.token(deviceCode, metadata -> metadata.putAll(parseMap(entity.getDeviceCodeMetadata()))); } return builder.build(); } private AuthorizationEntity toEntity(OAuth2Authorization authorization) { AuthorizationEntity entity = new AuthorizationEntity(); entity.setId(authorization.getId()); entity.setRegisteredClientId(authorization.getRegisteredClientId()); entity.setPrincipalName(authorization.getPrincipalName()); entity.setAuthorizationGrantType(authorization.getAuthorizationGrantType().getValue()); entity.setAuthorizedScopes(StringUtils.collectionToDelimitedString(authorization.getAuthorizedScopes(), ",")); entity.setAttributes(writeMap(authorization.getAttributes())); entity.setState(authorization.getAttribute(OAuth2ParameterNames.STATE)); OAuth2Authorization.Token authorizationCode = authorization.getToken(OAuth2AuthorizationCode.class); setTokenValues( authorizationCode, entity::setAuthorizationCodeValue, entity::setAuthorizationCodeIssuedAt, entity::setAuthorizationCodeExpiresAt, entity::setAuthorizationCodeMetadata ); OAuth2Authorization.Token accessToken = authorization.getToken(OAuth2AccessToken.class); setTokenValues( accessToken, entity::setAccessTokenValue, entity::setAccessTokenIssuedAt, entity::setAccessTokenExpiresAt, entity::setAccessTokenMetadata ); if (accessToken != null && accessToken.getToken().getScopes() != null) { entity.setAccessTokenScopes(StringUtils.collectionToDelimitedString(accessToken.getToken().getScopes(), ",")); } OAuth2Authorization.Token refreshToken = authorization.getToken(OAuth2RefreshToken.class); setTokenValues( refreshToken, entity::setRefreshTokenValue, entity::setRefreshTokenIssuedAt, entity::setRefreshTokenExpiresAt, entity::setRefreshTokenMetadata ); OAuth2Authorization.Token oidcIdToken = authorization.getToken(OidcIdToken.class); setTokenValues( oidcIdToken, entity::setOidcIdTokenValue, entity::setOidcIdTokenIssuedAt, entity::setOidcIdTokenExpiresAt, entity::setOidcIdTokenMetadata ); if (oidcIdToken != null) { entity.setOidcIdTokenClaims(writeMap(oidcIdToken.getClaims())); } OAuth2Authorization.Token userCode = authorization.getToken(OAuth2UserCode.class); setTokenValues( userCode, entity::setUserCodeValue, entity::setUserCodeIssuedAt, entity::setUserCodeExpiresAt, entity::setUserCodeMetadata ); OAuth2Authorization.Token deviceCode = authorization.getToken(OAuth2DeviceCode.class); setTokenValues( deviceCode, entity::setDeviceCodeValue, entity::setDeviceCodeIssuedAt, entity::setDeviceCodeExpiresAt, entity::setDeviceCodeMetadata ); return entity; } private void setTokenValues( OAuth2Authorization.Token token, Consumer tokenValueConsumer, Consumer issuedAtConsumer, Consumer expiresAtConsumer, Consumer metadataConsumer) { if (token != null) { OAuth2Token oAuth2Token = token.getToken(); tokenValueConsumer.accept(oAuth2Token.getTokenValue()); issuedAtConsumer.accept(oAuth2Token.getIssuedAt()); expiresAtConsumer.accept(oAuth2Token.getExpiresAt()); metadataConsumer.accept(writeMap(token.getMetadata())); } } private Map parseMap(String data) { try { return this.objectMapper.readValue(data, new TypeReference>() { }); } catch (Exception ex) { throw new IllegalArgumentException(ex.getMessage(), ex); } } private String writeMap(Map metadata) { try { return this.objectMapper.writeValueAsString(metadata); } catch (Exception ex) { throw new IllegalArgumentException(ex.getMessage(), ex); } } private static AuthorizationGrantType resolveAuthorizationGrantType(String authorizationGrantType) { if (AuthorizationGrantType.AUTHORIZATION_CODE.getValue().equals(authorizationGrantType)) { return AuthorizationGrantType.AUTHORIZATION_CODE; } else if (AuthorizationGrantType.CLIENT_CREDENTIALS.getValue().equals(authorizationGrantType)) { return AuthorizationGrantType.CLIENT_CREDENTIALS; } else if (AuthorizationGrantType.REFRESH_TOKEN.getValue().equals(authorizationGrantType)) { return AuthorizationGrantType.REFRESH_TOKEN; } else if (AuthorizationGrantType.DEVICE_CODE.getValue().equals(authorizationGrantType)) { return AuthorizationGrantType.DEVICE_CODE; } return new AuthorizationGrantType(authorizationGrantType); } } ​ 이전 : 6. Register 사용부 다음 : 8. 코드 발급부 https://youtu.be/bmouhgBpEnM 268, 스프링 OAuth2 인가 서버 > 8. 코드 발급부 모식도 ​ ​ ‘1. 코드 요청’ 엔드포인트에 필요한 @Bean 들을 등록하겠습니다. ‘1. 코드 요청’ 부분의 역할은 3자 플랫폼에서 ‘소셜 로그인’ 버튼을 누르게 된다면 발생하게 되는 인가 서버의 로그인창, 코드 발급을 수행합니다. ​ 수행 과정 ​ - 3자 플랫폼에서 소셜 로그인 하기 버튼을 클릭 (스프링 OAuth2 클라이언트) ​ 3자 플랫폼에 해당하는 "OAuth2 클라이언트"에서 소셜 로그인을 제공하는 “OAuth2 인가 서버”로 요청 보냄 이때 요청은 아래 주소와 같습니다. ​ https://주소/oauth2/authorize?response_type=code&client_id=등록아이디&scope=profile&redirect_uri=http://localhost:8080/login/oauth2/code/yummi ​ - 로그인창 표시 (스프링 OAuth2 인가 서버) ​ 로그인을 진행하기 위한 로그인창을 인가 서버에서 응답합니다. 이때 스프링 OAuth2 인가 서버의 경우 스프링 시큐리티에서 설정한 로그인창이 발생됩니다. ​ - 로그인 후 동의 화면 표시 (동의를 안 한 경우) ​ 특정 scope(범위)에 대해 3자 플랫폼에게 제공한다는 동의 사항 - 코드 발급 로그인이 완료 되었기 때문에 “스프링 OAuth2 인가 서버”에서 처음 받은 redirect_uri로 CODE를 발급합니다. ​ 코드 발급부 구현 목록 ​ 기본적인 로그인창과 엔드포인트는 처음 4강에서 진행한 “인가 Bean” 등록을 통해 자동으로 활성화 되지만, 동의 화면에 대한 결과 저장의 경우 직접 구현해서 등록해야 합니다. 따라서 동의 화면에서 발생한 결과를 저장하는 테이블 Entity, Repository, Service단을 구성하겠습니다. ConsentEntity ​ - ConsentEntity @Entity @Table(name = "oauth2_consent") @IdClass(ConsentEntity.AuthorizationConsentId.class) @Getter @Setter public class ConsentEntity { @Id private String registeredClientId; @Id private String principalName; @Column(length = 1000) private String authorities; public static class AuthorizationConsentId implements Serializable { private String registeredClientId; private String principalName; @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; AuthorizationConsentId that = (AuthorizationConsentId) o; return registeredClientId.equals(that.registeredClientId) && principalName.equals(that.principalName); } @Override public int hashCode() { return Objects.hash(registeredClientId, principalName); } } } ​ - ConsentRepository public interface ConsentRepository extends JpaRepository { Optional findByRegisteredClientIdAndPrincipalName(String registeredClientId, String principalName); void deleteByRegisteredClientIdAndPrincipalName(String registeredClientId, String principalName); } ​ OAuth2AuthorizationConsentService 구현 ​ 위에서 작성한 ConsentEntity를 OAuth2 인가 Config가 사용할 수 있도록 OAuth2AuthorizationConsentService 인터페이스를 구현해야 합니다. OAuth2AuthorizationConsentService 인터페이스의 기본 제공 구현부는 InMemoryOAuth2AuthorizationConsentService, JdbcOAuth2AuthorizationConsentService가 존재하지만 JPA 방식을 직접 커스텀해서 구현하겠습니다. - JpaOAuth2AuthorizationConsentService import org.springframework.dao.DataRetrievalFailureException; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationConsent; import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationConsentService; import org.springframework.security.oauth2.server.authorization.client.RegisteredClient; import org.springframework.security.oauth2.server.authorization.client.RegisteredClientRepository; import org.springframework.stereotype.Component; import org.springframework.util.StringUtils; import java.util.HashSet; import java.util.Set; @Component public class JpaOAuth2AuthorizationConsentService implements OAuth2AuthorizationConsentService { private final ConsentRepository consentRepository; private final RegisteredClientRepository registeredClientRepository; public JpaOAuth2AuthorizationConsentService(ConsentRepository consentRepository, RegisteredClientRepository registeredClientRepository) { this.consentRepository = consentRepository; this.registeredClientRepository = registeredClientRepository; } @Override public void save(OAuth2AuthorizationConsent authorizationConsent) { consentRepository.save(toEntity(authorizationConsent)); } @Override public void remove(OAuth2AuthorizationConsent authorizationConsent) { consentRepository.deleteByRegisteredClientIdAndPrincipalName(authorizationConsent.getRegisteredClientId(), authorizationConsent.getPrincipalName()); } @Override public OAuth2AuthorizationConsent findById(String registeredClientId, String principalName) { return consentRepository.findByRegisteredClientIdAndPrincipalName(registeredClientId, principalName).map(this::toObject).orElse(null); } private OAuth2AuthorizationConsent toObject(ConsentEntity authorizationConsent) { String registeredClientId = authorizationConsent.getRegisteredClientId(); RegisteredClient registeredClient = this.registeredClientRepository.findById(registeredClientId); if (registeredClient == null) { throw new DataRetrievalFailureException( "The RegisteredClient with id '" + registeredClientId + "' was not found in the RegisteredClientRepository."); } OAuth2AuthorizationConsent.Builder builder = OAuth2AuthorizationConsent.withId( registeredClientId, authorizationConsent.getPrincipalName()); if (authorizationConsent.getAuthorities() != null) { for (String authority : StringUtils.commaDelimitedListToSet(authorizationConsent.getAuthorities())) { builder.authority(new SimpleGrantedAuthority(authority)); } } return builder.build(); } private ConsentEntity toEntity(OAuth2AuthorizationConsent authorizationConsent) { ConsentEntity entity = new ConsentEntity(); entity.setRegisteredClientId(authorizationConsent.getRegisteredClientId()); entity.setPrincipalName(authorizationConsent.getPrincipalName()); Set authorities = new HashSet<>(); for (GrantedAuthority authority : authorizationConsent.getAuthorities()) { authorities.add(authority.getAuthority()); } entity.setAuthorities(StringUtils.collectionToCommaDelimitedString(authorities)); return entity; } } ​ 이전 : 7. Authorization 과정 저장 다음 : 9. 토큰 발급부 https://youtu.be/dI1-9Nz8RT4 269, 스프링 OAuth2 인가 서버 > 9. 토큰 발급부 모식도 ​ ​ ‘2. JWT 요청’ 엔드포인트에 필요한 @Bean 들을 등록하겠습니다. ‘2. JWT 요청’ 부분의 역할은 3자 플랫폼에서 ‘1. 코드 요청’을 통해 CODE를 발급한 후 다시 접근하여 CODE를 검증하여 JWT 발급을 수행합니다. ​ 수행 과정 ​ - 앞의 ‘8. 코드 발급부’에 이어 - 3자 플랫폼이 CODE 및 등록 clientId, clientSecret를 가지고 접근 - CODE, clientId, clientSecret 검증 후 JWT 발급 (OAuth2 인가 서버) 이때 JWT의 claim에는 ROLE과 같은 정보를 담고 있으며 JWT 서명은 RSA 방식을 주로 사용합니다. ​ 토큰 (JWT) 발급부 구현 목록 ​ 기본적인 엔드포인트의 경우 처음 4강에서 진행한 “인가 Bean” 등록을 통해 자동으로 활성화 되지만, 토큰 발급시 서명에 대한 알고리즘은 Bean으로 등록해야 합니다. 이때 서명의 경우 대칭키, 비대칭키로 나뉘며 비대칭키 방식을 지향하고 있습니다. ​ 비대칭키로 구현하는 이유 ​ ​ “OAuth2 인가 서버”에서는 로그인 후 접근 SCOPE를 담은 토큰을 발급하고, “OAuth2 리소스 서버”에서는 토큰을 검증(발급처가 우리 인가 서버 인지)하여 리소스 접근을 허락합니다. - 대칭키의 경우 대칭키의 경우 토큰 암호화 및 복호화를 동일한 키로 진행합니다. 따라서 인가서버 및 리소스 서버의 변수에 키값이 포함되어야 합니다. 이런 경우 키 관리가 어려워집니다. (해킹에 대한 많은 접근 지점, 키값 변경시 모든 서버 값 변경) - 비대칭키의 경우 (사용 예정) 인가 서버 토큰 발급시 비밀키로 암호화 후 공개키를 인가 서버 엔드포인트에서 주면 리소스 서버에서는 공개키로 해독을 진행함과 동시에 인가 서버에서 발급한 키라고 인지할 수 있으며, 위의 키 관리 문제도 해결됩니다. JWT 생성기 등록 ​ 스프링 인가 서버가 사용할 수 있도록 키 생성기를 비대칭키 방식으로 구현해서 등록시키면 됩니다. - SecurityConfig @Bean public JWKSource jwkSource() { KeyPair keyPair = generateRsaKey(); RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic(); RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate(); RSAKey rsaKey = new RSAKey.Builder(publicKey).privateKey(privateKey).keyID(UUID.randomUUID().toString()).build(); JWKSet jwkSet = new JWKSet(rsaKey); return (jwkSelector, securityContext) -> jwkSelector.select(jwkSet); } private static KeyPair generateRsaKey() { KeyPair keyPair; try { KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); keyPairGenerator.initialize(2048); keyPair = keyPairGenerator.generateKeyPair(); } catch (Exception e) { throw new IllegalStateException(e); } return keyPair; } ​ - import 참고 import com.nimbusds.jose.jwk.JWKSet; import com.nimbusds.jose.jwk.RSAKey; import com.nimbusds.jose.jwk.source.JWKSource; import com.nimbusds.jose.proc.SecurityContext; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.interfaces.RSAPrivateKey; import java.security.interfaces.RSAPublicKey; import java.util.UUID; ​ 이때 공개키를 제공하는 엔드포인트는 아래와 같습니다. ​ /oauth2/jwks ​ 이전 : 8. 코드 발급부 다음 : 10. 시연 https://youtu.be/_eRE4sPtuJU 270, 스프링 OAuth2 인가 서버 > 10. 시연 모식도 ​ ​ OAuth2 소셜 로그인을 구성할 3가지 중 “OAuth2 인가 서버” 구성을 완료 했기 때문에 테스트를 진행하겠습니다. 아직 OAuth2 리소스 서버, 클라이언트 구성을 마치지 않았기 때문에 아래의 3가지를 테스트 하겠습니다. ​ ​ - 사용 등록 테스트 (사용 등록시 발급되는 clientId, clientSecret를 기록) - CODE 발급 테스트 (로그인 경로로 접근 후 발급되는 CODE 확인) - 토큰 발급 테스트 (CODE로 토큰 획득) ​ 추가 구현 사항 ​ Register 등록부에서 clientSecret 값도 Form에서 넘겨 줄 수 있도록 구성하겠습니다. - register.mustache Document





​ - RegisterDTO @Getter @Setter public class RegisterDTO { private String clientName; private String clientSecret; private String redirectUris; private String postLogoutRedirectUris; private String scopes; } ​ - RegisterService​ public RegisterEntity register(RegisterDTO dto) { RegisterEntity entity = new RegisterEntity(); entity.setId(UUID.randomUUID().toString()); entity.setClientId(UUID.randomUUID().toString()); entity.setClientIdIssuedAt(Instant.now()); entity.setClientSecret(bCryptPasswordEncoder.encode(dto.getClientSecret())); entity.setClientAuthenticationMethods("client_secret_basic"); entity.setAuthorizationGrantTypes("refresh_token,authorization_code"); entity.setClientName(dto.getClientName()); entity.setRedirectUris(dto.getRedirectUris()); entity.setPostLogoutRedirectUris(dto.getPostLogoutRedirectUris()); entity.setScopes(dto.getScopes()); entity.setClientSettings("{\"@class\":\"java.util.Collections$UnmodifiableMap\",\"settings.client.require-proof-key\":false,\"settings.client.require-authorization-consent\":true}"); entity.setTokenSettings("{\"@class\":\"java.util.Collections$UnmodifiableMap\",\"settings.token.reuse-refresh-tokens\":true,\"settings.token.x509-certificate-bound-access-tokens\":false,\"settings.token.id-token-signature-algorithm\":[\"org.springframework.security.oauth2.jose.jws.SignatureAlgorithm\",\"RS256\"],\"settings.token.access-token-time-to-live\":[\"java.time.Duration\",300.000000000],\"settings.token.access-token-format\":{\"@class\":\"org.springframework.security.oauth2.server.authorization.settings.OAuth2TokenFormat\",\"value\":\"self-contained\"},\"settings.token.refresh-token-time-to-live\":[\"java.time.Duration\",3600.000000000],\"settings.token.authorization-code-time-to-live\":[\"java.time.Duration\",300.000000000],\"settings.token.device-code-time-to-live\":[\"java.time.Duration\",300.000000000]}"); return registerRepository.save(entity); } ​ 사용 등록 테스트 ​ 사용 등록 엔드포인트인 “/register” 엔드포인트에 접근 후 3자 플랫폼 사용 신청을 진행하겠습니다. - ClientName : yummi - ClientSecret : secret - RedirectUri : http://localhost:8080/login/oauth2/code/yummi - LogoutRedirectUri : http://localhost:8080 - scope : profile 3자 플랫폼에서 로그인 진행 가정 테스트 ​ 3자 플랫폼에서 소셜 로그인 버튼을 클릭했다고 가정하고 그때 생성되는 uri를 만들어 테스트하겠습니다. ​ http://localhost:9000/oauth2/authorize?response_type=code&client_id=등록아이디&scope=profile&redirect_uri=http://localhost:8080/login/oauth2/code/yummi ​ 위 주소로 요청시 인가 서버의 로그인창이 발생합니다. 이때 3자 플랫폼 등록시 설정한 “client_id, redirect_uri, scope”를 모두 알맞게 지정해야 합니다. 로그인 진행 ​ 3강에서 진행한 회원 가입한 아이디로 로그인을 성공하시면 위에서 설정한 redirect_uri로 토큰이 발급됩니다. 토큰 발급 테스트 ​ POSTMAN이라는 API 클라이언트를 활용하여 CODE로 부터 토큰을 발급하겠습니다. ​ ​ ​ 발급한 토큰 BASE 64 해독 ​ 과연 claim에는 어떤 정보가 있을까요. 이전 : 9. 토큰 발급부 https://youtu.be/BcytWifSbgk 271, 이번 시리즈는 스프링 OAuth2 인가 서버에서 이어집니다. OAuth2 인가 서버를 통해 발급 받은 토큰을 검증하여 리소스를 제공하는 스프링 OAuth2 리소스 서버를 구축하는 프로젝트입니다. ​ 스프링 OAuth2 리소스 서버 ​ 1. 실습 목표 및 간단 동작 원리 2. 프로젝트 생성 및 의존성 추가 3. 토큰 디코더 4. 리소스 응답 5. 시연 ​ 코드 ​ https://github.com/xxxjjhhh/spring_oauth2_resource_server 272, 스프링 OAuth2 리소스 서버 > 1. 실습 목표 및 간단 동작 원리 실습 목표 ​ OAuth2 인가 서버에 이어서, OAuth2 Resource 서버와 스프링 시큐리티 6 프레임워크를 활용하여 인가 서버에서 발급한 토큰을 검증하여 3자 플랫폼에게 리소스를 응답해주는 OAuth2 리소스 서버를 구축하는 것이 목표입니다. 구현 ​ 이전 시리즈 : OAuth2 인가 서버 (네이버나 구글의 OAuth2 로그인을 제공하는 것과 동일한 개념) ​ 이번 시리즈 : OAuth2 리소스 서버 (위에서 인가 JWT를 발급 받은 후 유저와 같은 데이터를 받는 부분) ​ 다음 시리즈 : OAuth2 클라이언트를 통해 우리가 구현한 위 서버에 연결 (스프링 OAuth2 클라이언트 세션 시리즈를 통해 우리가 직접 만든 OAuth2 서버에 사용 신청) ​ OAuth2 객체간 상호 작용 ​ OAuth2 인가 서버, OAuth2 리소스 서버, OAuth2 클라이언트 간의 상호 작용 ​ ​ OAuth2 리소스 서버 동작 원리 ​ 리소스 서버는 인가 서버에서 발급한 토큰을 검증하여 접근 권한을 부여하는 방식으로 동작됩니다. 이때 인가 서버에서 토큰을 비대칭키의 비밀키를 통해 만들었기 때문에 리소스 서버에서는 인가 서버에서 공개하는 공개키를 통해 토큰을 검증할 수 있습니다. 버전 및 의존성 ​ - 스프링 부트 : 3.3.4 - 스프링 Resource Server : 6.3.3 - 스프링 시큐리티 : 6.3.4 - Lombok ​ 다음 : 2. 프로젝트 생성 및 의존성 추가 https://youtu.be/ozgMOFwpg5I 273, 스프링 OAuth2 리소스 서버 > 2. 프로젝트 생성 및 의존성 추가 의존성 ​ https://start.spring.io/ {"_links":{"gradle-project":{"href":"https://start.spring.io/starter.zip?type=gradle-project{&dependencies,packaging,javaVersion,language,bootVersion,groupId,artifactId,version,name,description,packageName}","templated":true},"gradle-project-kotlin":{"href":"https://start.spring.io/starter.zip?type=... start.spring.io ​ - 시리즈 의존성 - Spring Web - Spring Security - OAuth2 Resource Server - Lombok ​ application.properites 설정 ​ - 포트 설정 server.port=9001 ​ 이전 : 1. 실습 목표 및 간단 동작 원리 다음 : 3. 토큰 디코더 https://youtu.be/28v8wKlfKQQ 274, 스프링 OAuth2 리소스 서버 > 3. 토큰 디코더 리소스 서버의 목적 ​ 리소스 서버는 인가 서버가 발급한 토큰을 검증하여 리소스를 응답하기 때문에 토큰 검증을 위한 jwtDecoder가 요구됩니다. ​ ​ 토큰 Decoder Bean 등록 ​ 토큰은 비대칭키 중 비밀키를 통해 인코딩을 진행하기 때문에 공개키로 디코딩하는 검증 작업을 수행해야 합니다. ​ 비대칭키 중 공개키는 인가 서버의 엔드포인트를 통해 확인할 수 있기 때문에 리소스 서버에서 토큰 DecoderBean 등록시 인가 서버의 주소를 바라보면 됩니다. 스프링 OAuth2 리소스 서버에서 기본적으로 제공하는 Decoder Bean을 등록하도록 하겠습니다. - SecurityConfig @Configuration @EnableWebSecurity public class SecurityConfig { @Bean public JwtDecoder jwtDecoder() { return JwtDecoders.fromIssuerLocation("http://localhost:9000"); } } ​ 이전 : 2. 프로젝트 생성 및 의존성 추가 다음 : 4. 리소스 응답 https://youtu.be/X3oAJTQXYZw 275, 스프링 OAuth2 리소스 서버 > 4. 리소스 응답 profile : 유저 응답 ​ 보통 OAuth2 인가, 리소스 서버의 경우 소셜 로그인으로 많이 활용합니다. 3자 플랫폼이 설정한 profile scope를 통해 유저 정보를 응답 받게 됩니다. 이번 시간에는 해당 유저 정보를 응답하는 엔드포인트와 권한 설정을 진행하겠습니다. 응답 데이터 형식 ​ { response={username=개발자유미, email=xxxjjhhh@naver.com} } ​ 응답 DTO 구성 ​ - ResDTO @Getter @Setter public class ResDTO { private String username; } ​ - ResWrapper​ @Getter @Setter public class ResWrapper { private ResDTO response; } ​ 응답 엔드포인트 ​ @RestController public class MainController { @GetMapping("/me") public ResWrapper me() { ResDTO resDTO = new ResDTO(); resDTO.setUsername(SecurityContextHolder.getContext().getAuthentication().getName()); ResWrapper resWrapper = new ResWrapper(); resWrapper.setResponse(resDTO); return resWrapper; } } ​ 아주 간단하게 SecurityContextHolder에 저장되어 있는 username 값을 꺼내어 응답했지만, 실제 서비스에서는 SecurityContextHolder에 저장되어 있는 username 값을 기반으로 DB에 쿼리를 날린 뒤 더 많은 정보를 응답하도록 구현할 수 있습니다. ​ profile 접근 권한 인가 처리 ​ - SecurityConfig @Bean public SecurityFilterChain resourceServer(HttpSecurity http) throws Exception { http .oauth2ResourceServer((resource) -> resource.jwt(Customizer.withDefaults())); http .authorizeHttpRequests((auth) -> auth .requestMatchers("/me").hasAuthority("SCOPE_profile") .requestMatchers("/admin").hasAnyAuthority("SCOPE_admin", "ROLE_ADMIN") .anyRequest().authenticated() ); http .sessionManagement(session -> session .sessionCreationPolicy(SessionCreationPolicy.STATELESS)); return http.build(); } ​ hasAuthority() 메소드를 통해 SCOPE 접두사에 대한 인가 설정을 진행할 수 있습니다. 기존의 ROLE_접두사와 같이 사용할 경우 hasAnyAuthority() 메소드를 사용할 수 있습니다. ​ 이전 : 3. 토큰 디코더 다음 : 5. 시연 https://youtu.be/Tl3BDziCjQQ 276, 스프링 OAuth2 리소스 서버 > 5. 시연 인가 서버 토큰 발급 ​ OAuth2 인가 서버에서 “3자 플랫폼 사용 등록” → “소셜 로그인 진행” → “코드 발급” → “토큰 발급” 과정을 통해 Access JWT를 발급 받겠습니다. 기타 OAuth2 인가 서버 관련 자세한 시연 영상 : 스프링 OAuth2 인가 서버 : 10. 시연 ​ - 사용등록 스프링 OAuth2 인가 서버 시리즈에서 사용등록한 client_id, client_secret를 사용하겠습니다. - 소셜 로그인 진행 → 코드 발급 http://localhost:9000/oauth2/authorize?response_type=code&client_id=등록아이디&scope=profile&redirect_uri=http://localhost:8080/login/oauth2/code/yummi ​ - 토큰 발급 ​ 리소스 서버 접근 ​ 위에서 발급 받은 Access JWT를 헤더에 추가한 뒤 리소스 서버 엔드포인트에 접근하여 유저 정보를 획득하겠습니다. ​ ​ 이때 JWT는 요청시 헤더의 Authorization 키에 Bearer 접두사와 공백을 붙여 전송하면 됩니다. ​ ​ 이전 : 4. 리소스 응답 https://youtu.be/yLtgRYMIQuk 277, 신뢰성 있는 서비스에서 로그인하여 인증을 받고, 그 권한을 인가 받아 세션을 생성하는 스프링 시큐리티 OAuth2 소셜 로그인 프로젝트입니다. ​ 스프링 OAuth2 클라이언트 ​ 1. 실습 목표 및 간단한 동작 원리 2. 프로젝트 생성 및 의존성 추가 3. 동작 원리 4. OAuth2 변수 역할 5. SecurityConfig 등록 6. 네이버 소셜 로그인 신청 7. 구글 소셜 로그인 신청 8. OAuth2UserService 응답 받기 9. 응답 데이터로 로그인 완료 10. 유저 정보 DB 저장 11. 커스텀 로그인 페이지 ​ 스프링 OAuth2 클라이언트 심화 ​ 12. ClientRegistration 13. OAuth2AuthorizationRequestRedirectFilter 14. OAuth2LoginAuthenticationFilter 15. OAuth2AuthorizedClientService ​ 코드 ​ 1강 ~ 10강 코드 파일 바로가기 ​ 278, 스프링 OAuth2 클라이언트 세션 > 1. 실습 목표 및 간단한 동작 원리 실습 목표 ​ OAuth2.0 클라이언트와 스프링 시큐리티 6 프레임워크를 활용하여 신뢰할 수 있는 외부 사이트(구글, 네이버)로 부터 인증을 받고 전달 받은 유저 데이터를 활용하여 세션을 만들고 인가를 진행하는 방법. ​ 인증 받은 데이터는 MySQL 데이터베이스를 활용하여 저장하고 관리한다. 구현 ​ - 인증 : 네이버 소셜 로그인, 구글 소셜 로그인 (코드 방식) - 인가 : 세션 방식을 통한 경로별 접근 권한 - 인증 정보 DB 저장 후 추가 정보 기입 OAuth2.0 인증 방식 시큐리티 동작 원리 ​ - 인증 서버와 자원 서버 및 우리의 서버 (코드 방식) ​ 버전 및 의존성 ​ - Spring boot 3.2.1 - Spring Security 6.2.1 - OAuth2 Client - Lombok - Spring Data JPA - MySQL - Gradle - Groovy - IntelliJ Ultimate 기타 ​ OAuth2.0 코드 방식 인증을 활용합니다. 인증 후 발급된 정보로 세션을 만들고 SSR 방식으로 모든 페이지를 응답합니다. 소셜 로그인을 통해 인증 받은 데이터는 우리의 서비스 데이터베이스에 저장을 한 뒤 관리를 진행해야 합니다. 관리를 하지 않고 인증만 받고 사용할 수 있지만 추가적인 사용자 정보나 어떠한 사용자가 우리의 서비스를 활용하는지 확인하기 위해서는 무조건 관리하는 것을 추천 드립니다. 구현적인 부분과 간단한 동작 로직을 먼저 작성한 뒤 내부 동작 로직을 알려드리겠습니다. 다음 : 2. 프로젝트 생성 및 의존성 추가 https://youtu.be/ulb4eNSqCPs?si=OxMW6iNHbAM0KOP8 279, 스프링 OAuth2 클라이언트 세션 > 2. 프로젝트 생성 및 의존성 추가 의존성 ​ https://start.spring.io/ {"_links":{"gradle-project":{"href":"https://start.spring.io/starter.zip?type=gradle-project{&dependencies,packaging,javaVersion,language,bootVersion,groupId,artifactId,version,name,description,packageName}","templated":true},"gradle-project-kotlin":{"href":"https://start.spring.io/starter.zip?type=... start.spring.io ​ - 필수 의존성 - Lombok - Spring Web - Mustache - Spring Security - OAuth2 Client - Spring Data JPA - MySQL Driver ​ 데이터베이스 의존성 주석 처리 ​ 임시로 주석 처리 진행 (스프링 부트에서 데이터베이스 의존성을 추가한 뒤 연결을 진행하지 않을 경우 런타임 에러 발생) 기본 컨트롤러 및 VIEW 생성 ​ - MainController import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ResponseBody; @Controller @ResponseBody public class MainController { @GetMapping("/") public String mainPage() { return "main"; } } ​ - main.mustache​ Document main page ​ - MyController @Controller @ResponseBody public class MyController { @GetMapping("/my") public String myPage() { return "my"; } } ​ - my.mustache​ Document my page ​ 이전 : 1. 실습 목표 및 간단한 동작 원리 다음 : 3. 동작 원리 https://youtu.be/5sHRtJ2wgyw 280, 스프링 OAuth2 클라이언트 세션 > 3. 동작 원리 동작 모식도 : OAuth2 코드 방식 ​ ​ 각각의 필터가 동작하는 주소 (관습) ​ - OAuth2AuthorizationRequestRedirectFilter /oauth2/authorization/서비스명 /oauth2/authorization/naver /oauth2/authorization/google ​ - OAuth2LoginAuthenticationFilter : 외부 인증 서버에 설정할 redirect_uri /login/oauth2/code/서비스명 /login/oauth2/code/naver /login/oauth2/code/google ​ OAuth2 인증 및 동작을 위한 변수들 ​ 변수 설정만 진행하면 OAuth2AuthorizationRequestRedirectFilter → OAuth2LoginAuthenticationFilter → OAuth2LoginAuthenticationProvider 까지의 과정을 추가 설정하지 않아도 자동으로 진행한다. 따라서 사용자는 UserDetailsService와 UserDetails만 구현하면 됩니다. - application.properties spring.security.oauth2.client.registration.서비스명.client-name= spring.security.oauth2.client.registration.서비스명.client-id= spring.security.oauth2.client.registration.서비스명.client-secret= spring.security.oauth2.client.registration.서비스명.redirect-uri= spring.security.oauth2.client.registration.서비스명.authorization-grant-type= spring.security.oauth2.client.registration.서비스명.scope= spring.security.oauth2.client.provider.서비스명.authorization-uri= spring.security.oauth2.client.provider.서비스명.token-uri= spring.security.oauth2.client.provider.서비스명.user-info-uri= spring.security.oauth2.client.provider.서비스명.user-name-attribute= ​ 앞으로 영상에서 위의 변수를 가지고 설정을 진행합니다. ​ 우리가 구현해야 할 부분 ​ - OAuth2UserDetailsService - OAuth2UserDetails ​ 참고 ​ - OAuth2AuthorizationRequestRedirectFilter OAuth2AuthorizationRequestRedirectFilter (6.2.1) 스프링 공식 API Docs 바로가기 - OAuth2LoginAuthenticationFilter OAuth2LoginAuthenticationFilter (6.2.1) 스프링 공식 API Docs 바로가기 - OAuth2LoginAuthenticationProvider OAuth2LoginAuthenticationProvider (6.2.1) 스프링 공식 API Docs 바로가기 ​ 이전 : 2. 프로젝트 생성 및 의존성 추가 다음 : 4. OAuth2 변수 역할 https://youtu.be/db85S6CmRzg 281, 스프링 OAuth2 클라이언트 세션 > 4. OAuth2 변수 역할 OAuth2 소셜 로그인을 위한 변수 설정 ​ 위의 각각의 로직이 동작을 하기 위해서는 서비스별로 특정 값이 필요하기 때문에 변수 설정이 필요합니다. - application.properties #registration spring.security.oauth2.client.registration.서비스명.client-name=서비스명 spring.security.oauth2.client.registration.서비스명.client-id=서비스에서 발급 받은 아이디 spring.security.oauth2.client.registration.서비스명.client-secret=서비스에서 발급 받은 비밀번호 spring.security.oauth2.client.registration.서비스명.redirect-uri=서비스에 등록한 우리쪽 로그인 성공 URI spring.security.oauth2.client.registration.서비스명.authorization-grant-type=authorization_code spring.security.oauth2.client.registration.서비스명.scope=리소스 서버에서 가져올 데이터 범위 #provider spring.security.oauth2.client.provider.서비스명.authorization-uri=서비스 로그인 창 주소 spring.security.oauth2.client.provider.서비스명.token-uri=토큰 발급 서버 주소 spring.security.oauth2.client.provider.서비스명.user-info-uri=사용자 정보 획득 주소 spring.security.oauth2.client.provider.서비스명.user-name-attribute=응답 데이터 변수 ​ - 예시 #registration spring.security.oauth2.client.registration.naver.client-name=naver spring.security.oauth2.client.registration.naver.client-id=발급아이디 spring.security.oauth2.client.registration.naver.client-secret=발급비밀번호 spring.security.oauth2.client.registration.naver.redirect-uri=http://localhost:8080/login/oauth2/code/naver spring.security.oauth2.client.registration.naver.authorization-grant-type=authorization_code spring.security.oauth2.client.registration.naver.scope=name,email #provider spring.security.oauth2.client.provider.naver.authorization-uri=https://nid.naver.com/oauth2.0/authorize spring.security.oauth2.client.provider.naver.token-uri=https://nid.naver.com/oauth2.0/token spring.security.oauth2.client.provider.naver.user-info-uri=https://openapi.naver.com/v1/nid/me spring.security.oauth2.client.provider.naver.user-name-attribute=response ​ registration과 provider ​ registration은 외부 서비스에서 우리 서비스를 특정하기 위해 등록하는 정보여서 등록이 필수적입니다. ​ 하지만 provider의 경우 서비스별로 정해진 값이 존재하며 OAuth2 클라이언트 의존성이 유명한 서비스의 경우 내부적으로 데이터를 가지고 있습니다. ​ (구글, Okta, 페이스북, 깃허브, 등등) ​ 이전 : 3. 동작 원리 다음 : 5. SecurityConfig 등록 https://youtu.be/w3lXqNiHwik?si=soEV0zg10F-z5meP 282, 스프링 OAuth2 클라이언트 세션 > 5. SecurityConfig 등록 SecurityConfig ​ - config > SecurityConfig.java @Configuration @EnableWebSecurity public class SecurityConfig { @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http .csrf((csrf) -> csrf.disable()); http .formLogin((login) -> login.disable()); http .httpBasic((basic) -> basic.disable()); http .oauth2Login(Customizer.withDefaults()); http .authorizeHttpRequests((auth) -> auth .requestMatchers("/", "/oauth2/**", "/login/**").permitAll() .anyRequest().authenticated()); return http.build(); } } ​ 이전 : 4. OAuth2 변수 역할 다음 : 6. 네이버 소셜 로그인 신청 https://youtu.be/JxvlYELHNnU 283, 스프링 OAuth2 클라이언트 세션 > 6. 네이버 소셜 로그인 신청a 네이버 로그인 API 공식 문서 바로가기 네이버 로그인 API 신청 ​ 네이버 개발자 센터 -> 네이버 로그인 API ​ ​ ClientID와 Client Secret를 스프링 부트 application.properties OAuth2 변수에 설정하면 됩니다. ​ 변수 설정 ​ - application.properties #registration spring.security.oauth2.client.registration.naver.client-name=naver spring.security.oauth2.client.registration.naver.client-id= spring.security.oauth2.client.registration.naver.client-secret= spring.security.oauth2.client.registration.naver.redirect-uri=http://localhost:8080/login/oauth2/code/naver spring.security.oauth2.client.registration.naver.authorization-grant-type=authorization_code spring.security.oauth2.client.registration.naver.scope=name,email #provider spring.security.oauth2.client.provider.naver.authorization-uri=https://nid.naver.com/oauth2.0/authorize spring.security.oauth2.client.provider.naver.token-uri=https://nid.naver.com/oauth2.0/token spring.security.oauth2.client.provider.naver.user-info-uri=https://openapi.naver.com/v1/nid/me spring.security.oauth2.client.provider.naver.user-name-attribute=response ​ 이전 : 5. SecurityConfig 등록 다음 : 7. 구글 소셜 로그인 신청 https://youtu.be/L8yAtjjOhDo 284, 스프링 OAuth2 클라이언트 세션 > 7. 구글 소셜 로그인 신청 구글 GCP 바로가기 구글 OAuth2 클라이언트 신청 ​ ​ 구글 OAuth2 소셜 로그인을 사용하기 위해서는 GCP 가입이 필수적입니다. ​ ​ “API 사용자 인증 정보” 접근 ​ ​ 검색을 통해 “API 및 서비스”에 접근하면 좌측 카테고리에서 “OAuth 동의 화면”괴 “사용자 인증 정보” 설정을 통해 사용할 수 있습니다. ​ 변수 설정 ​ - application.properties #registration spring.security.oauth2.client.registration.google.client-name=google spring.security.oauth2.client.registration.google.client-id= spring.security.oauth2.client.registration.google.client-secret= spring.security.oauth2.client.registration.google.redirect-uri=http://localhost:8080/login/oauth2/code/google spring.security.oauth2.client.registration.google.authorization-grant-type=authorization_code spring.security.oauth2.client.registration.google.scope=profile,email ​ 이전 : 6. 네이버 소셜 로그인 신청 다음 : 8. OAuth2UserService 응답 받기 https://youtu.be/VFvlivlhoMo 285, 스프링 OAuth2 클라이언트 세션 > 8. OAuth2UserService 응답 받기 OAuth2UserService ​ - CustomOAuth2UserService @Service public class CustomOAuth2UserService extends DefaultOAuth2UserService { //DefaultOAuth2UserService OAuth2UserService의 구현체 @Override public OAuth2User loadUser(OAuth2UserRequest userRequest) throws OAuth2AuthenticationException { OAuth2User oAuth2User = super.loadUser(userRequest); System.out.println(oAuth2User.getAttributes()); String registrationId = userRequest.getClientRegistration().getRegistrationId(); OAuth2Response oAuth2Response = null; if (registrationId.equals("naver")) { oAuth2Response = new NaverResponse(oAuth2User.getAttributes()); } else if (registrationId.equals("google")) { oAuth2Response = new GoogleReponse(oAuth2User.getAttributes()); } else { return null; } //추후 작성 } } ​ OAuth2Response ​ - 네이버 데이터 : JSON { resultcode=00, message=success, response={id=123123123, name=개발자유미} } ​ - 구글 데이터 : JSON { resultcode=00, message=success, id=123123123, name=개발자유미 } ​ - DTO > 인터페이스 OAuth2Response public interface OAuth2Response { //제공자 (Ex. naver, google, ...) String getProvider(); //제공자에서 발급해주는 아이디(번호) String getProviderId(); //이메일 String getEmail(); //사용자 실명 (설정한 이름) String getName(); } ​ - dto > NaverResponse public class NaverResponse implements OAuth2Response{ private final Map attribute; public NaverResponse(Map attribute) { this.attribute = (Map) attribute.get("response"); } @Override public String getProvider() { return "naver"; } @Override public String getProviderId() { return attribute.get("id").toString(); } @Override public String getEmail() { return attribute.get("email").toString(); } @Override public String getName() { return attribute.get("name").toString(); } } ​ - dto > GoogleResponse public class GoogleReponse implements OAuth2Response{ private final Map attribute; public GoogleReponse(Map attribute) { this.attribute = attribute; } @Override public String getProvider() { return "google"; } @Override public String getProviderId() { return attribute.get("sub").toString(); } @Override public String getEmail() { return attribute.get("email").toString(); } @Override public String getName() { return attribute.get("name").toString(); } } ​ OAuth2UserService 등록 : SecurityConfig ​ - SecurityConfig @Configuration @EnableWebSecurity public class SecurityConfig { private final CustomOAuth2UserService customOAuth2UserService; public SecurityConfig(CustomOAuth2UserService customOAuth2UserService) { this.customOAuth2UserService = customOAuth2UserService; } @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http .csrf((csrf) -> csrf.disable()); http .formLogin((login) -> login.disable()); http .httpBasic((basic) -> basic.disable()); http .oauth2Login((oauth2) -> oauth2 .userInfoEndpoint((userInfoEndpointConfig) -> userInfoEndpointConfig .userService(customOAuth2UserService))); http .authorizeHttpRequests((auth) -> auth .requestMatchers("/").permitAll() .anyRequest().authenticated()); return http.build(); } } ​ 이전 : 7. 구글 소셜 로그인 신청 다음 : 9. 응답 데이터로 로그인 완료 https://youtu.be/bMkYibr4BaM 286, 스프링 OAuth2 클라이언트 세션 > 9. 응답 데이터로 로그인 완료 8강 까지 구현한 CustomOAuth2UserService ​ @Service public class CustomOAuth2UserService extends DefaultOAuth2UserService { //DefaultOAuth2UserService OAuth2UserService의 구현체 @Override public OAuth2User loadUser(OAuth2UserRequest userRequest) throws OAuth2AuthenticationException { OAuth2User oAuth2User = super.loadUser(userRequest); System.out.println(oAuth2User.getAttributes()); String registrationId = userRequest.getClientRegistration().getRegistrationId(); OAuth2Response oAuth2Response = null; if (registrationId.equals("naver")) { oAuth2Response = new NaverResponse(oAuth2User.getAttributes()); } else if (registrationId.equals("google")) { oAuth2Response = new GoogleReponse(oAuth2User.getAttributes()); } else { return null; } //추후 작성 } } ​ 나머지 CustomOAuth2UserService ​ @Service public class CustomOAuth2UserService extends DefaultOAuth2UserService { //DefaultOAuth2UserService OAuth2UserService의 구현체 @Override public OAuth2User loadUser(OAuth2UserRequest userRequest) throws OAuth2AuthenticationException { OAuth2User oAuth2User = super.loadUser(userRequest); System.out.println(oAuth2User.getAttributes()); String registrationId = userRequest.getClientRegistration().getRegistrationId(); OAuth2Response oAuth2Response = null; if (registrationId.equals("naver")) { oAuth2Response = new NaverResponse(oAuth2User.getAttributes()); } else if (registrationId.equals("google")) { oAuth2Response = new GoogleReponse(oAuth2User.getAttributes()); } else { return null; } String role = "ROLE_USER"; return new CustomOAuth2User(oAuth2Response, role); } } ​ CustomOAuth2User 생성 ​ package com.example.testvideo.dto; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.oauth2.core.user.OAuth2User; import java.util.ArrayList; import java.util.Collection; import java.util.Map; public class CustomOAuth2User implements OAuth2User { private final OAuth2Response oAuth2Response; private final String role; public CustomOAuth2User(OAuth2Response oAuth2Response, String role) { this.oAuth2Response = oAuth2Response; this.role = role; } @Override public Map getAttributes() { return null; } @Override public Collection getAuthorities() { Collection collection = new ArrayList<>(); collection.add(new GrantedAuthority() { @Override public String getAuthority() { return role; } }); return collection; } @Override public String getName() { return oAuth2Response.getName(); } public String getUsername() { return oAuth2Response.getProvider()+" "+oAuth2Response.getProviderId(); } } ​ 이전 : 8. OAuth2UserService 응답 받기 다음 : 10. 유저 정보 DB 저장 https://youtu.be/jT9qBPPSwFs 287, 스프링 OAuth2 클라이언트 세션 > 10. 유저 정보 DB 저장 ​ ​ DB관련 의존성 주석 해제 ​ - build.gradle dependencies { //implementation 'org.springframework.boot:spring-boot-starter-data-jpa' //runtimeOnly 'com.mysql:mysql-connector-j' } ​ DB 연결 변수 작성 ​ - application.properties spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver spring.datasource.url=jdbc:mysql://아이피:3306/데이터베이스?useSSL=false&useUnicode=true&serverTimezone=Asia/Seoul&allowPublicKeyRetrieval=true spring.datasource.username=아이디 spring.datasource.password=비밀번호 spring.jpa.hibernate.ddl-auto=none spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl ​ UserEntity 생성 ​ - entity > UserEntity @Entity @Getter @Setter public class UserEntity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String username; private String email; private String role; } ​ UserRepository 생성 ​ - repository > UserRepository public interface UserRepository extends JpaRepository { UserEntity findByUsername(String username); } ​ CustomOAuth2UserService 유저 정보 DB 저장 로직 작성 ​ - service > CustomOAuth2UserService @Service public class CustomOAuth2UserService extends DefaultOAuth2UserService { //DefaultOAuth2UserService OAuth2UserService의 구현체 private final UserRepository userRepository; public CustomOAuth2UserService(UserRepository userRepository) { this.userRepository = userRepository; } @Override public OAuth2User loadUser(OAuth2UserRequest userRequest) throws OAuth2AuthenticationException { OAuth2User oAuth2User = super.loadUser(userRequest); System.out.println(oAuth2User.getAttributes()); String registrationId = userRequest.getClientRegistration().getRegistrationId(); OAuth2Response oAuth2Response = null; if (registrationId.equals("naver")) { oAuth2Response = new NaverResponse(oAuth2User.getAttributes()); } else if (registrationId.equals("google")) { oAuth2Response = new GoogleReponse(oAuth2User.getAttributes()); } else { return null; } String username = oAuth2Response.getProvider()+" "+oAuth2Response.getProviderId(); UserEntity existData = userRepository.findByUsername(username); String role = "ROLE_USER"; if (existData == null) { UserEntity userEntity = new UserEntity(); userEntity.setUsername(username); userEntity.setEmail(oAuth2Response.getEmail()); userEntity.setRole(role); userRepository.save(userEntity); } else { existData.setUsername(username); existData.setEmail(oAuth2Response.getEmail()); role = existData.getRole(); userRepository.save(existData); } return new CustomOAuth2User(oAuth2Response, role); } } ​ 영상 중 오류 사항 : 수정 완료 ​ 오류 사항 건의 감사드립니다. ​ ​ 이전 : 9. 응답 데이터로 로그인 완료 다음 : 11. 커스텀 로그인 페이지 https://youtu.be/CY_QrS26Euk 288, 스프링 OAuth2 클라이언트 세션 > 11. 커스텀 로그인 페이지 기본 OAuth2 로그인 페이지 ​ GET : /login ​ ​ 커스텀 로그인 페이지 설정 ​ - login.mustache

login page


naver login
google login ​ - controller > LoginController @Controller public class LoginController { @GetMapping("/login") public String loginPage() { return "login"; } } ​ SecurityConfig OAuth2 커스텀 로그인 페이지 등록 ​ - config > SecurityConfig http .oauth2Login((oauth2) -> oauth2 .loginPage("/login") .userInfoEndpoint((userInfoEndpointConfig) -> userInfoEndpointConfig.userService(customOAuth2UserService))); ​ 이전 : 10. 유저 정보 DB 저장 다음 : 12. ClientRegistration https://youtu.be/FqEdiOGZmn0 289, 스프링 OAuth2 클라이언트 세션 > 12. ClientRegistration 자료 ​ - ClientRegistration ClientRegistration (6.2.1) 스프링 공식 API 문서 바로가기 - ClientRegistrationRepository ClientRegistrationRepository (6.2.1) 스프링 공식 API 문서 바로가기 ​ OAuth2 서비스 변수 등록 방법 ​ 기존에 application.properties 변수 설정 파일에서 설정했던 소셜 로그인 제공 서비스에 대한 정보 기입을 관련 클래스를 통해 직접 진행하는 방법. ​ 앞으로 커스텀을 진행하기 위해 클래스를 직접 구현하는 것이 필수적이다. - ClientRegistration 서비스별 OAuth2 클라이언트의 등록 정보를 가지는 클래스다. ​ - ClientRegistrationRepository ClientRegistration의 저장소로 서비스별 ClientRegistration들을 가진다. 변수 설정 주석 ​ application.properties에 설정한 oauth2 관련 변수를 모두 주석 처리한 뒤 아래 클래스를 작성한다. ClientRegistration 생성 ​ - oauth2 > ClientRegistration @Component public class SocialClientRegistration { public ClientRegistration naverClientRegistration() { return ClientRegistration.withRegistrationId("naver") .clientId("아이디") .clientSecret("비밀번호") .redirectUri("http://localhost:8080/login/oauth2/code/naver") .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE) .scope("name", "email") .authorizationUri("https://nid.naver.com/oauth2.0/authorize") .tokenUri("https://nid.naver.com/oauth2.0/token") .userInfoUri("https://openapi.naver.com/v1/nid/me") .userNameAttributeName("response") .build(); } public ClientRegistration googleClientRegistration() { return ClientRegistration.withRegistrationId("google") .clientId("아이디") .clientSecret("비밀번호") .redirectUri("http://localhost:8080/login/oauth2/code/google") .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE) .scope("profile", "email") .authorizationUri("https://accounts.google.com/o/oauth2/v2/auth") .tokenUri("https://www.googleapis.com/oauth2/v4/token") .jwkSetUri("https://www.googleapis.com/oauth2/v3/certs") .issuerUri("https://accounts.google.com") .userInfoUri("https://www.googleapis.com/oauth2/v3/userinfo") .userNameAttributeName(IdTokenClaimNames.SUB) .build(); } } ​ - oauth2 > ClientRegistrationRepository @Configuration public class CustomClientRegistrationRepo { private final SocialClientRegistration socialClientRegistration; public CustomClientRegistrationRepo(SocialClientRegistration socialClientRegistration) { this.socialClientRegistration = socialClientRegistration; } public ClientRegistrationRepository clientRegistrationRepository() { return new InMemoryClientRegistrationRepository(socialClientRegistration.naverClientRegistration(), socialClientRegistration.googleClientRegistration()); } } ​ InMemoryClientRegistrationRepository 클래스를 사용하여 인메모리 방식으로 관리를 진행한다. ​ SecurityConfig 등록 ​ - config > SecurityConfig @Configuration @EnableWebSecurity public class SecurityConfig { private final CustomOAuth2UserService customOAuth2UserService; private final CustomClientRegistrationRepo customClientRegistrationRepo; public SecurityConfig(CustomOAuth2UserService customOAuth2UserService, CustomClientRegistrationRepo customClientRegistrationRepo) { this.customOAuth2UserService = customOAuth2UserService; this.customClientRegistrationRepo = customClientRegistrationRepo; } @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http .csrf((csrf) -> csrf.disable()); http .formLogin((login) -> login.disable()); http .httpBasic((basic) -> basic.disable()); http .oauth2Login((oauth2) -> oauth2 .clientRegistrationRepository(customClientRegistrationRepo.clientRegistrationRepository()) .userInfoEndpoint((userInfoEndpointConfig) -> userInfoEndpointConfig.userService(customOAuth2UserService))); http .authorizeHttpRequests((auth) -> auth .requestMatchers("/", "/oauth2/**", "/login/**").permitAll() .anyRequest().authenticated()); return http.build(); } } ​ 이전 : 11. 커스텀 로그인 페이지 다음 : 13. OAuth2AuthorizationRequestRedirectFilter https://youtu.be/cn3a8b2Gt8k 290, 스프링 OAuth2 클라이언트 세션 > 13. OAuth2AuthorizationRequestRedirectFilter 로그인 페이지에서 : /oauth2/authorization/서비스 ​ ​ 로그인 페이지에서 GET : /oauth2/authorization/서비스 경로로 요청을 할 경우 OAuth2 의존성에 의해 OAuth2AuthorizationRequestRedirectFilter에서 해당 요청을 받고 내부 프로세서를 진행한다. ​ ​ OAuth2AuthorizationRequestRedirectFilter는 요청을 받은 후 해당하는 서비스의 로그인 URI로 요청을 리디렉션 시킨다. (이때 서비스의 정보는 지난 시간 등록한 ClientRegistrationRepository에서 가져온다.) ​ OAuth2AuthorizationRequestRedirectFilter ​ - OAuth2AuthorizationRequestRedirectFilter public class OAuth2AuthorizationRequestRedirectFilter extends OncePerRequestFilter { public static final String DEFAULT_AUTHORIZATION_REQUEST_BASE_URI = "/oauth2/authorization"; private final ThrowableAnalyzer throwableAnalyzer = new DefaultThrowableAnalyzer(); private RedirectStrategy authorizationRedirectStrategy = new DefaultRedirectStrategy(); private OAuth2AuthorizationRequestResolver authorizationRequestResolver; private AuthorizationRequestRepository authorizationRequestRepository = new HttpSessionOAuth2AuthorizationRequestRepository(); private RequestCache requestCache = new HttpSessionRequestCache(); //아래 생성자들 public OAuth2AuthorizationRequestRedirectFilter(ClientRegistrationRepository clientRegistrationRepository) { this(clientRegistrationRepository, DEFAULT_AUTHORIZATION_REQUEST_BASE_URI); } public OAuth2AuthorizationRequestRedirectFilter(ClientRegistrationRepository clientRegistrationRepository, String authorizationRequestBaseUri) { Assert.notNull(clientRegistrationRepository, "clientRegistrationRepository cannot be null"); Assert.hasText(authorizationRequestBaseUri, "authorizationRequestBaseUri cannot be empty"); this.authorizationRequestResolver = new DefaultOAuth2AuthorizationRequestResolver(clientRegistrationRepository, authorizationRequestBaseUri); } public OAuth2AuthorizationRequestRedirectFilter(OAuth2AuthorizationRequestResolver authorizationRequestResolver) { Assert.notNull(authorizationRequestResolver, "authorizationRequestResolver cannot be null"); this.authorizationRequestResolver = authorizationRequestResolver; } public void setAuthorizationRedirectStrategy(RedirectStrategy authorizationRedirectStrategy) { Assert.notNull(authorizationRedirectStrategy, "authorizationRedirectStrategy cannot be null"); this.authorizationRedirectStrategy = authorizationRedirectStrategy; } //OAuth2 유저 저정소 setter public final void setAuthorizationRequestRepository( AuthorizationRequestRepository authorizationRequestRepository) { Assert.notNull(authorizationRequestRepository, "authorizationRequestRepository cannot be null"); this.authorizationRequestRepository = authorizationRequestRepository; } public final void setRequestCache(RequestCache requestCache) { Assert.notNull(requestCache, "requestCache cannot be null"); this.requestCache = requestCache; } //아래 리디렉션을 위한 메소드들 @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { try { OAuth2AuthorizationRequest authorizationRequest = this.authorizationRequestResolver.resolve(request); if (authorizationRequest != null) { this.sendRedirectForAuthorization(request, response, authorizationRequest); return; } } catch (Exception ex) { this.unsuccessfulRedirectForAuthorization(request, response, ex); return; } try { filterChain.doFilter(request, response); } catch (IOException ex) { throw ex; } catch (Exception ex) { // Check to see if we need to handle ClientAuthorizationRequiredException Throwable[] causeChain = this.throwableAnalyzer.determineCauseChain(ex); ClientAuthorizationRequiredException authzEx = (ClientAuthorizationRequiredException) this.throwableAnalyzer .getFirstThrowableOfType(ClientAuthorizationRequiredException.class, causeChain); if (authzEx != null) { try { OAuth2AuthorizationRequest authorizationRequest = this.authorizationRequestResolver.resolve(request, authzEx.getClientRegistrationId()); if (authorizationRequest == null) { throw authzEx; } this.requestCache.saveRequest(request, response); this.sendRedirectForAuthorization(request, response, authorizationRequest); } catch (Exception failed) { this.unsuccessfulRedirectForAuthorization(request, response, failed); } return; } if (ex instanceof ServletException) { throw (ServletException) ex; } if (ex instanceof RuntimeException) { throw (RuntimeException) ex; } throw new RuntimeException(ex); } } private void sendRedirectForAuthorization(HttpServletRequest request, HttpServletResponse response, OAuth2AuthorizationRequest authorizationRequest) throws IOException { if (AuthorizationGrantType.AUTHORIZATION_CODE.equals(authorizationRequest.getGrantType())) { this.authorizationRequestRepository.saveAuthorizationRequest(authorizationRequest, request, response); } this.authorizationRedirectStrategy.sendRedirect(request, response, authorizationRequest.getAuthorizationRequestUri()); } private void unsuccessfulRedirectForAuthorization(HttpServletRequest request, HttpServletResponse response, Exception ex) throws IOException { LogMessage message = LogMessage.format("Authorization Request failed: %s", ex); if (InvalidClientRegistrationIdException.class.isAssignableFrom(ex.getClass())) { // Log an invalid registrationId at WARN level to allow these errors to be // tuned separately from other errors this.logger.warn(message, ex); } else { this.logger.error(message, ex); } response.sendError(HttpStatus.INTERNAL_SERVER_ERROR.value(), HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase()); } private static final class DefaultThrowableAnalyzer extends ThrowableAnalyzer { @Override protected void initExtractorMap() { super.initExtractorMap(); registerExtractor(ServletException.class, (throwable) -> { ThrowableAnalyzer.verifyThrowableHierarchy(throwable, ServletException.class); return ((ServletException) throwable).getRootCause(); }); } } } ​ 이전 : 12. ClientRegistration 다음 : 14. OAuth2LoginAuthenticationFilter https://youtu.be/cpx0VUA8Q1c 291, 스프링 OAuth2 클라이언트 세션 > 14. OAuth2LoginAuthenticationFilter 로그인 성공 redirect_uri 필터 : /login/oauth2/code/서비스명 ​ ​ OAuth2LoginAuthenticationFilter는 인증 서버에서 로그인을 성공한 뒤 우리 서버측으로 발급되는 CODE를 획득하고, CODE를 통해 Access 토큰과 User 정보를 획득하는 OAuth2LoginAuthenticationProvider를 호출하는 일련의 과정을 시작하는 필터입니다. OAuth2LoginAuthenticationFilter ​ OAuth2LoginAuthenticationFilter는 /login/oauth2/code/서비스명 경로에 대해서 CODE를 받는 필터입니다. 이후 검증을 진행하고 완료되면 OAuth2LoginAuthenticationProvider를 호출합니다. ​ public class OAuth2LoginAuthenticationFilter extends AbstractAuthenticationProcessingFilter { public static final String DEFAULT_FILTER_PROCESSES_URI = "/login/oauth2/code/*"; private static final String AUTHORIZATION_REQUEST_NOT_FOUND_ERROR_CODE = "authorization_request_not_found"; private static final String CLIENT_REGISTRATION_NOT_FOUND_ERROR_CODE = "client_registration_not_found"; private ClientRegistrationRepository clientRegistrationRepository; private OAuth2AuthorizedClientRepository authorizedClientRepository; private AuthorizationRequestRepository authorizationRequestRepository = new HttpSessionOAuth2AuthorizationRequestRepository(); private Converter authenticationResultConverter = this::createAuthenticationResult; //아래 생성자들 public OAuth2LoginAuthenticationFilter(ClientRegistrationRepository clientRegistrationRepository, OAuth2AuthorizedClientService authorizedClientService) { this(clientRegistrationRepository, authorizedClientService, DEFAULT_FILTER_PROCESSES_URI); } public OAuth2LoginAuthenticationFilter(ClientRegistrationRepository clientRegistrationRepository, OAuth2AuthorizedClientService authorizedClientService, String filterProcessesUrl) { this(clientRegistrationRepository, new AuthenticatedPrincipalOAuth2AuthorizedClientRepository(authorizedClientService), filterProcessesUrl); } public OAuth2LoginAuthenticationFilter(ClientRegistrationRepository clientRegistrationRepository, OAuth2AuthorizedClientRepository authorizedClientRepository, String filterProcessesUrl) { super(filterProcessesUrl); Assert.notNull(clientRegistrationRepository, "clientRegistrationRepository cannot be null"); Assert.notNull(authorizedClientRepository, "authorizedClientRepository cannot be null"); this.clientRegistrationRepository = clientRegistrationRepository; this.authorizedClientRepository = authorizedClientRepository; } //CODE를 획득하고 OAuth2LoginAuthenticationProvider를 호출하는 메소드 @Override public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException { MultiValueMap params = OAuth2AuthorizationResponseUtils.toMultiMap(request.getParameterMap()); if (!OAuth2AuthorizationResponseUtils.isAuthorizationResponse(params)) { OAuth2Error oauth2Error = new OAuth2Error(OAuth2ErrorCodes.INVALID_REQUEST); throw new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString()); } OAuth2AuthorizationRequest authorizationRequest = this.authorizationRequestRepository .removeAuthorizationRequest(request, response); if (authorizationRequest == null) { OAuth2Error oauth2Error = new OAuth2Error(AUTHORIZATION_REQUEST_NOT_FOUND_ERROR_CODE); throw new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString()); } String registrationId = authorizationRequest.getAttribute(OAuth2ParameterNames.REGISTRATION_ID); ClientRegistration clientRegistration = this.clientRegistrationRepository.findByRegistrationId(registrationId); if (clientRegistration == null) { OAuth2Error oauth2Error = new OAuth2Error(CLIENT_REGISTRATION_NOT_FOUND_ERROR_CODE, "Client Registration not found with Id: " + registrationId, null); throw new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString()); } // @formatter:off String redirectUri = UriComponentsBuilder.fromHttpUrl(UrlUtils.buildFullRequestUrl(request)) .replaceQuery(null) .build() .toUriString(); // @formatter:on OAuth2AuthorizationResponse authorizationResponse = OAuth2AuthorizationResponseUtils.convert(params, redirectUri); Object authenticationDetails = this.authenticationDetailsSource.buildDetails(request); OAuth2LoginAuthenticationToken authenticationRequest = new OAuth2LoginAuthenticationToken(clientRegistration, new OAuth2AuthorizationExchange(authorizationRequest, authorizationResponse)); authenticationRequest.setDetails(authenticationDetails); OAuth2LoginAuthenticationToken authenticationResult = (OAuth2LoginAuthenticationToken) this .getAuthenticationManager() .authenticate(authenticationRequest); OAuth2AuthenticationToken oauth2Authentication = this.authenticationResultConverter .convert(authenticationResult); Assert.notNull(oauth2Authentication, "authentication result cannot be null"); oauth2Authentication.setDetails(authenticationDetails); OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient( authenticationResult.getClientRegistration(), oauth2Authentication.getName(), authenticationResult.getAccessToken(), authenticationResult.getRefreshToken()); this.authorizedClientRepository.saveAuthorizedClient(authorizedClient, oauth2Authentication, request, response); return oauth2Authentication; } public final void setAuthorizationRequestRepository( AuthorizationRequestRepository authorizationRequestRepository) { Assert.notNull(authorizationRequestRepository, "authorizationRequestRepository cannot be null"); this.authorizationRequestRepository = authorizationRequestRepository; } public final void setAuthenticationResultConverter( Converter authenticationResultConverter) { Assert.notNull(authenticationResultConverter, "authenticationResultConverter cannot be null"); this.authenticationResultConverter = authenticationResultConverter; } private OAuth2AuthenticationToken createAuthenticationResult(OAuth2LoginAuthenticationToken authenticationResult) { return new OAuth2AuthenticationToken(authenticationResult.getPrincipal(), authenticationResult.getAuthorities(), authenticationResult.getClientRegistration().getRegistrationId()); } } ​ OAuth2LoginAuthenticationProvider ​ OAuth2LoginAuthenticationFilter로 부터 호출 받아 전달 받은 정보를 통해 외부 인증 서버를 호출하여 Access 토큰을 발급 받습니다. ​ 이후 Access 토큰을 통해 외부 리소스 서버에서 유저 정보를 OAuth2UserService로 받습니다. ​ public class OAuth2LoginAuthenticationProvider implements AuthenticationProvider { private final OAuth2AuthorizationCodeAuthenticationProvider authorizationCodeAuthenticationProvider; private final OAuth2UserService userService; private GrantedAuthoritiesMapper authoritiesMapper = ((authorities) -> authorities); //생성자 public OAuth2LoginAuthenticationProvider( OAuth2AccessTokenResponseClient accessTokenResponseClient, OAuth2UserService userService) { Assert.notNull(userService, "userService cannot be null"); this.authorizationCodeAuthenticationProvider = new OAuth2AuthorizationCodeAuthenticationProvider( accessTokenResponseClient); this.userService = userService; } //Access 토큰을 요청하고, Access 토큰을 가지고 유저 정보를 요청하는 메소드 @Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { OAuth2LoginAuthenticationToken loginAuthenticationToken = (OAuth2LoginAuthenticationToken) authentication; // Section 3.1.2.1 Authentication Request - // https://openid.net/specs/openid-connect-core-1_0.html#AuthRequest scope // REQUIRED. OpenID Connect requests MUST contain the "openid" scope value. if (loginAuthenticationToken.getAuthorizationExchange() .getAuthorizationRequest() .getScopes() .contains("openid")) { // This is an OpenID Connect Authentication Request so return null // and let OidcAuthorizationCodeAuthenticationProvider handle it instead return null; } OAuth2AuthorizationCodeAuthenticationToken authorizationCodeAuthenticationToken; try { authorizationCodeAuthenticationToken = (OAuth2AuthorizationCodeAuthenticationToken) this.authorizationCodeAuthenticationProvider .authenticate( new OAuth2AuthorizationCodeAuthenticationToken(loginAuthenticationToken.getClientRegistration(), loginAuthenticationToken.getAuthorizationExchange())); } catch (OAuth2AuthorizationException ex) { OAuth2Error oauth2Error = ex.getError(); throw new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString(), ex); } OAuth2AccessToken accessToken = authorizationCodeAuthenticationToken.getAccessToken(); Map additionalParameters = authorizationCodeAuthenticationToken.getAdditionalParameters(); OAuth2User oauth2User = this.userService.loadUser(new OAuth2UserRequest( loginAuthenticationToken.getClientRegistration(), accessToken, additionalParameters)); Collection mappedAuthorities = this.authoritiesMapper .mapAuthorities(oauth2User.getAuthorities()); OAuth2LoginAuthenticationToken authenticationResult = new OAuth2LoginAuthenticationToken( loginAuthenticationToken.getClientRegistration(), loginAuthenticationToken.getAuthorizationExchange(), oauth2User, mappedAuthorities, accessToken, authorizationCodeAuthenticationToken.getRefreshToken()); authenticationResult.setDetails(loginAuthenticationToken.getDetails()); return authenticationResult; } public final void setAuthoritiesMapper(GrantedAuthoritiesMapper authoritiesMapper) { Assert.notNull(authoritiesMapper, "authoritiesMapper cannot be null"); this.authoritiesMapper = authoritiesMapper; } @Override public boolean supports(Class authentication) { return OAuth2LoginAuthenticationToken.class.isAssignableFrom(authentication); } } ​ 이전 : 13. OAuth2AuthorizationRequestRedirectFilter 다음 : 15. OAuth2AuthorizedClientService https://youtu.be/jKAaPLXNuq8 292, 스프링 OAuth2 클라이언트 세션 > 15. OAuth2AuthorizedClientService OAuth2AuthorizedClientService ​ OAuth2 소셜 로그인을 진행하는 사용자에 대해 우리의 서버는 인증 서버에서 발급 받은 Access 토큰과 같은 정보를 담을 저장소가 필요하다. 기본적으로 인메모리 방식으로 관리되는데 소셜 로그인 사용자 수가 증가하고 서버의 스케일 아웃 문제로 인해 인메모리 방식은 실무에서 사용하지 않는다. 따라서 DB에 해당 정보를 저장하기 위해서는 OAuth2AuthorizedClientService를 직접 작성해야 한다. JDBC 의존성 추가 ​ JDBC 방식을 지원하기 때문에 JDBC 모듈이 필요하고 JPA를 사용하고 싶은 경우 전부 커스텀해서 만들어야 한다. - build.gradle dependencies { implementation 'org.springframework.boot:spring-boot-starter-jdbc' } ​ OAuth2AuthorizedClientService 클래스 생성 ​ - oauth2 > CustomOAuth2AuthorizedClientService @Configuration public class CustomOAuth2AuthorizedClientService { public OAuth2AuthorizedClientService oAuth2AuthorizedClientService(JdbcTemplate jdbcTemplate, ClientRegistrationRepository clientRegistrationRepository) { return new JdbcOAuth2AuthorizedClientService(jdbcTemplate ,clientRegistrationRepository); } } ​ return new를 통해 Jdbc 방식 JdbcOAuth2AuthorizedClientService() 클래스를 응답 ​ SecurityConfig 등록 ​ @Configuration @EnableWebSecurity public class SecurityConfig { private final CustomOAuth2UserService customOAuth2UserService; private final CustomClientRegistrationRepo customClientRegistrationRepo; private final CustomOAuth2AuthorizedClientService customOAuth2AuthorizedClientService; private final JdbcTemplate jdbcTemplate; public SecurityConfig(CustomOAuth2UserService customOAuth2UserService, CustomClientRegistrationRepo customClientRegistrationRepo, CustomOAuth2AuthorizedClientService customOAuth2AuthorizedClientService, JdbcTemplate jdbcTemplate) { this.customOAuth2UserService = customOAuth2UserService; this.customClientRegistrationRepo = customClientRegistrationRepo; this.customOAuth2AuthorizedClientService = customOAuth2AuthorizedClientService; this.jdbcTemplate = jdbcTemplate; } @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http .csrf((csrf) -> csrf.disable()); http .formLogin((login) -> login.disable()); http .httpBasic((basic) -> basic.disable()); http .oauth2Login((oauth2) -> oauth2 .loginPage("/login") .clientRegistrationRepository(customClientRegistrationRepo.clientRegistrationRepository()) .authorizedClientService(customOAuth2AuthorizedClientService.oAuth2AuthorizedClientService(jdbcTemplate, customClientRegistrationRepo.clientRegistrationRepository())) .userInfoEndpoint((userInfoEndpointConfig) -> userInfoEndpointConfig.userService(customOAuth2UserService))); http .authorizeHttpRequests((auth) -> auth .requestMatchers("/", "/login/**", "/oauth2/**").permitAll() .anyRequest().authenticated()); return http.build(); } } ​ JdbcOAuth2AuthorizedClientService 클래스 ​ 해당 클래스 : 스프링 시큐리티 공식 깃허브 바로가기 ​ 데이터베이스에 해당 테이블 생성 ​ 우리가 사용하는 MySQL 데이터베이스에 OAuth2AuthorizedClientService가 사용할 테이블이 존재해야 한다. 아래 명령어를 통해 테이블을 생성할 수 있다. ​ CREATE TABLE oauth2_authorized_client ( client_registration_id varchar(100) NOT NULL, principal_name varchar(200) NOT NULL, access_token_type varchar(100) NOT NULL, access_token_value blob NOT NULL, access_token_issued_at timestamp NOT NULL, access_token_expires_at timestamp NOT NULL, access_token_scopes varchar(1000) DEFAULT NULL, refresh_token_value blob DEFAULT NULL, refresh_token_issued_at timestamp DEFAULT NULL, created_at timestamp DEFAULT CURRENT_TIMESTAMP NOT NULL, PRIMARY KEY (client_registration_id, principal_name) ); ​ 실행 결과 ​ ​ 의문사항 ​ (client_registration_id, principal_name)가 겹치는 경우가 존재하면 테이블에 값이 오버 라이팅되는 현상이 발생하는데 운영 환경에서 발생하는 문제가 없을지 의문점이 든다. - 예시 user : username / client_registration_id / principal_name user1 : bbbbbbbb / naver / 개발자유미 user2 : aaaaaaaaa / naver / 개발자유미 ​ 위와 같이 client_registration_id와 principal_name이 겹칠 경우 새로운 row가 생성되지 않고 기존 데이터 위에 덮어 씌어짐 ​ 만약 해당 경우가 동시에 로그인을 진행한다면 로그인이 실패할 수 있을거 같다. (Access 토큰을 발급 받고 추후에 사용하지는 않지만, 동시에 로그인을 진행한다면 오류가 발생할 수 있지 않을까.) 따라서 스프링 시큐리티 공식 깃허브에 Issue로 질문을 했고, 개발자측에서 OAuth2AuthorizedClientService를 알아서 구현해서 사용하라고 답변이 왔습니다. ​ ​ 이전 : 14. OAuth2LoginAuthenticationFilter https://youtu.be/NAGoCwc6iBg 293, 신뢰성 있는 서비스에서 로그인하여 인증을 받고, 그 권한을 인가 받아 JWT를 발급하는 스프링 시큐리티 OAuth2 소셜 로그인 프로젝트입니다. ​ 스프링 OAuth2 클라이언트 JWT ​ 1. 실습 목표 2. 동작 원리와 프론트/백 책임 분배 3. 프로젝트 생성 및 의존성 추가 4. 동작 원리 5. OAuth2 변수 역할 6. SecurityConfig 등록 7. 네이버 소셜 로그인 신청 8. 구글 소셜 로그인 신청 9. OAuth2UserService 응답 받기 10. OAuth2UserService 완료 11. 유저 정보 DB 저장 12. JWT 발급 및 검증 클래스 13. 로그인 성공 JWT 발급 14. JWT 검증 필터 15. CORS 설정 16. 리액트에서 요청 17. 재로그인 무한 루프 오류 18. 아이디어 ​ 코드 ​ 1강 ~ 15강 코드 파일 ​ ​ ​ 294, 스프링 OAuth2 클라이언트 JWT > 1. 실습 목표 실습 목표 ​ OAuth2.0 클라이언트와 스프링 시큐리티 6 프레임워크를 활용하여 신뢰할 수 있는 외부 사이트(구글, 네이버)로 부터 인증을 받고 전달 받은 유저 데이터를 활용하여 JWT를 발급하고 인가를 진행하는 방법. ​ 인증 받은 데이터는 MySQL 데이터베이스를 활용하여 저장하고 관리한다. 구현 ​ API 서버 형태로 구현을 진행합니다. ​ - 인증 : 네이버/구글 소셜 로그인 (코드 방식) 후 JWT 발급 - 인가 : JWT를 통한 경로별 접근 권한 - 인증 정보 DB 저장 후 추가 정보 기입 수반되는 시리즈 ​ 이번 시리즈는 아래 3가지 시리즈를 시청하신 후 따라하시는 것을 권장드립니다. 스프링 시큐리티 : 개발자 유미 재생 목록 바로가기 스프링 시큐리티 JWT : 개발자 유미 재생 목록 바로가기 스프링 OAuth2 클라이언트 세션 : 개발자 유미 재생 목록 바로가기 1. 세션과 JWT 방식의 차이점을 알고 각각의 사용처에 대해서 명확히 알고 시작하셔야 합니다. 2. 세션 방식의 구현과 JWT 방식의 구현을 대략적으로 알고 진행하셔야 합니다. 3. 시큐리티 내부 동작 원리를 어느정도 알고 있어야 합니다. 4. OAuth2를 활용한 CODE 방식의 소셜 로그인 동작 방식을 알고 있어야 합니다. 버전 및 의존성 ​ - Spring boot 3.2.2 - Spring Security 6.2.2 - OAuth2 Client - Lombok - Spring Data JPA - MySQL - JJWT 0.12.3 - Gradle - Groovy - IntelliJ Ultimate 기타 ​ - OAuth2.0 코드 방식 인증을 활용합니다. - 인증 후 발급된 정보로 JWT를 발급합니다. - JWT의 경우 단일 토큰으로 진행합니다. - 소셜 로그인을 통해 인증 받은 데이터는 우리의 서비스 데이터베이스에 저장을 한 뒤 관리를 진행해야 합니다. 관리를 하지 않고 인증만 받고 사용할 수 있지만 추가적인 사용자 정보나 어떠한 사용자가 우리의 서비스를 활용하는지 확인하기 위해서는 무조건 관리하는 것을 추천 드립니다. - 제 코드는 OAuth2 클라이언트 JWT방식을 구현하기 위한 가장 기본적인 뼈대 코드로 이 시리즈가 발판이 되어 여러분들이 더 좋은 결과물을 만드셨으면 좋겠습니다! ​ 다음 : 2. 동작 원리와 프론트/백 책임 분배 https://youtu.be/xsmKOo-sJ3c?si=LIDlwG0Hggx22_Bq 296, 스프링 OAuth2 클라이언트 JWT > 2. 동작 원리와 프론트/백 책임 분배 OAuth2 Code Grant 방식의 동작 순서 ​ 1. 로그인 페이지 2. 성공 후 코드 발급 (redirect_url) 3. 코드를 통해 Access 토큰 요청 4. Access 토큰 발급 완료 5. Access 토큰을 통해 유저 정보 요청 6. 유저 정보 획득 완료 세션 방식에서 OAuth2 클라이언트 동작 원리 ​ ​ 세션 방식에서는 로직을 구성하는데 큰 고민 없이 진행할 수 있다. 로그인이 성공하면 세션을 생성하면 앞으로의 요청에 대해서도 사용자를 알아챌 수 있다. ​ JWT 방식에서 OAuth2 클라이언트 구성시 고민점 ​ JWT 방식에서는 로그인(인증)이 성공하면 JWT 발급 문제와 웹/하이브리드/네이티브앱별 특징에 의해 OAuth2 Code Grant 방식 동작의 책임을 프론트엔드 측에 둘 것인지 백엔드 측에 둘 것인지 많은 고민을 한다. - 로그인(인증)이 성공하면 JWT를 발급해야 하는 문제 - 프론트단에서 로그인 경로에 대한 하이퍼링크를 실행하면 소셜 로그인창이 등장하고 로그인 로직이 수행된다. - 로그인이 성공되면 JWT가 발급되는데 하이퍼링크로 실행했기 때문에 JWT를 받을 로직이 없다. (해당 부분에 대해 redirect_url 설정에 따라 많은 고민이 필요합니다.) - API Client(axios, fetch)로 요청 보내면 백엔드측으로 요청이 전송되지만 외부 서비스 로그인 페이지를 확인할 수 없다. - 웹/하이브리드/네이티브앱별 특징 - 웹에서 편하게 사용할 수 있는 웹페이지가 앱에서는 웹뷰로 보이기 때문에 UX적으로 안좋은 경험을 가질 수 있다. - 앱 환경에서 쿠키 소멸 현상 위와 같은 문제로 OAuth2 Code Grant 방식 동작에 대한 redirect_url, Access 토큰 발급 문제를 어느단에서 처리해야 하는지에 대한 구현이 많고 넷상에 잘못된 구현 방법도 많이 있다. 잘못된 구현 방법과 구현되어 있는 모든 방법을 아래에서 알아보자. 프론트/백 책임 분배 (웹에서) ​ - 모든 책임을 프론트가 맡음 ​ 프론트단에서 (로그인 → 코드 발급 → Access 토큰 → 유저 정보 획득) 과정을 모두 수행한 뒤 백엔드단에서 (유저 정보 → JWT 발급) 방식으로 주로 네이티브앱에서 사용하는 방식. → 프론트에서 보낸 유저 정보의 진위 여부를 따지기 위해 추가적인 보안 로직이 필요하다. - 책임을 프론트와 백엔드가 나누어 가짐 : 잘못된 방식 (대부분의 웹 블로그가 이 방식으로 구현) - 프론트단에서 (로그인 → 코드 발급) 후 코드를 백엔드로 전송 백엔드단에서 (코드 → 토큰 발급 → 유저 정보 획득 → JWT 발급) ​ - 프론트단에서 (로그인 → 코드 발급 → Access 토큰) 후 Access 토큰을 백엔드로 전송 백엔드단에서 (Access 토큰 → 유저 정보 획득 → JWT 발급) ​ 카카오와 같은 대형 서비스 개발 포럼 및 보안 규격에서 위와 같은 코드/Access 토큰을 전송하는 방법을 지양함. (하지만 토이로 구현하기 쉬워 자주 사용한다.) ​ - 모든 책임을 백엔드가 맡음​ ​ 프론트단에서 백엔드의 OAuth2 로그인 경로로 하이퍼링킹을 진행 후 백엔드단에서 (로그인 페이지 요청 → 코드 발급 → Access 토큰 → 유저 정보 획득 → JWT 발급) 방식으로 주로 웹앱/모바일앱 통합 환경 서버에서 사용하는 방식. → 백엔드에서 JWT를 발급하는 방식의 고민과 프론트측에서 받는 로직을 처리해야 한다. ​ 우리가 구현할 방식 ​ 우리 채널은 백엔드에 초점이 맞춰져 있기 때문에 모든 책임을 백엔드에서 맡아 (로그인 페이지 요청 → 코드 발급 → Access 토큰 → 유저 정보 획득 → JWT 발급)에 대한 로직을 모두 스프링 쪽에서 처리하도록 하겠습니다. 카카오 dev톡에 적혀 있는 프론트/백 책임 분배 ​ 구글링을 통해 카카오 dev 톡에 적혀 있는 프론트와 백엔드가 책임을 나눠 가지는 질문에 대한 카카오 공식 답변입니다. ​ ​ 앱에 대해서는 모든 책임을 프론트가 일임하고 코드나 Access 토큰을 전달하는 행위 자체를 지양합니다. 추가적으로 다른 자료들에도 코드나 Access 토큰을 전달하는 행위를 금지하고 있습니다. ​ 이전 : 1. 실습 목표 다음 : 3. 프로젝트 생성 및 의존성 추가 https://youtu.be/6XZ8oJOex_U 297, 스프링 OAuth2 클라이언트 JWT > 3. 프로젝트 생성 및 의존성 추가 의존성 ​ start.spring.io 스프링 Initializr 바로가기 - 필수 의존성 - Lombok - Spring Web - Spring Security - OAuth2 Client - Spring Data JPA - MySQL Driver 데이터베이스 의존성 주석 처리 ​ 임시로 주석 처리 진행 (스프링 부트에서 데이터베이스 의존성을 추가한 뒤 연결을 진행하지 않을 경우 런타임 에러 발생) ​ JWT 필수 의존성 ​ JWT 토큰을 생성하고 관리하기 위해 JWT 의존성을 필수적으로 설정해야 합니다. 설정은 build.gradle을 통해 진행하며 이때 버전을 선택하여 적용해야 합니다. 대부분은 JWT 0.11.5 버전을 통해 구현하지만 최신 버전은 0.12.3입니다. 따라서 0.12.3을 기반으로 구현합니다. (JWT를 생성하고 내부에서 데이터를 얻는 메소드가 버전마다 많이 상이합니다.) JWT 0.11.5 버전과 0.12.3 버전에 대한 자세한 내용은 “스프링 시큐리티 JWT” 시리즈에서 확인하실 수 있습니다. 스프링 시큐리티 JWT : 개발자 유미 시리즈 바로가기 - 0.12.3 : build.gradle dependencies { implementation 'io.jsonwebtoken:jjwt-api:0.12.3' implementation 'io.jsonwebtoken:jjwt-impl:0.12.3' implementation 'io.jsonwebtoken:jjwt-jackson:0.12.3' } ​ - 0.11.5 : build.gradle dependencies { implementation 'io.jsonwebtoken:jjwt-api:0.11.5' implementation 'io.jsonwebtoken:jjwt-impl:0.11.5' implementation 'io.jsonwebtoken:jjwt-jackson:0.11.5' } ​ - 의존성 BOM Maven Repository : jjwt 0.12.3 : 바로가기 Maven Repository : jjwt 0.11.5 : 바로가기 ​ 기본 Controller 생성 ​ - MainController import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ResponseBody; @Controller public class MainController { @GetMapping("/") @ResponseBody public String mainAPI() { return "main route"; } } ​ - MyController import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ResponseBody; @Controller public class MyController { @GetMapping("/my") @ResponseBody public String myAPI() { return "my route"; } } ​ 이전 : 2. 동작 원리와 프론트/백 책임 분배 다음 : 4. 동작 원리 https://youtu.be/BY-HWViE_l4 298, 스프링 OAuth2 클라이언트 JWT > 4. 동작 원리 동작 모식도 ​ ​ 각각의 필터가 동작하는 주소 ​ - JWTFilter : 우리가 커스텀해서 등록해야 함 모든 주소에서 동작 ​ - OAuth2AuthorizationRequestRedirectFilter /oauth2/authorization/서비스명 /oauth2/authorization/naver /oauth2/authorization/google ​ - OAuth2LoginAuthenticationFilter : 외부 인증 서버에 설정할 redirect_uri /login/oauth2/code/서비스명 /login/oauth2/code/naver /login/oauth2/code/google ​ OAuth2 클라이언트에서 우리가 구현해야 할 부분 ​ - OAuth2UserDetailsService - OAuth2UserDetails - LoginSuccessHandler JWT에서 우리가 구현해야 할 부분 ​ - JWTFilter - JWTUtil : JWT를 발급 및 검증하는 클래스 참고 ​ - OAuth2AuthorizationRequestRedirectFilter OAuth2AuthorizationRequestRedirectFilter : 스프링 (6.2.1) API 문서 바로가기 - OAuth2LoginAuthenticationFilter OAuth2LoginAuthenticationFilter : 스프링 (6.2.1) API 문서 바로가기 - OAuth2LoginAuthenticationProvider OAuth2LoginAuthenticationProvider : 스프링 (6.2.1) API 문서 바로가기 - OAuth2 클라이언트 세션 OAuth2 클라이언트 세션 : 개발자 유미 재생목록 바로가기 - JWT 스프링 시큐리티 JWT : 개발자 유미 재생목록 바로가기 ​ 이전 : 3. 프로젝트 생성 및 의존성 추가 다음 : 5. OAuth2 변수 역할 https://youtu.be/JQJVHcI7Rzo 299, 스프링 OAuth2 클라이언트 JWT > 5. OAuth2 변수 역할 OAuth2 소셜 로그인을 위한 변수 설정 ​ 위의 각각의 로직이 동작을 하기 위해서는 서비스별로 설정 값이 필요하기 때문에 변수 설정이 필요합니다. - application.properties #registration spring.security.oauth2.client.registration.서비스명.client-name=서비스명 spring.security.oauth2.client.registration.서비스명.client-id=서비스에서 발급 받은 아이디 spring.security.oauth2.client.registration.서비스명.client-secret=서비스에서 발급 받은 비밀번호 spring.security.oauth2.client.registration.서비스명.redirect-uri=서비스에 등록한 우리쪽 로그인 성공 URI spring.security.oauth2.client.registration.서비스명.authorization-grant-type=authorization_code spring.security.oauth2.client.registration.서비스명.scope=리소스 서버에서 가져올 데이터 범위 #provider spring.security.oauth2.client.provider.서비스명.authorization-uri=서비스 로그인 창 주소 spring.security.oauth2.client.provider.서비스명.token-uri=토큰 발급 서버 주소 spring.security.oauth2.client.provider.서비스명.user-info-uri=사용자 정보 획득 주소 spring.security.oauth2.client.provider.서비스명.user-name-attribute=응답 데이터 변수 ​ - 예시 #registration spring.security.oauth2.client.registration.naver.client-name=naver spring.security.oauth2.client.registration.naver.client-id=발급아이디 spring.security.oauth2.client.registration.naver.client-secret=발급비밀번호 spring.security.oauth2.client.registration.naver.redirect-uri=http://localhost:8080/login/oauth2/code/naver spring.security.oauth2.client.registration.naver.authorization-grant-type=authorization_code spring.security.oauth2.client.registration.naver.scope=name,email #provider spring.security.oauth2.client.provider.naver.authorization-uri=https://nid.naver.com/oauth2.0/authorize spring.security.oauth2.client.provider.naver.token-uri=https://nid.naver.com/oauth2.0/token spring.security.oauth2.client.provider.naver.user-info-uri=https://openapi.naver.com/v1/nid/me spring.security.oauth2.client.provider.naver.user-name-attribute=response ​ registration과 provider ​ registration은 외부 서비스에서 우리 서비스를 특정하기 위해 등록하는 정보여서 등록이 필수적입니다. ​ 하지만 provider의 경우 서비스별로 정해진 값이 존재하며 OAuth2 클라이언트 의존성이 유명한 서비스의 경우 내부적으로 데이터를 가지고 있습니다. ​ (구글, Okta, 페이스북, 깃허브, 등등) Registration에 관한 추가 사항 ​ - 변수 역할 (세션 시리즈에서 촬영 : 현재 내용과 거의 동일) 스프링 OAuth2 클라이언트 세션 4 : 변수 설정 - ClientRegistration 클래스 스프링 OAuth2 클라이언트 세션 12 : ClientRegistration ​ 이전 : 4. 동작 원리 다음 : 6. SecurityConfig 등록 https://youtu.be/sUuc0XW2te4 300, 스프링 OAuth2 클라이언트 JWT > 6. SecurityConfig 등록 SecurityConfig ​ OAuth2 클라이언트 JWT 설정을 위한 SecurityConfig 클래스의 일부분을 작성할 예정입니다. 먼저 기본적인 설정만 진행하고 시리즈를 진행하며 커스텀 필터 요소들을 추가 구현할 예정입니다. - config > SecurityConfig @Configuration @EnableWebSecurity public class SecurityConfig { @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { //csrf disable http .csrf((auth) -> auth.disable()); //From 로그인 방식 disable http .formLogin((auth) -> auth.disable()); //HTTP Basic 인증 방식 disable http .httpBasic((auth) -> auth.disable()); //oauth2 http .oauth2Login(Customizer.withDefaults()); //경로별 인가 작업 http .authorizeHttpRequests((auth) -> auth .requestMatchers("/").permitAll() .anyRequest().authenticated()); //세션 설정 : STATELESS http .sessionManagement((session) -> session .sessionCreationPolicy(SessionCreationPolicy.STATELESS)); return http.build(); } } ​ 이전 : 5. OAuth2 변수 역할 다음 : 7. 네이버 소셜 로그인 신청 https://youtu.be/NuOLlxPet3w 301, 스프링 OAuth2 클라이언트 JWT > 7. 네이버 소셜 로그인 신청 네이버 로그인 API 공식 문서 바로가기 네이버 로그인 API 신청 ​ 네이버 개발자센터 → 네이버 로그인 API ​ ​ ClientID와 Client Secret를 스프링 부트 application.properties OAuth2 변수에 설정하면 됩니다. ​ 변수 설정 ​ - application.properties #registration spring.security.oauth2.client.registration.naver.client-name=naver spring.security.oauth2.client.registration.naver.client-id= spring.security.oauth2.client.registration.naver.client-secret= spring.security.oauth2.client.registration.naver.redirect-uri=http://localhost:8080/login/oauth2/code/naver spring.security.oauth2.client.registration.naver.authorization-grant-type=authorization_code spring.security.oauth2.client.registration.naver.scope=name,email #provider spring.security.oauth2.client.provider.naver.authorization-uri=https://nid.naver.com/oauth2.0/authorize spring.security.oauth2.client.provider.naver.token-uri=https://nid.naver.com/oauth2.0/token spring.security.oauth2.client.provider.naver.user-info-uri=https://openapi.naver.com/v1/nid/me spring.security.oauth2.client.provider.naver.user-name-attribute=response ​ 네이버 소셜 로그인 요청 경로 ​ GET : /oauth2/authorization/naver ​ 이전 : 6. SecurityConfig 등록 다음 : 8. 구글 소셜 로그인 신청 https://youtu.be/fNEtoPmgUHs 302, 스프링 OAuth2 클라이언트 JWT > 8. 구글 소셜 로그인 신청 구글 GCP 바로가기 구글 OAuth2 클라이언트 신청 ​ 구글 OAuth2 소셜 로그인을 사용하기 위해서는 GCP 가입이 필수적입니다. ​ ​ “API 사용자 인증 정보” 접근 ​ ​ 검색을 통해 “API 및 서비스”에 접근하면 좌측 카테고리에서 “OAuth 동의 화면”괴 “사용자 인증 정보” 설정을 통해 사용할 수 있습니다. ​ 변수 설정 ​ - application.properties #registration spring.security.oauth2.client.registration.google.client-name=google spring.security.oauth2.client.registration.google.client-id= spring.security.oauth2.client.registration.google.client-secret= spring.security.oauth2.client.registration.google.redirect-uri=http://localhost:8080/login/oauth2/code/google spring.security.oauth2.client.registration.google.authorization-grant-type=authorization_code spring.security.oauth2.client.registration.google.scope=profile,email ​ 이전 : 7. 네이버 소셜 로그인 신청 다음 : 9. OAuth2UserService 응답 받기 https://youtu.be/ed10nojCa9g 303, 스프링 OAuth2 클라이언트 JWT > 9. OAuth2UserService 응답 받기 OAuth2UserService ​ - CustomOAuth2UserService @Service public class CustomOAuth2UserService extends DefaultOAuth2UserService { @Override public OAuth2User loadUser(OAuth2UserRequest userRequest) throws OAuth2AuthenticationException { OAuth2User oAuth2User = super.loadUser(userRequest); System.out.println(oAuth2User); String registrationId = userRequest.getClientRegistration().getRegistrationId(); OAuth2Response oAuth2Response = null; if (registrationId.equals("naver")) { oAuth2Response = new NaverResponse(oAuth2User.getAttributes()); } else if (registrationId.equals("google")) { oAuth2Response = new GoogleResponse(oAuth2User.getAttributes()); } else { return null; } //추후 작성 } } ​ OAuth2Response ​ - 네이버 데이터 : JSON { resultcode=00, message=success, response={id=123123123, name=개발자유미} } ​ - 구글 데이터 : JSON { resultcode=00, message=success, id=123123123, name=개발자유미 } ​ - dto > 인터페이스 OAuth2Response public interface OAuth2Response { //제공자 (Ex. naver, google, ...) String getProvider(); //제공자에서 발급해주는 아이디(번호) String getProviderId(); //이메일 String getEmail(); //사용자 실명 (설정한 이름) String getName(); } ​ - dto > NaverResponse public class NaverResponse implements OAuth2Response{ private final Map attribute; public NaverResponse(Map attribute) { this.attribute = (Map) attribute.get("response"); } @Override public String getProvider() { return "naver"; } @Override public String getProviderId() { return attribute.get("id").toString(); } @Override public String getEmail() { return attribute.get("email").toString(); } @Override public String getName() { return attribute.get("name").toString(); } } ​ - dto > GoogleResponse public class GoogleResponse implements OAuth2Response{ private final Map attribute; public GoogleResponse(Map attribute) { this.attribute = attribute; } @Override public String getProvider() { return "google"; } @Override public String getProviderId() { return attribute.get("sub").toString(); } @Override public String getEmail() { return attribute.get("email").toString(); } @Override public String getName() { return attribute.get("name").toString(); } } ​ OAuth2UserService 등록 : SecurityConfig ​ - SecurityConfig @Configuration @EnableWebSecurity public class SecurityConfig { private final CustomOAuth2UserService customOAuth2UserService; public SecurityConfig(CustomOAuth2UserService customOAuth2UserService) { this.customOAuth2UserService = customOAuth2UserService; } @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { //csrf disable http .csrf((auth) -> auth.disable()); //From 로그인 방식 disable http .formLogin((auth) -> auth.disable()); //HTTP Basic 인증 방식 disable http .httpBasic((auth) -> auth.disable()); //oauth2 http .oauth2Login((oauth2) -> oauth2 .userInfoEndpoint((userInfoEndpointConfig) -> userInfoEndpointConfig .userService(customOAuth2UserService))); //경로별 인가 작업 http .authorizeHttpRequests((auth) -> auth .requestMatchers("/").permitAll() .anyRequest().authenticated()); //세션 설정 : STATELESS http .sessionManagement((session) -> session .sessionCreationPolicy(SessionCreationPolicy.STATELESS)); return http.build(); } } ​ 이전 : 8. 구글 소셜 로그인 신청 다음 : 10. OAuth2UserService 완료 https://youtu.be/Sl3A879RS5o 304, 스프링 OAuth2 클라이언트 JWT > 10. OAuth2UserService 완료 9강 까지 구현한 CustomOAuth2UserService ​ @Service public class CustomOAuth2UserService extends DefaultOAuth2UserService { @Override public OAuth2User loadUser(OAuth2UserRequest userRequest) throws OAuth2AuthenticationException { OAuth2User oAuth2User = super.loadUser(userRequest); System.out.println(oAuth2User); String registrationId = userRequest.getClientRegistration().getRegistrationId(); OAuth2Response oAuth2Response = null; if (registrationId.equals("naver")) { oAuth2Response = new NaverResponse(oAuth2User.getAttributes()); } else if (registrationId.equals("google")) { oAuth2Response = new GoogleResponse(oAuth2User.getAttributes()); } else { return null; } //추후 작성 } } ​ 나머지 CustomOAuth2UserService ​ @Service public class CustomOAuth2UserService extends DefaultOAuth2UserService { @Override public OAuth2User loadUser(OAuth2UserRequest userRequest) throws OAuth2AuthenticationException { OAuth2User oAuth2User = super.loadUser(userRequest); System.out.println(oAuth2User); String registrationId = userRequest.getClientRegistration().getRegistrationId(); OAuth2Response oAuth2Response = null; if (registrationId.equals("naver")) { oAuth2Response = new NaverResponse(oAuth2User.getAttributes()); } else if (registrationId.equals("google")) { oAuth2Response = new GoogleResponse(oAuth2User.getAttributes()); } else { return null; } //리소스 서버에서 발급 받은 정보로 사용자를 특정할 아이디값을 만듬 String username = oAuth2Response.getProvider()+" "+oAuth2Response.getProviderId(); UserDTO userDTO = new UserDTO(); userDTO.setUsername(username); userDTO.setName(oAuth2Response.getName()); userDTO.setRole("ROLE_USER"); return new CustomOAuth2User(userDTO); } } ​ UserDTO ​ @Getter @Setter public class UserDTO { private String role; private String name; private String username; } ​ CustomOAuth2User 생성 ​ public class CustomOAuth2User implements OAuth2User { private final UserDTO userDTO; public CustomOAuth2User(UserDTO userDTO) { this.userDTO = userDTO; } @Override public Map getAttributes() { return null; } @Override public Collection getAuthorities() { Collection collection = new ArrayList<>(); collection.add(new GrantedAuthority() { @Override public String getAuthority() { return userDTO.getRole(); } }); return collection; } @Override public String getName() { return userDTO.getName(); } public String getUsername() { return userDTO.getUsername(); } } ​ 이전 : 9. OAuth2UserService 응답 받기 다음 : 11. 유저 정보 DB 저장 https://youtu.be/6WVRXwy4gHg 305, 스프링 OAuth2 클라이언트 JWT > 11. 유저 정보 DB 저장 ​ ​ DB 관련 의존성 주석 해제 ​ - build.gradle dependencies { //implementation 'org.springframework.boot:spring-boot-starter-data-jpa' //runtimeOnly 'com.mysql:mysql-connector-j' } ​ DB 연결 변수 작성 ​ - application.properties spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver spring.datasource.url=jdbc:mysql://아이피:3306/데이터베이스?useSSL=false&useUnicode=true&serverTimezone=Asia/Seoul&allowPublicKeyRetrieval=true spring.datasource.username=아이디 spring.datasource.password=비밀번호 spring.jpa.hibernate.ddl-auto=none spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl ​ UserEntity 생성 ​ - entity > UserEntity @Entity @Getter @Setter public class UserEntity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String username; private String name; private String email; private String role; } ​ UserRepository 생성 ​ - repository > UserRepository public interface UserRepository extends JpaRepository { UserEntity findByUsername(String username); } ​ CustomOAuth2UserService 유저 정보 DB 저장 로직 ​ - service > CustomOAuth2UserService @Service public class CustomOAuth2UserService extends DefaultOAuth2UserService { private final UserRepository userRepository; public CustomOAuth2UserService(UserRepository userRepository) { this.userRepository = userRepository; } @Override public OAuth2User loadUser(OAuth2UserRequest userRequest) throws OAuth2AuthenticationException { OAuth2User oAuth2User = super.loadUser(userRequest); System.out.println(oAuth2User); String registrationId = userRequest.getClientRegistration().getRegistrationId(); OAuth2Response oAuth2Response = null; if (registrationId.equals("naver")) { oAuth2Response = new NaverResponse(oAuth2User.getAttributes()); } else if (registrationId.equals("google")) { oAuth2Response = new GoogleResponse(oAuth2User.getAttributes()); } else { return null; } String username = oAuth2Response.getProvider()+" "+oAuth2Response.getProviderId(); UserEntity existData = userRepository.findByUsername(username); if (existData == null) { UserEntity userEntity = new UserEntity(); userEntity.setUsername(username); userEntity.setEmail(oAuth2Response.getEmail()); userEntity.setName(oAuth2Response.getName()); userEntity.setRole("ROLE_USER"); userRepository.save(userEntity); UserDTO userDTO = new UserDTO(); userDTO.setUsername(username); userDTO.setName(oAuth2Response.getName()); userDTO.setRole("ROLE_USER"); return new CustomOAuth2User(userDTO); } else { existData.setEmail(oAuth2Response.getEmail()); existData.setName(oAuth2Response.getName()); userRepository.save(existData); UserDTO userDTO = new UserDTO(); userDTO.setUsername(existData.getUsername()); userDTO.setName(oAuth2Response.getName()); userDTO.setRole(existData.getRole()); return new CustomOAuth2User(userDTO); } } } ​ OAuth2 관련 부분은 사실상 끝. ​ 중요한 OAuth2 관련 심화 영상은 세션 방식에서 한 번 다루었고 확인 부탁드립니다. 스프링 OAuth2 클라이언트 세션 12 : Client Registration 스프링 OAuth2 클라이언트 세션 13 : OAuth2AuthorizationRequestRedirectFilter 스프링 OAuth2 클라이언트 세션 14 : OAuth2LoginAuthenticationFilter 스프링 OAuth2 클라이언트 세션 15 : OAuth2AuthorizedClientService ​ 이전 : 10. OAuth2UserService 완료 다음 : 12. JWT 발급 및 검증 클래스 https://youtu.be/ItDxZn3SrNE 306, 스프링 OAuth2 클라이언트 JWT > 12. JWT 발급 및 검증 클래스 JWT 발급과 검증 ​ - 로그인시 → 성공 → JWT 발급 - 접근시 → JWT 검증 JWT에 관해 발급과 검증을 담당할 클래스가 필요하다. 따라서 JWTUtil이라는 클래스를 생성하여 JWT 발급, 검증 메소드를 작성하는 시간입니다. ​ JWT 생성 원리 ​ JWT.IO 공식 사이트 바로가기 JWT는 Header.Payload.Signature 구조로 이루어져 있다. 각 요소는 다음 기능을 수행한다. - Header - JWT임을 명시 - 사용된 암호화 알고리즘 - Payload - 정보 - Signature - 암호화알고리즘((BASE64(Header))+(BASE64(Payload)) + 암호화키) JWT의 특징은 내부 정보를 단순 BASE64 방식으로 인코딩하기 때문에 외부에서 쉽게 디코딩 할 수 있다. 외부에서 열람해도 되는 정보를 담아야하며, 토큰 자체의 발급처를 확인하기 위해서 사용한다. (지폐와 같이 외부에서 그 금액을 확인하고 금방 외형을 따라서 만들 수 있지만 발급처에 대한 보장 및 검증은 확실하게 해야하는 경우에 사용한다. 따라서 토큰 내부에 비밀번호와 같은 값 입력 금지) JWT 암호화 방식 ​ - 암호화 종류 - 양방향 - 대칭키 - 이 프로젝트는 양방향 대칭키 방식 사용 : HS256 - 비대칭키 - 단방향 암호화 키 저장 ​ 암호화 키는 하드코딩 방식으로 구현 내부에 탑재하는 것을 지양하기 때문에 변수 설정 파일에 저장한다. - application.properties spring.jwt.secret=vmfhaltmskdlstkfkdgodyroqkfwkdbalroqkfwkdbalaaaaaaaaaaaaaaaabbbbb ​ JWTUtil ​ - 토큰 Payload에 저장될 정보 - username - role - 생성일 - 만료일 - JWTUtil 구현 메소드 - JWTUtil 생성자 - username 확인 메소드 - role 확인 메소드 - 만료일 확인 메소드 - JWTUtil : 0.12.3 @Component public class JWTUtil { private SecretKey secretKey; public JWTUtil(@Value("${spring.jwt.secret}")String secret) { secretKey = new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), Jwts.SIG.HS256.key().build().getAlgorithm()); } public String getUsername(String token) { return Jwts.parser().verifyWith(secretKey).build().parseSignedClaims(token).getPayload().get("username", String.class); } public String getRole(String token) { return Jwts.parser().verifyWith(secretKey).build().parseSignedClaims(token).getPayload().get("role", String.class); } public Boolean isExpired(String token) { return Jwts.parser().verifyWith(secretKey).build().parseSignedClaims(token).getPayload().getExpiration().before(new Date()); } public String createJwt(String username, String role, Long expiredMs) { return Jwts.builder() .claim("username", username) .claim("role", role) .issuedAt(new Date(System.currentTimeMillis())) .expiration(new Date(System.currentTimeMillis() + expiredMs)) .signWith(secretKey) .compact(); } } ​ - JWTUtil : 0.11.5 @Component public class JWTUtil { private Key key; public JWTUtil(@Value("${spring.jwt.secret}")String secret) { byte[] byteSecretKey = Decoders.BASE64.decode(secret); key = Keys.hmacShaKeyFor(byteSecretKey); } public String getUsername(String token) { return Jwts.parserBuilder().setSigningKey(key).build().parseClaimsJws(token).getBody().get("username", String.class); } public String getRole(String token) { return Jwts.parserBuilder().setSigningKey(key).build().parseClaimsJws(token).getBody().get("role", String.class); } public Boolean isExpired(String token) { return Jwts.parserBuilder().setSigningKey(key).build().parseClaimsJws(token).getBody().getExpiration().before(new Date()); } public String createJwt(String username, String role, Long expiredMs) { Claims claims = Jwts.claims(); claims.put("username", username); claims.put("role", role); return Jwts.builder() .setClaims(claims) .setIssuedAt(new Date(System.currentTimeMillis())) .setExpiration(new Date(System.currentTimeMillis() + expiredMs)) .signWith(key, SignatureAlgorithm.HS256) .compact(); } } ​ 이전 : 11. 유저 정보 DB 저장 다음 : 13. 로그인 성공 JWT 발급 https://youtu.be/VwSKz9m_yvE 307, 스프링 OAuth2 클라이언트 JWT > 13. 로그인 성공 JWT 발급 로그인 성공 ​ OAuth2 로그인이 성공하면 실행될 성공 핸들러를 커스텀해서 내부에 JWT 발급 구현을 진행하면 됩니다. 이번 영상이 OAuth2 클라이언트 로그인에 대해서 모든 책임(redirect_url)을 백엔드가 가질 경우 JWT 발급에 대해서 프론트측에서 어떻게 받게 만들지 고민이 많으실 건데 발급 방법이 나옵니다. ​ ​ CustomSuccessHandler와 JWTUtil 주입 ​ - oauth2 > CustomSuccessHandler @Component public class CustomSuccessHandler extends SimpleUrlAuthenticationSuccessHandler { private final JWTUtil jwtUtil; public CustomSuccessHandler(JWTUtil jwtUtil) { this.jwtUtil = jwtUtil; } @Override public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException { //OAuth2User CustomOAuth2User customUserDetails = (CustomOAuth2User) authentication.getPrincipal(); String username = customUserDetails.getUsername(); Collection authorities = authentication.getAuthorities(); Iterator iterator = authorities.iterator(); GrantedAuthority auth = iterator.next(); String role = auth.getAuthority(); String token = jwtUtil.createJwt(username, role, 60*60*60L); response.addCookie(createCookie("Authorization", token)); response.sendRedirect("http://localhost:3000/"); } private Cookie createCookie(String key, String value) { Cookie cookie = new Cookie(key, value); cookie.setMaxAge(60*60*60); //cookie.setSecure(true); cookie.setPath("/"); cookie.setHttpOnly(true); return cookie; } } ​ SecurityConfig SuccessHandler 등록 ​ - config > SecurityConfig @Configuration @EnableWebSecurity public class SecurityConfig { private final CustomOAuth2UserService customOAuth2UserService; private final CustomSuccessHandler customSuccessHandler; private final JWTUtil jwtUtil; public SecurityConfig(CustomOAuth2UserService customOAuth2UserService, CustomSuccessHandler customSuccessHandler, JWTUtil jwtUtil) { this.customOAuth2UserService = customOAuth2UserService; this.customSuccessHandler = customSuccessHandler; this.jwtUtil = jwtUtil; } @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { //csrf disable http .csrf((auth) -> auth.disable()); //From 로그인 방식 disable http .formLogin((auth) -> auth.disable()); //HTTP Basic 인증 방식 disable http .httpBasic((auth) -> auth.disable()); //oauth2 http .oauth2Login((oauth2) -> oauth2 .userInfoEndpoint((userInfoEndpointConfig) -> userInfoEndpointConfig .userService(customOAuth2UserService)) .successHandler(customSuccessHandler) ); //경로별 인가 작업 http .authorizeHttpRequests((auth) -> auth .requestMatchers("/").permitAll() .anyRequest().authenticated()); //세션 설정 : STATELESS http .sessionManagement((session) -> session .sessionCreationPolicy(SessionCreationPolicy.STATELESS)); return http.build(); } } ​ 이전 : 12. JWT 발급 및 검증 클래스 다음 : 14. JWT 검증 필터 https://youtu.be/s6D_zXnrXNo 308, 스프링 OAuth2 클라이언트 JWT > 14. JWT 검증 필터 JWT 검증 필터 ​ 스프링 시큐리티 filter chain에 요청에 담긴 JWT를 검증하기 위한 커스텀 필터를 등록해야 한다. ​ 해당 필터를 통해 요청 쿠키에 JWT가 존재하는 경우 JWT를 검증하고 강제로SecurityContextHolder에 세션을 생성한다. (이 세션은 STATLESS 상태로 관리되기 때문에 해당 요청이 끝나면 소멸 된다.) JWTFilter 구현 ​ - jwt > JWTFilter public class JWTFilter extends OncePerRequestFilter { private final JWTUtil jwtUtil; public JWTFilter(JWTUtil jwtUtil) { this.jwtUtil = jwtUtil; } @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { //cookie들을 불러온 뒤 Authorization Key에 담긴 쿠키를 찾음 String authorization = null; Cookie[] cookies = request.getCookies(); for (Cookie cookie : cookies) { System.out.println(cookie.getName()); if (cookie.getName().equals("Authorization")) { authorization = cookie.getValue(); } } //Authorization 헤더 검증 if (authorization == null) { System.out.println("token null"); filterChain.doFilter(request, response); //조건이 해당되면 메소드 종료 (필수) return; } //토큰 String token = authorization; //토큰 소멸 시간 검증 if (jwtUtil.isExpired(token)) { System.out.println("token expired"); filterChain.doFilter(request, response); //조건이 해당되면 메소드 종료 (필수) return; } //토큰에서 username과 role 획득 String username = jwtUtil.getUsername(token); String role = jwtUtil.getRole(token); //userDTO를 생성하여 값 set UserDTO userDTO = new UserDTO(); userDTO.setUsername(username); userDTO.setRole(role); //UserDetails에 회원 정보 객체 담기 CustomOAuth2User customOAuth2User = new CustomOAuth2User(userDTO); //스프링 시큐리티 인증 토큰 생성 Authentication authToken = new UsernamePasswordAuthenticationToken(customOAuth2User, null, customOAuth2User.getAuthorities()); //세션에 사용자 등록 SecurityContextHolder.getContext().setAuthentication(authToken); filterChain.doFilter(request, response); } } ​ SecurityConfig JWTFilter 등록 ​ - config > SecurityConfig @Configuration @EnableWebSecurity public class SecurityConfig { private final CustomOAuth2UserService customOAuth2UserService; private final CustomSuccessHandler customSuccessHandler; private final JWTUtil jwtUtil; public SecurityConfig(CustomOAuth2UserService customOAuth2UserService, CustomSuccessHandler customSuccessHandler, JWTUtil jwtUtil) { this.customOAuth2UserService = customOAuth2UserService; this.customSuccessHandler = customSuccessHandler; this.jwtUtil = jwtUtil; } @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { //csrf disable http .csrf((auth) -> auth.disable()); //From 로그인 방식 disable http .formLogin((auth) -> auth.disable()); //HTTP Basic 인증 방식 disable http .httpBasic((auth) -> auth.disable()); //JWTFilter 추가 http .addFilterBefore(new JWTFilter(jwtUtil), UsernamePasswordAuthenticationFilter.class); //oauth2 http .oauth2Login((oauth2) -> oauth2 .userInfoEndpoint((userInfoEndpointConfig) -> userInfoEndpointConfig .userService(customOAuth2UserService)) .successHandler(customSuccessHandler) ); //경로별 인가 작업 http .authorizeHttpRequests((auth) -> auth .requestMatchers("/").permitAll() .anyRequest().authenticated()); //세션 설정 : STATELESS http .sessionManagement((session) -> session .sessionCreationPolicy(SessionCreationPolicy.STATELESS)); return http.build(); } } ​ 이전 : 13. 로그인 성공 JWT 발급 다음 : 15. CORS 설정 https://youtu.be/9g_iN6rLQcQ 309, 스프링 OAuth2 클라이언트 JWT > 15. CORS 설정 자료 ​ 스프링 시큐리티 CORS 공식 문서 CORS란 ​ 교차 출처 리소스 공유 : 위키피디아 문서 바로가기 발생 원리 ​ ​ CORS 설정 ​ - SecurityConfig @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http .cors(corsCustomizer -> corsCustomizer.configurationSource(new CorsConfigurationSource() { @Override public CorsConfiguration getCorsConfiguration(HttpServletRequest request) { CorsConfiguration configuration = new CorsConfiguration(); configuration.setAllowedOrigins(Collections.singletonList("http://localhost:3000")); configuration.setAllowedMethods(Collections.singletonList("*")); configuration.setAllowCredentials(true); configuration.setAllowedHeaders(Collections.singletonList("*")); configuration.setMaxAge(3600L); configuration.setExposedHeaders(Collections.singletonList("Set-Cookie")); configuration.setExposedHeaders(Collections.singletonList("Authorization")); return configuration; } })); return http.build(); } ​ - config > CorsMvcConfig @Configuration public class CorsMvcConfig implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry corsRegistry) { corsRegistry.addMapping("/**") .exposedHeaders("Set-Cookie") .allowedOrigins("http://localhost:3000"); } } ​ 이전 : 14. JWT 검증 필터 다음 : 16. 리액트에서 요청 https://youtu.be/Xiv5KFoEW4w 310, 스프링 OAuth2 클라이언트 JWT > 16. 리액트에서 요청 리액트에서 소셜 로그인 요청 ​ ​ 2번 과정 ​ const onNaverLogin = () => { window.location.href = "http://localhost:8080/oauth2/authorization/naver" } function Login(props) { return ( <>

Login

); } ​ axios 요청 ​ axios .get("http://localhost:8080/", {withCredentials: true}) .then((res) => { alert(JSON.stringify(res.data)) }) .catch((error) => alert(error)) ​ 이전 : 15. CORS 설정 다음 : 17. 재로그인 무한 루프 오류 https://youtu.be/OddaHR7oIWE 311, 스프링 OAuth2 클라이언트 JWT > 17. 재로그인 무한 루프 오류 좋은 제안 감사드립니다. ​ ​ 오류 발생 경우 ​ 필터 위치에 따라 OAuth2 인증을 진행하는 필터보다 JWTFilter가 앞에 존재하는 경우 아래와 같은 오류가 발생할 수 있습니다. 1. 재로그인 2. JWT 만료 → 거절 3. OAuth2 로그인 실패 → 재요청 4. 무한 루프 따라서 JWTFilter를 OAuth2LoginAuthenticationFilter 뒤에 위치 시키거나 JWTFilter 내부에 if문을 통해 특정 경로 요청은 넘어가도록 진행하면 됩니다. SecurityConfig 클래스에서 설정 ​ - SecurityConfig > filterChain //JWTFilter 추가 http .addFilterAfter(new JWTFilter(jwtUtil), OAuth2LoginAuthenticationFilter.class); ​ JWTFilter ​ - JWTFilter > doFilterInternal String requestUri = request.getRequestURI(); if (requestUri.matches("^\\/login(?:\\/.*)?$")) { filterChain.doFilter(request, response); return; } if (requestUri.matches("^\\/oauth2(?:\\/.*)?$")) { filterChain.doFilter(request, response); return; } ​ 이전 : 16. 리액트에서 요청 다음 : 18. 아이디어 https://youtu.be/OCssYnZbLOU 312, 스프링 OAuth2 클라이언트 JWT > 18. 아이디어 아이디어 ​ 구현적인 부분은 17강까지 영상을 통해 가능하지만, 댓글 질문 많아 요약 정리를 진행하겠습니다. 우선 실행은 영상 촬영 전 테스트를 통해 확인을 했고, 실제 제 영상을 보고 프로젝트에 잘 적용했고 테스트 결과 잘 된다는 댓글이 몇 분 계셔서 안심하고 진행하셔도 될 거 같습니다. ​ (OAuth2 + 일반 로그인 + JWT 심화 시리즈를 합쳐 진행하신 분들도 잘 돌아간다고 합니다.) 책임에 관련된 부분 ​ 인가 코드 → 토큰 → 유저 정보 흐름에 대한 책임 영상을 2강에서 다뤘습니다. 이 부분에 대해 궁금하신 분들이 많아 다시 정리합니다. - 웹 : 웹 환경에선 되도록 (무조건) 모든 흐름 자체를 백엔드에서 처리하는 것이 좋습니다. 시청자 분이 제 영상을 가지고 직접 카카오 DEV 톡에 질문하신 글이 있었습니다. 카카오 DEV 톡 : 질문글 바로가기 카카오측 공식 답변도 웹은 최대한 모든 흐름 자체를 백엔드측에서 진행하라고 권고하고 있습니다. - 앱 : 앱에서 쿠키를 다루기가 정말 힘듭니다. SDK를 추천드립니다. 현재 시리즈 + 웹뷰를 통해 구현을 진행하시거나 (쿠키를 다루기 힘듭니다.) SDK를 활용하여(카카오 및 네이버에서도 적극 추천) 모든 흐름을 앱에서 처리하고, 그 결과만 백엔드로 전송하시는 방법을 추천드립니다. (결국 하나의 소셜 로그인 도메인에 대해 서버측은 2개의 API를 가지게 됩니다. ㅜㅜ BFF를 도입..?) JWT : OAuth2 쿠키 발급 → 헤더는 절대 못 쓰는지? ​ 일단 발급 자체는 쿠키로만 가능합니다. 헤더로 발급을 진행하면 하이퍼 링크로 받을 수 없습니다. 하지만 첫 발급 이후에는 헤더로 JWT를 이동 시킬 수 있습니다. ​ 1. 로그인 성공 쿠키로 발급 2. 프론트의 특정 페이지로 리디렉션을 보냄 3. 프론트의 특정 페이지는 axios를 통해 쿠키를(credentials=true)를 가지고 다시 백엔드로 접근하여 헤더로 JWT를 받아옴 4. 헤더로 받아온 JWT를 로컬 스토리지등에 보관하여 사용 JWT : 소셜 로그인 + 일반 로그인 ​ 아래 두 시리즈를 합치면 됩니다. 스프링 OAuth2 클라이언트 JWT 시리즈 바로가기 스프링 시큐리티 JWT 시리즈 바로가기 추가로 Refresh/Access도 도입하시는 것을 추천드립니다. 스프링 JWT 심화 시리즈 바로가기 다만, 문제가 발생합니다. 로그인은 각각의 플로우를 사용하면 됩니다. 이후 로그인 성공 핸들러를 통해 JWT를 발급하는데, 발급하는 형식이 다릅니다.(쿠키/헤더) 즉, 발급 받은 JWT로 요청할 때 각각의 시리즈 JWTFilter에서 구현 방식이 쿠키/헤더로 다르기 때문에 통합의 필요성이 발생합니다. JWTFilter는 무조건 하나의 로직이 좋습니다. 헤더 방식으로 통합하겠습니다. 그럼 소셜 로그인을 통해 쿠키로 받은 JWT는 어떻게 처리할지? 라고 물어보면 위에서 말한 아래 흐름을 사용하시면 됩니다. ​ 1. 로그인 성공 쿠키로 발급 2. 프론트의 특정 페이지로 리디렉션을 보냄 3. 프론트의 특정 페이지는 axios를 통해 쿠키를(credentials=true)를 가지고 다시 백엔드로 접근하여 헤더로 토큰을 받아옴 4. 헤더로 받아온 토큰을 로컬 스토리지등에 보관하여 사용 추가 : 쿠키를 정말로 잡지 못하겠다. ​ 앱의 경우 SDK를 적극 권장드리지만 여건이 안되는 경우 쿠키 방식으로도 받게됩니다. 이때 쿠키의 경우 모바일앱에서 다루기 매우 까다롭습니다. ​ 이때는 어쩔 수 없이 (위험 요소가 있지만) 토큰을 로그인 성공 후 응답 쿼리 파라미터에 문자열로 넣어서 보내는 방식도 있을거 같습니다. ​ 이전 : 17. 재로그인 무한 루프 오류 https://youtu.be/n2HQkqhOvMo 313, 이번 시리즈는 스프링 OAuth2 인가 서버와 스프링 OAuth2 리소스 서버에 이어집니다. 앞서 구축한 “인가 서버”, “리소스 서버”를 활용해 우리의 소셜 로그인 서비스에 대해 3자 플랫폼인 스프링 OAuth2 클라이언트로 로그인을 진행하는 프로젝트입니다. 스프링 OAuth2 최종 연동 ​ 1. 실습 목표 2. 변수 응답 설정 3. 로컬 테스트 설정 4. 시연 314, 스프링 OAuth2 최종 연동 > 1. 실습 목표 실습 목표 ​ “OAuth2 인가 서버”, “OAuth2 리소스 서버”를 구현 했기 때문에 최종적으로 “OAuth2 클라이언트”를 통해 우리가 만든 소셜 로그인 서비스를 사용하도록 하겠습니다. ​ ​ 연계 시리즈 ​ “OAuth2 인가 서버”, “OAuth2 리소스 서버” 이외에 추가적으로 “스프링 OAuth2 클라이언트” 프로젝트가 요구됩니다. 우리가 진행한 OAuth2 클라이언트 시리즈는 아래와 같으며, 각 프로젝트 중 하나를 선택하여 변수 설정 및 데이터를 받는 DTO만 구현하면 사용할 수 있습니다. ​ 스프링 OAuth2 클라이언트 세션 스프링 OAuth2 클라이언트 JWT ​ ​ 스프링 OAuth2 클라이언트 설정 ​ - 변수 설정 - OAuth2UserService - Response ​ 다음 : 2. 변수 응답 설정 https://youtu.be/VcKvM_ppw4E 315, 스프링 OAuth2 최종 연동 > 2. 변수 응답 설정 변수 설정 ​ - application.properites #registration spring.security.oauth2.client.registration.yummi.client-name=yummi spring.security.oauth2.client.registration.yummi.provider=yummi spring.security.oauth2.client.registration.yummi.client-id=9d3ee033-55cc-4dc1-83ac-493972420dcc spring.security.oauth2.client.registration.yummi.client-secret=secret spring.security.oauth2.client.registration.yummi.redirect-uri=http://localhost:8080/login/oauth2/code/yummi spring.security.oauth2.client.registration.yummi.authorization-grant-type=authorization_code spring.security.oauth2.client.registration.yummi.scope=profile #provider spring.security.oauth2.client.provider.yummi.authorization-uri=http://localhost:9000/oauth2/authorize spring.security.oauth2.client.provider.yummi.token-uri=http://localhost:9000/oauth2/token spring.security.oauth2.client.provider.yummi.user-info-uri=http://localhost:9001/me spring.security.oauth2.client.provider.yummi.jwk-set-uri=http://localhost:9000/oauth2/jwks spring.security.oauth2.client.provider.yummi.user-name-attribute=response ​ - 네이버 예시​ #registration spring.security.oauth2.client.registration.naver.client-name=naver spring.security.oauth2.client.registration.naver.client-id= spring.security.oauth2.client.registration.naver.client-secret= spring.security.oauth2.client.registration.naver.redirect-uri=http://localhost:8080/login/oauth2/code/naver spring.security.oauth2.client.registration.naver.authorization-grant-type=authorization_code spring.security.oauth2.client.registration.naver.scope=name,email #provider spring.security.oauth2.client.provider.naver.authorization-uri=https://nid.naver.com/oauth2.0/authorize spring.security.oauth2.client.provider.naver.token-uri=https://nid.naver.com/oauth2.0/token spring.security.oauth2.client.provider.naver.user-info-uri=https://openapi.naver.com/v1/nid/me spring.security.oauth2.client.provider.naver.user-name-attribute=response ​ 응답 설정 ​ - CustomOAuth2UserService else if (registrationId.equals("yummi")) { oAuth2Response = new YummiResponse(oAuth2User.getAttributes()); } ​ - YummiResponse​ import java.util.Map; public class YummiResponse implements OAuth2Response{ private final Map attribute; public YummiResponse(Map attribute) { this.attribute = (Map) attribute.get("response"); } @Override public String getProvider() { return "yummi"; } @Override public String getProviderId() { return "23413241234"; } @Override public String getEmail() { return attribute.get("username").toString() + "@devyummi.com"; } @Override public String getName() { return attribute.get("username").toString(); } } ​ 이전 : 1. 실습 목표 다음 : 3. 로컬 테스트 설정 https://youtu.be/NHH3GC7zbzo 316, 스프링 OAuth2 최종 연동 > 3. 로컬 테스트 설정 로컬 테스트시 문제점 ​ 시연을 위해서는 3가지 프로젝트를 구동시켜야 합니다. “스프링 OAuth2 인가 서버”, “스프링 OAuth2 리소스 서버”, “스프링 OAuth2 클라이언트” 3개의 프로젝트가 모두 같은 컴퓨터에 구동되고, 이때 소셜 로그인을 수행하면 “스프링 OAuth2 클라이언트”의 로그인시 생성되는 쿠키와 “스프링 OAuth2 인가 서버” 로그인시 생성되는 쿠키가 충돌하여 로그인이 실패하는 이슈가 있습니다. 다만 이 이슈는 로컬에서 3개의 프로젝트를 실행하고 테스트시 발생하며, 일반적으로 “인가 서버”와 “3자 플랫폼"이 분리 될 경우 오류 없이 수행됩니다. 테스트를 위한 클라이언트 쿠키 설정 ​ 임시로 세션 쿠키명을 변경시키겠습니다. (배포 환경에는 필요 없는 임시코드라 stackoverflow를 참조했습니다.) - cookieUtil import jakarta.servlet.http.Cookie; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.springframework.util.SerializationUtils; import java.util.Base64; public class CookieUtil { public static void addCookie(HttpServletResponse response, String name, String value, int maxAge) { Cookie cookie = new Cookie(name, value); cookie.setPath("/"); cookie.setMaxAge(maxAge); response.addCookie(cookie); } public static void deleteCookie(HttpServletRequest request, HttpServletResponse response, String name) { Cookie[] cookies = request.getCookies(); if (cookies == null) { return; } for (Cookie cookie : cookies) { if (name.equals(cookie.getName())) { cookie.setValue(""); cookie.setPath("/"); cookie.setMaxAge(0); response.addCookie(cookie); } } } public static String serialize(Object obj) { return Base64.getUrlEncoder() .encodeToString(SerializationUtils.serialize(obj)); } public static T deserialize(Cookie cookie, Class cls) { return cls.cast( SerializationUtils.deserialize( Base64.getUrlDecoder().decode(cookie.getValue()) ) ); } } ​ - CookieRepository import jakarta.servlet.http.Cookie; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.springframework.security.oauth2.client.web.AuthorizationRequestRepository; import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest; import org.springframework.web.util.WebUtils; public class CookieRepository implements AuthorizationRequestRepository { public final static String OAUTH2_AUTHORIZATION_REQUEST_COOKIE_NAME = "oauth2_auth_request"; private final static int COOKIE_EXPIRE_SECONDS = 18000; @Override public OAuth2AuthorizationRequest removeAuthorizationRequest(HttpServletRequest request, HttpServletResponse response) { return this.loadAuthorizationRequest(request); } @Override public OAuth2AuthorizationRequest loadAuthorizationRequest(HttpServletRequest request) { Cookie cookie = WebUtils.getCookie(request, OAUTH2_AUTHORIZATION_REQUEST_COOKIE_NAME); return CookieUtil.deserialize(cookie, OAuth2AuthorizationRequest.class); } @Override public void saveAuthorizationRequest(OAuth2AuthorizationRequest authorizationRequest, HttpServletRequest request, HttpServletResponse response) { if (authorizationRequest == null) { removeAuthorizationRequestCookies(request, response); return; } CookieUtil.addCookie(response, OAUTH2_AUTHORIZATION_REQUEST_COOKIE_NAME, CookieUtil.serialize(authorizationRequest), COOKIE_EXPIRE_SECONDS); } public void removeAuthorizationRequestCookies(HttpServletRequest request, HttpServletResponse response) { CookieUtil.deleteCookie(request, response, OAUTH2_AUTHORIZATION_REQUEST_COOKIE_NAME); } } ​ - SecurityConfig > SecurityFilterChain​ http .oauth2Login((oauth2) -> oauth2 .authorizationEndpoint((authorizationEndpointConfig) -> authorizationEndpointConfig .authorizationRequestRepository(new CookieRepository())) //.authorizationRequestRepository(new HttpSessionOAuth2AuthorizationRequestRepository())) .userInfoEndpoint((userInfoEndpointConfig) -> userInfoEndpointConfig .userService(customOAuth2UserService))); ​ 이전 : 2. 변수 응답 설정 다음 : 4. 시연 https://youtu.be/1HJArJ8gQzE 317, 스프링 OAuth2 최종 연동 > 4. 시연 테스트 환경 ​ 스프링 OAuth2 인가 서버 : 9000 포트 스프링 OAuth2 리소스 서버 : 9001 포트 스프링 OAuth2 클라이언트 : 8080 포트 소셜 로그인 수행 ​ 우리가 만든 인가/리소스 서버를 기반으로 소셜 로그인을 진행하겠습니다. ​ ​ 이전 : 3. 로컬 테스트 설정 https://youtu.be/2JKbfOsZ854 318, 도커 설치 및 이미지별 도커 컨테이너 생성 방법 도커 설치 및 환경 설정 ​ 1. 우분투 환경 도커 설치 2. 빌드 레이어 전력 3. 이미지별 도커 컨테이너 생성 ​ MySQL 컨테이너 생성 Neo4j 컨테이너 생성 ​ ​ 319, 도커 단순 사용 > 1. 우분투 환경 도커 설치 설치 환경 ​ 우분투 24.04LTS (22.04 ~ 큰 차이 없음) apt-get을 통한 설치 ​ sudo apt-get update sudo apt-get install apt-transport-https ca-certificates curl software-properties-common curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo gpg --dearmor -o /usr/share/keyrings/docker-archive-keyring.gpg echo "deb [arch=amd64 signed-by=/usr/share/keyrings/docker-archive-keyring.gpg] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable" | sudo tee /etc/apt/sources.list.d/docker.list > /dev/null sudo apt-get update sudo apt-get install docker-ce docker-ce-cli containerd.io ​ 도커 sudo ​ 매번 docker 명령어 앞에 sudo를 입력하기 싫다면 아래 명령을 통해 현재 사용자를 docker 그룹에 추가함 (sudo 권한을 가지기 때문에 계정별 조심히 설정) ​ sudo usermod -aG docker $USER newgrp docker ​ 다음 : 2. 도커용 nvidia 툴킷 (nvidia-smi) https://youtu.be/tLZh7TdOSTg 320, 도커 단순 사용 > MySQL 컨테이너 생성 도커 MySQL 컨테이너 생성 명령어 ​ 컨테이너로 띄울 MySQL 이미지 버전 tag는 아래를 통해 확인 가능하며, 가장 무난한 8버전 기반으로 만들겠습니다. https://hub.docker.com/_/mysql/tags ​ sudo docker run --name 별칭 -d --restart=unless-stopped -p 3307:3306 -e MYSQL_ROOT_PASSWORD=비밀번호 mysql:8 ​ --name 별칭 : 별칭 ​ -d : 백그라운드 실행 ​ --restart=unless-stopped : 서버가 재부팅된 후 자동 컨테이너 시작 (unless-stopped는 사용자가 직접 컨테이너 종료시 재부팅되어도 시작 안됨) ​ -p 서버포트:내부포트 : 포트 설정 콜론 기준으로 우측은 MySQL 기본 포트인 3306 ​ -e MYSQL_ROOT_PASSWORD=비밀번호 : 기본적으로 생성되는 MySQL root 계정의 비밀번호 ​ https://youtu.be/ZJY8vboUQmw 321, 도커 단순 사용 > Neo4j 컨테이너 생성 도커 Neo4j 컨테이너 생성 명령어 ​ 컨테이너로 띄울 Neo4j 이미지 버전 tag는 아래를 통해 확인 가능하며, 가장 무난한 5버전 기반으로 만들겠습니다. https://hub.docker.com/_/neo4j/tags ​ sudo docker run -d \ --name 별칭 \ --restart=unless-stopped \ -p 7474:7474 -p 7473:7473 -p7687:7687 \ -v /home/xxxjjhhh/neo4j/data:/data \ -e NEO4J_AUTH=neo4j/비밀번호 \ -e NEO4J_dbms_memory_heap_initial__size=1G \ -e NEO4J_dbms_memory_heap_max__size=2G \ neo4j:5 ​ --name 별칭 : 도커 컨테이너 별칭 설정 ​ --restart=unless-stopped : 사용자가 직접 컨테이너를 종료 시키지 않으면 재부팅시 자동 시작 ​ -p : 7474(http), 7473(https), 7687(bolt) ​ -v : data 경로에 데이터가 저장 됨, 외부로 마운트 ​ 환경 변수 : NEO4J_AUTH ​ 어드민 계정명은 필수적으로 neo4j여야 합니다. 다른 값 사용시 도커 컨테이너 실행 오류 ​ https://youtu.be/2Eus0Sr02n4 322, 웹 개발자(프론트/백엔드)를 위한 웹 보안 기초 개념 시리즈입니다. ​ 웹 보안 개념 ​ 1. CSRF 공격 2. XSS 공격 3. OWASP JAVA HTML Sanitizer 4. 다양한 버퍼 오버플로우와 방어 전략 5. ​ 323, 웹 보안 개념 > 1. CSRF 공격 Cross-Site Request Forgery ​ 로그인된 사용자에게 사용자가 원하지 않지만, 해커가 원하는 요청을 유도하는 공격 기법으로 로그인 사용자가 ADMIN과 같은 권한을 가지면 큰 피해를 입을 수 있습니다. ​ ​ 어떤 방식으로 특정 유저에게 요청을 유도할 수 있을까요? 모든 요청 유도는 서비스의 구현 취약점을 찾은 후, 취약점을 기반한 위조 트랩을 만드는 방식입니다. ​ 취약점 1 : GET 요청 URI에 행위가 나타나는 케이스 ​ https://www.devyummi.com/delete/1 경로가 1번 게시글을 지우는 역할을 수행한다 가정하겠습니다. 위 경로는 어드민에게만 인가 권한이 주어진다 가정합니다. (즉, 권한이 없는 사람이 저 요청을 하면 지워지지 않음) ​ 하지만 GET 요청 URI 행위 취약점을 통해 해커가 어드민에게 저 경로를 실행하게 할 수 있습니다. 아래 과정을 확인하겠습니다. 1. 위 주소 요청을 보내는 HTML 태그를 만듬 a. 태그 href="위주소" b. 태그 src="위주소" 2. 해당 태그를 행위를 수행할 수 있는 권한이 있는 유저에게 보냄 a. 이메일 b. 공개된 게시판 - 해결 방법 GET 요청 URI일때 CRUD 중 Read 이외의 행위가 들어가면 안됩니다. - 사례 누가봐도 위험한 구현이지만, 2008년 옥션이 당했던 방식입니다. 옥션 계정 비밀번호를 변경하는 로직이 URI 쿼리 파라미터 기반이었고, 해커가 에 비밀번호 변경 URI를 심어 어드민 계정에 이메일을 보냄으로 공격이 성공했습니다. ​ 취약점 2 : Form 요청 hidden ​ 취약점 1 사례를 통해 GET 요청의 위험성을 알았습니다. 때문에 CUD 행위를 POST Form태그 기반으로 진행하겠습니다. 그럼 안전할까요? ​ 하지만 Form 태그 또한 CSRF 공격으로 부터 안전하지 못합니다. 1. 파라미터를 hidden type으로 숨긴 Form태그를 만듬 a. 수동으로 버튼 클릭 b. 자동으로 버튼 활성 2. 해당 Form을 권한이 있는 유저에게 보냄 a. 이메일 b. 공개된 게시판 - 해결 방법 CSRF 토큰이 존재합니다. 흔히 스프링 시큐리티 SecurityConfig 필터체인 작성시 csrf() 설정을 추가하는 것이 CSRF 토큰을 검증하는 로직을 추가하는 것 입니다. 서버는 로그인한 유저에게 고유의 난수 CSRF 토큰을 발급합니다. 이후 서비스 개발자들이 만든 Form 태그는 해당 CSRF 토큰을 hidden 파라미터로 담도록 설계합니다. 해커가 만든 Form 태그는 CSRF 토큰을 담지 못하기 때문에 Form 요청시 인가가 거부됩니다. 세션 방식일 경우 위험성 ​ 위 두가지 취약점은 서비스의 인증 방식이 세션일 경우 특히 유효합니다. 많은 시큐리티 강좌들이 CSRF 보안 로직을 세션일 때, 추가하고 JWT일 경우 제외하고 있습니다. 왜 세션 방식이 위험한지 파악하고, JWT 방식은 정말 안전한지 확인하겠습니다. - 쿠키-세션 방식 인증 세션 방식 인증은 접근하는 브라우저별로 하나의 쿠키(톰캣쪽은 보통 JSESSIONID)를 발급하고, 그 쿠키에 대응되는 정보를 서버 메모리(세션)에 저장합니다. 이때, 쿠키는 브라우저에 의해 매 요청에 끼워서 필수적으로 전송됩니다. (예외 케이스는 존재하지만) - JWT 방식 반면 JWT 방식 인증은 로그인을 마친 유저에게 JWT를 발급하고, 인증이 필요할 때 서버측으로 JWT를 보내지만, JWT의 저장 특성상 로컬스토리지에 저장하기 때문에 쿠키 방식이 아니어서 자동으로 요청에 따라가지 않습니다. - 이를 통해 인증용 쿠키/JWT가 자동으로 따라가는지의 여부에 따라 결국 CSRF의 위험성이 달라집니다. 자동으로 따라가는 것은 결국 해커가 만든 트랩에서도 인증을 할 수 있는 요소가 따라가는 것이기 때문입니다. - 그럼 JWT는 항상 안전한가 JWT는 대게 발급을 하게 된다면 프론트의 로컬 스토리지에 저장하게 됩니다. 로컬 스토리지에 저장한 JWT는 요청시 JS 코드를 기반으로 꺼내 axios나 fetch에 붙이게 됩니다. 우리 서비스가 의도한 요청은 위 작업들을 구현하지만, 해커가 만든 위조 요청은 저것을 구현하기가 매우 어렵습니다. 따라서 JWT는 CSRF 공격으로 부터 많이 안전하다 할 수 있습니다. 다만, JWT를 로컬 스토리지가 아닌 쿠키에 보관하는 경우, 그리고 쿠키가 모든 요청에 항상 따라가는 경우는 CSRF 공격에 조심해야 합니다. (Refresh용 토큰 제외) ​ 정리하면 ​ - JWT Access용 JWT를 로컬 스토리지에 보관한다면 CSRF 공격에 대해선 큰 걱정을 하지 않아도 됨. - 쿠키-세션 세션에 대응되는 쿠키는 브라우저에 의해 매 요청에 따라가기 때문에 CSRF 공격에 대한 위험성을 가지며, 위 취약점 1, 2 사례를 기반으로 추가 보안 로직이 수반되어야 합니다. ​ 다음 : 2. XSS 공격 https://youtu.be/8H9J8lSPKuw 324, 웹 보안 개념 > 2. XSS 공격 Cross Site Scripting ​ XSS는 해커가 웹 서비스에 정보를 탈취할 수 있는 JS 로직을 삽입하여, 정상적인 유저가 그 로직을 실행하면서 발생하는 해킹 기법입니다. 탈취되는 정보는 주로 쿠키, JWT와 같은 프론트측에 저장되는 요소들 입니다. (지난 시간, 로컬 스토리지에 저장한 JWT는 CSRF 공격으로 부터 다소 안전하다고 했는데, XSS 공격에는 취약점을 가지게 됩니다.) - XSS? CSS? 풀 네임은 분명 Cross Site Scripting인데, 왜 XSS라고 불릴까요? 이는 HTML/CSS의 CSS가 너무 널리 알려져 그렇습니다. 따라서 보안 분야에서 중요한 Cross Site Scripting을 CSS로 쓰기엔, 혼동이 있을 수 있어 XSS로 표기합니다. XSS 공격 종류 ​ - Reflected 프론트 입력창에서 JS 입력값이 백엔드 API로 보내진 후, 컨트롤러에서 그 값을 그대로 VIEW에 넣어져 리턴 후 악성 JS 실행. ​ - DOM based 프론트 입력창에서 JS 입력값이 innerHtml과 같은 스크립트에 의해 DOM에 바로 반영어 악성 JS 실행. ​ - Stored ,