Spring WebFlux를 이용한 chat 프로그램 - 백엔드 기본 구성
2025. 5. 1. 17:52ㆍJAVA/Spring Boot
이번엔 백엔드 환경설정을 한다.
이클립스를 사용하고 있고 이클립스에 STD를 설치 해 놓은 상태이다.
프로젝트를 생성할 때
Spring Boot > Spring Starter Project 를 선택해서 생성한다.
프로젝트 명이나 이런건 알아서 설정하면 되고 Dependencies에서 다음과 같이 선택한다.
Spring Reactive Web
WebSocket
Lombok
Spring Data R2DBC
Spring Data Reactive MongoDB
PostgreSQL Driver
위와 같이 하면 build.gradle 파일이 다음과 같이 생성된다.
plugins {
id 'java'
id 'org.springframework.boot' version '3.4.5'
id 'io.spring.dependency-management' version '1.1.7'
}
group = 'com.company'
version = '0.0.1-SNAPSHOT'
java {
toolchain {
languageVersion = JavaLanguageVersion.of(23)
}
}
configurations {
compileOnly {
extendsFrom annotationProcessor
}
}
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-data-mongodb-reactive'
implementation 'org.springframework.boot:spring-boot-starter-data-r2dbc'
implementation 'org.springframework.boot:spring-boot-starter-webflux'
implementation 'org.springframework.boot:spring-boot-starter-security'
/*
* Spring security에서 The bean 'conversionServicePostProcessor', defined in class path resource ...
* 오류 발생하기 때문에 spring-boot-starter-web는 제외 처리 한다.
* 오류 이유가 Spring MVC 기반 Security와 WebFlux 기반 Security를 동시에 로딩하려고 하면서 충돌이 되는 거란다.
*
* ChatGPT 답변
* spring-boot-starter-security는 기본적으로 MVC용 보안 설정 (WebSecurityConfiguration)을 로드합니다.
* spring-boot-starter-webflux와 함께 @EnableWebFluxSecurity를 쓰면 WebFlux 보안 설정 (WebFluxSecurityConfiguration)도 로드됩니다.
* 둘 다 사용되면 conversionServicePostProcessor와 같은 이름의 빈이 중복 정의되어 충돌이 발생합니다.
*/
implementation('org.springframework.boot:spring-boot-starter-websocket') {
exclude group: 'org.springframework.boot', module: 'spring-boot-starter-web'
}
runtimeOnly 'org.postgresql:postgresql'
runtimeOnly 'org.postgresql:r2dbc-postgresql'
// JWT
implementation 'io.jsonwebtoken:jjwt:0.9.1'
compileOnly 'org.projectlombok:lombok'
annotationProcessor 'org.projectlombok:lombok'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
testImplementation 'io.projectreactor:reactor-test'
testRuntimeOnly 'org.junit.platform:junit-platform-launcher'
}
tasks.named('test') {
useJUnitPlatform()
}
application.yml 설정
기본 적으로 프로젝트가 생성되면 yml 파일이 아닌 properties 파일로 application이 생성되어 있을 것이다.
간단히 그냥 이름을 바꿔줘면 된다.
application.properties → application.yml
spring:
application:
name: chat-backend
r2dbc:
url: r2dbc:postgresql://localhost:5432/chatdb
username: postgres
password: ******
data:
mongodb:
uri: mongodb://localhost:27017/chatdb
codec:
max-in-memory-size: 10MB
Security 설정
package com.company.common.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity;
import org.springframework.security.config.web.server.ServerHttpSecurity;
import org.springframework.security.web.server.SecurityWebFilterChain;
@Configuration
@EnableWebFluxSecurity // 👈 이거 꼭 필요!
public class SecurityConfig {
@Bean
SecurityWebFilterChain filterChain(ServerHttpSecurity http) {
return http
.csrf(csrf -> csrf.disable())
.authorizeExchange(ex -> ex
.anyExchange().permitAll()
)
.build();
}
}
JwtUtil 생성
package com.company.common.utils;
import java.util.Date;
import org.springframework.stereotype.Component;
import io.jsonwebtoken.JwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
/**
* JWT 토큰을 생성 및 검증하는 유틸리티 클래스
*/
@Component
public class JwtUtil {
// 토큰 서명용 비밀 키
private static final String SECRET_KEY = "mySecretKey";
// 토큰 만료 시간: 1시간
private static final long EXPIRATION = 1000 * 60 * 60;
// 사용자 이름을 기반으로 JWT 토큰 생성
public String generateToken(String username) {
return Jwts.builder()
.setSubject(username) // 토큰 제목에 사용자 이름 저장
.setIssuedAt(new Date()) // 발급 시간
.setExpiration(new Date(System.currentTimeMillis() + EXPIRATION)) // 만료 시간
.signWith(SignatureAlgorithm.HS256, SECRET_KEY) // 서명 알고리즘과 비밀 키
.compact();
}
// 토큰에서 사용자 이름 추출
public String extractUsername(String token) {
return Jwts.parser().setSigningKey(SECRET_KEY)
.parseClaimsJws(token)
.getBody().getSubject();
}
// 토큰이 유효한지 검사
public boolean validateToken(String token) {
try {
Jwts.parser().setSigningKey(SECRET_KEY)
.parseClaimsJws(token); // 유효하지 않으면 예외 발생
return true;
} catch (JwtException e) {
return false;
}
}
}
여기까지 설정하고 다음은 회원가입과 로그인 처리 진행할랍니다.
또 작성하려니 귀찮네..ㅋ
'JAVA > Spring Boot' 카테고리의 다른 글
Spring WebFlux를 이용한 chat 프로그램 - Dynamic Route 설정 (1) | 2025.05.03 |
---|---|
Spring WebFlux를 이용한 chat 프로그램 - 회원가입 및 로그인 (0) | 2025.05.02 |
Spring WebFlux를 이용한 chat 프로그램 - 프론트엔드 환경 구성 (0) | 2025.05.01 |
Spring WebFlux를 이용한 chat 프로그램 - 환경구성 (0) | 2025.05.01 |
시작 (0) | 2017.10.16 |