728x90

Nginx 설정으로 8080 포트 접근을 차단 설정하면 문제가 발생하더라.

Spring Boot 포트를 8080으로 설정해서 jar 파일을 구동시켰다.

1
2
nohup java -Xshare:off -jar /home/spring/SpringJWT/SpringJWT-0.0.1-SNAPSHOT.jar --server.port=8080 > /var/log/springjwt.log 2>&1 &
 



방화벽 설정을 아래와 같이 하면 https://spb.abc.com:8080/api/pub-key 와 같은 직접적인 접속을 허용하지 않는다.

오로지 Front-End 언어(ex, React)에서 Back-End 를 호출하는 axios 라이브러리를 통한 접속만 허용한다.

1
2
3
4
5
6
7
8
9
10
11
12
ㅇ 현재 방화벽 설정 확인
sudo firewall-cmd --list-all
 
ㅇ 8080 포트를 오직 로컬(Nginx)에서만 접근 가능하도록 설정
# Nginx 프록시 서버만 8080 포트 접근 허용 (예: 127.0.0.1 또는 내부 IP)
sudo firewall-cmd --permanent --add-rich-rule='rule family="ipv4" source address="127.0.0.1" port port="8080" protocol="tcp" accept'
 
# 외부에서 8080 포트 접근 차단
sudo firewall-cmd --permanent --add-rich-rule='rule family="ipv4" port port="8080" protocol="tcp" drop'
 
# 방화벽 재적용
sudo firewall-cmd --reload

 

 

nginx.conf 설정 예제 파일

실제 클라우드 환경에서 동작 테스트한 스크립트이며 도메인만 다른 명칭으로 변경했다.

즉 abc 라고 된 부분만 실제 부분을 변경한 것이다.

rocky linux 9.5 가 openssl 버전을 TLS 1.3 버전을 지원해서 아래와 같이 수정했다.

만약 TLS 1.2 버전을 지원하면 ssl_ciphers 주석 부분을 살리고 이에 맞는 스크립트로 수정해야 한다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
worker_processes auto;
 
error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;
 
include /etc/nginx/modules-enabled/*.conf;
 
events {
    worker_connections 1024;
}
 
http {
    include /etc/nginx/mime.types;
    default_type application/octet-stream;
 
    log_format main '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';
 
    access_log /var/log/nginx/access.log main;
 
    sendfile on;
    keepalive_timeout 65;
 
    # 시스템 정보 노출 제한
    server_tokens off;
 
    # 디렉토리 검색 방지
    autoindex off;
 
    ssl_protocols TLSv1.3;
    ssl_ecdh_curve X25519:prime256v1:secp384r1;
    #ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384:DHE-RSA-CHACHA20-POLY1305;
    ssl_prefer_server_ciphers off;
 
    # Redirect all HTTP traffic to HTTPS for spb.abc.com
    server {
        listen 80;
        server_name spb.abc.com;
        return 301 https://spb.abc.com$request_uri;
    }
 
    # Reverse Proxy for spb.abc.com with React static files
    server {
        listen 443 ssl;
        server_name spb.abc.com;
 
        ssl_certificate /etc/letsencrypt/live/spb.abc.com/fullchain.pem;
        ssl_certificate_key /etc/letsencrypt/live/spb.abc.com/privkey.pem;
        ssl_trusted_certificate /etc/letsencrypt/live/spb.abc.com/chain.pem;
        include /etc/letsencrypt/options-ssl-nginx.conf;
 
        error_log /var/log/nginx/spb-error.log;
        access_log /var/log/nginx/spb-access.log main;
 
        root /home/react/react-auth/build;
        index index.html;
 
        location / {
            try_files $uri /index.html;
            limit_except GET POST {
                deny all;
            }
        }
 
        location /static/ {
            root /home/react/react-auth/build/static;
            expires 30d;
            add_header Cache-Control "public, max-age=2592000";
        }
 
        location ~* \.(?:js|css|json|ico|png|jpg|jpeg|svg|woff|woff2|ttf|otf|eot|mp4|webm|ogv|ogg|mp3|wav|webp)$ {
            expires max;
            access_log off;
            add_header Cache-Control "public";
        }
 
    location ^~ /api {
        proxy_pass https://spb.abc.com:8080/api;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
 
    location ^~ /login {
        proxy_pass https://spb.abc.com:8080/login;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
    }
 
    include /etc/nginx/conf.d/*.conf;
}
 

 

 

아래 내용은 chatGPT 도움을 받은 내용을 기록해 둔다.

 

location ^~ /api {
    proxy_pass https://spb.abc.com:8080/api;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Proto $scheme;
}

이 설정은 Nginx가 /api 경로로 들어오는 요청을 https://spb.abc.com:8080/api로 프록시(Proxy)하는 역할을 한다.
즉, Front-End 가 https://spb.abc.com/api로 요청을 보내면, 해당 요청이 https://spb.abc.com:8080/api로 전달된다.

location ^~ /api {
    /api로 시작하는 모든 요청을 처리한다.
    ^~ : 해당 경로가 요청 URL과 일치하면 더 이상 다른 location 블록을 검사하지 않음 (우선순위 높음).

proxy_pass https://spb.abc.com:8080/api;
    Nginx가 /api 요청을 https://spb.abc.com:8080/api로 전달한다.
    예를 들어:

    React 요청:  https://spb.abc.com/api/users
    Nginx가 전달하는 요청: https://spb.abc.com:8080/api/users

    proxy_pass는 백엔드 서버(8080번 포트에서 실행 중인 API 서버)로 요청을 전달하는 역할을 한다.

# proxy_set_header 설정
proxy_set_header Host $host;
    원본 요청의 Host 헤더를 유지한다.
    기본적으로 proxy_pass를 사용하면 Nginx는 원래 요청의 Host 헤더를 변경할 수 있다.
    Host 헤더를 유지하면 백엔드 서버에서 도메인 정보를 유지한 채 요청을 처리할 수 있음.


proxy_set_header X-Real-IP $remote_addr;
    클라이언트(사용자)의 실제 IP 주소를 백엔드 서버로 전달한다.
    예를 들어:

    클라이언트 IP: 123.45.67.89
    백엔드 서버에서 보는 IP: 123.45.67.89

    Nginx가 백엔드 서버를 대신 호출하기 때문에, 백엔드에서는 보통 클라이언트의 IP를 127.0.0.1로 인식할 수 있다.
    이 설정이 없으면 백엔드 서버는 모든 요청이 Nginx에서 온 것으로 인식할 수 있음.


proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    X-Forwarded-For 헤더는 클라이언트의 IP 주소를 보존하는 역할을 한다.
    예를 들어, 사용자가 여러 프록시를 거쳐 요청하는 경우:

    X-Forwarded-For: 123.45.67.89, 98.76.54.32, 192.168.1.10

        123.45.67.89 → 실제 클라이언트 IP
        98.76.54.32 → 중간 프록시
        192.168.1.10 → 마지막 프록시(Nginx)
    백엔드에서 로그를 분석할 때 실제 클라이언트의 IP를 확인할 수 있음.


proxy_set_header X-Forwarded-Proto $scheme;
    클라이언트가 요청할 때 사용한 프로토콜(HTTP 또는 HTTPS)을 백엔드 서버에 전달한다.
    예를 들어:

    클라이언트가 https://spb.abc.com/api 요청 → X-Forwarded-Proto: https
    클라이언트가 http://spb.abc.com/api 요청 → X-Forwarded-Proto: http

    백엔드에서 HTTPS 요청을 식별할 때 유용하다.

 

 

1
2
3
4
5
6
7
location /gis {
    proxy_pass http://192.168.123.91:18080;
    proxy_http_version 1.1;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
}
 

 

location /gis {
    /gis로 시작하는 모든 요청을 처리한다.
    예를 들어:

    클라이언트 요청:  http://spb.abc.com/gis/map
    Nginx가 전달하는 요청: http://192.168.123.91:18080/map
    /gis는 프록시 서버에서 제거되므로, 백엔드 서버(192.168.123.91:18080)는 /map으로 요청을 받음.


proxy_pass http://192.168.123.91:18080;
    백엔드 서버(192.168.123.91:18080)로 요청을 전달한다.
    예제:
    클라이언트 요청: http://spb.abc.com/gis/data
    Nginx가 전달하는 요청: http://192.168.123.91:18080/data
    /gis 경로는 자동으로 제거되며, 백엔드 서버가 그대로 요청을 처리할 수 있도록 설정됨.


만약 /gis를 유지해야 한다면, 다음처럼 수정 필요
proxy_pass http://192.168.123.91:18080/gis;

이렇게 하면 백엔드 서버에서 /gis/data 형태로 요청을 받게 된다.


proxy_http_version 1.1;
    백엔드와의 통신에서 HTTP/1.1을 사용하도록 설정.
    기본적으로 Nginx는 HTTP/1.0을 사용할 수 있음.
    HTTP/1.1을 사용하면 WebSocket과 같은 기능을 지원할 수 있음.


proxy_set_header Host $host;
    원본 요청의 Host 헤더를 유지하여 백엔드 서버로 전달한다.
    예를 들어:
    클라이언트 요청 Host: spb.abc.com
    백엔드 서버에서 보는 Host: spb.abc.com

    백엔드가 요청을 받을 때 Nginx의 IP 대신 원본 도메인 정보를 유지할 수 있음.


proxy_set_header X-Real-IP $remote_addr;
    클라이언트의 실제 IP를 백엔드 서버에 전달한다.
    기본적으로 Nginx가 백엔드에 요청을 전달할 때 자신(Nginx)의 IP로 요청을 보내기 때문에, 
    백엔드 서버에서는 클라이언트의 원래 IP를 확인할 수 없음.
    이 설정을 추가하면 백엔드가 원래 클라이언트의 IP를 알 수 있음.

728x90
블로그 이미지

Link2Me

,
728x90

implementation 'org.springframework.boot:spring-boot-starter-web' 라이브러리는 Back-end 단에서 필요한 의존성입니다. React는 Front-end 라이브러리로 JavaScript 기반에서 동작하며, 서버와의 통신은 보통 HTTP 요청(REST API) 또는 WebSocket을 사용합니다. 이 의존성은 Spring Boot에서 HTTP 요청을 처리하거나 RESTful API를 제공하기 위해 필요한 설정과 구성 요소(Web 관련 모듈 포함)를 포함하고 있습니다.

의존성의 역할

  • spring-boot-starter-web 의존성을 추가하면 다음과 같은 기능을 사용할 수 있습니다:
    1. Spring MVC: 컨트롤러(endpoint)를 정의하기 위한 기능.
    2. 내장 톰캣 서버: 애플리케이션을 실행하기 위한 웹 서버.
    3. Jackson 라이브러리 포함: JSON 형식의 요청/응답 바인딩.
    4. 기타 Spring Web 관련 설정 및 모듈.

따라서 React가 Front-end로 쓰이고, Back-end를 Spring Boot로 구현한다면 API 서버를 구축하기 위해 반드시 필요합니다. React와 Spring Boot는 별개이지만, React에서 만들어진 요청을 Spring Boot가 처리하려면 spring-boot-starter-web 의존성은 필수입니다.

728x90
블로그 이미지

Link2Me

,
728x90

Rocky 9.5 리눅스 환경에서 스프링부트 실행을 위해 준비한 스크립트이다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
##############################################
######### RockeyOS 9.5 Spring Boot 설치 ######
##############################################
# 스크립트는 반드시 관리자 권한에서 실행해야 한다.
# openssl 버전 확인 => TLS 1.3 지원
openssl version
 
dnf -y install expat-devel
 
# 시스템 업데이트
sudo dnf -y update
 
sudo dnf -y install wget unzip mc git nmap curl
 
# SSL 관련 패키지 설치 확인
sudo dnf -y install openssl openssl-devel
 
####################################################################################
# 방화벽 데몬 시작
systemctl start firewalld
 
# 서버 부팅 시 firewalld 데몬 자동 시작 설정
systemctl enable firewalld
 
firewall-cmd --permanent --add-service=http 
firewall-cmd --permanent --add-service=https
firewall-cmd --permanent --add-service=mysql
firewall-cmd --permanent --zone=public --add-port=3306/tcp
 
firewall-cmd --permanent --zone=public --add-port=8080/tcp
firewall-cmd --permanent --zone=public --add-port=3000/tcp
firewall-cmd --reload
firewall-cmd --list-all
 
####################################################################################
# tomcat 배포 사전 조건
# 1. JAVA가 설치되어 있어야 한다. (톰캣 9는 자바 11 이상이 필요)
# jar 파일은 내부 톰캣이 있기에 따로 톰캣을 설치하지 않아도 된다. 
####################################################################################
# 1. 기본 패키지 업데이트
sudo dnf update -y
 
# 2. Java 17 버전 설치
sudo dnf install -y java-17-openjdk java-17-openjdk-devel
java -version
 
# 3. Java 환경 변수 설정
echo "export JAVA_HOME=/usr/lib/jvm/java-17-openjdk" | sudo tee -/etc/profile.d/java.sh
echo "export PATH=\$JAVA_HOME/bin:\$PATH" | sudo tee -/etc/profile.d/java.sh
source /etc/profile.d/java.sh
 
# 여러개 설치되어 있는 자바 버전 선택하기
sudo alternatives --config java
 
 
# 4. Spring Boot 실행
# 아래 명령어를 수행하여 실행되는 메시지를 직접 육안으로 확인한다.
java -jar <jar파일명>
java -Xshare:off -jar /home/spring/SpringJWT/SpringJWT-0.0.1-SNAPSHOT.jar
 
# 5. Spring Boot 애플리케이션 실행
# 애플리케이션 실행 (백그라운드)
# 노트북에서 빌드(build)한 파일을 리눅스 서버로 업로드하고 아래와 같이 실행한다.
 
nohup java -Xshare:off -jar /home/spring/SpringJWT/SpringJWT-0.0.1-SNAPSHOT.jar --server.port=8080 > /var/log/springjwt.log 2>&1 &
 
 
# 필요한 Apache 모듈 활성화
sudo systemctl restart httpd
 
####################################################################################
# 프로세스 확인
ps aux | grep SpringJWT
 
# 프로세스 종료 (필요 시)
kill $(ps aux | grep 'SpringJWT' | awk '{print $2}')
 
# 종료 프로세스 작성
vi /usr/local/bin/kill_8080.sh
 
#!/bin/bash
 
# 8080 포트 사용 중인 프로세스 확인
PID=$(lsof -i :8080 -t)
 
if [ -"$PID" ]; then
    echo "8080 포트에서 실행 중인 프로세스(PID: $PID) 종료 중..."
    kill $PID
    sleep 2
 
    # 프로세스가 종료되지 않았으면 강제 종료
    if ps -p $PID > /dev/null; then
        echo "⚠️ 정상 종료되지 않아 강제 종료 진행..."
        kill -9 $PID
    fi
 
    echo "8080 포트 프로세스 종료 완료."
else
    echo "ℹ️ 8080 포트에서 실행 중인 프로세스가 없습니다."
fi
 
# 저장(wq)하고 빠져나온다.
 
# 실행권한 부여
sudo chmod +/usr/local/bin/kill_8080.sh
 
# 스크립트 실행
sudo /usr/local/bin/kill_8080.sh
 
####################################################################################
# systemd 서비스 등록 (서버 부팅 후 자동 실행)
vi /etc/systemd/system/springjwt.service
 
[Unit]
Description=Spring Boot Application - SpringJWT
After=network.target
 
[Service]
User=apache
Group=apache
ExecStart=/usr/bin/java -Xshare:off -jar /home/spring/SpringJWT/SpringJWT-0.0.1-SNAPSHOT.jar
SuccessExitStatus=143
Restart=always
RestartSec=5
StandardOutput=file:/var/log/springjwt.log
StandardError=file:/var/log/springjwt.log
 
[Install]
WantedBy=multi-user.target
 
#저장(wq)하고 빠져나온다.
 
# systemd 데몬 리로드
sudo systemctl daemon-reload
 
# 서비스 등록 및 실행
sudo systemctl enable springjwt
sudo systemctl start springjwt
 
# 실행 상태 확인
sudo systemctl status springjwt
 
# 서비스 중지 (필요 시)
sudo systemctl stop springjwt
 
# 실행 로그 확인
cat /var/log/springjwt.log
 
####################################################################################
 

 

 

728x90
블로그 이미지

Link2Me

,
728x90

React 에서 axios 를 통해서 백엔드에서 키를 호출하는 방법에 대해 기록한다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
import React from "react";
import {useState, useEffect, useRef} from "react";
import {Link, useNavigate} from "react-router-dom";
import axios from "axios";
import { JSEncrypt } from "jsencrypt"// npm install jsencrypt
 
const Signup = () => {
    //const baseUrl = process.env.REACT_APP_API_BASE_URL || "http://localhost:8080";
    const baseUrl = "https://spb.abc.com:8080";
 
    const navigate = useNavigate();
    const initData = {
        userID: '',
        password: ''
    }
 
    const [publicKey, setPublicKey] = useState("");
    const [sessionId, setSessionId] = useState(""); // 세션 ID 저장
    const isFetched = useRef(false); // 실행 여부 체크
 
    useEffect(() => {
        if (isFetched.current) return
        isFetched.current = true
 
        console.log("🔹 공개키 요청 실행됨");
        // 백엔드에서 공개키 가져오기
        axios.get(baseUrl + "/api/public-key")
            .then(response => {
                console.log("🔹 공개키 응답:", response.data);
                setPublicKey(response.data.publicKey);
                setSessionId(response.data.sessionId); // 세션 ID 저장
            })
            .catch(error => console.error("공개키 가져오기 실패", error));
    }, []);
 
    const encrypt = new JSEncrypt(); // Start our encryptor.
    encrypt.setPublicKey(publicKey); // Assign our encryptor to utilize the public key.
 
    const [formData, setFormData] = useState(initData);
    const [users, setUsers] = useState([]);
    // 첫번째 원소 : 현재 상태, 두번재 원소 : 상태를 바꾸어 주는 함수
    const [error, setError] = useState(null);
 
    const onChangeInput = (e) => {
        setFormData({
            ...formData,
            [e.target.name]: e.target.value
        });
        // e.target.name 은 해당 input의 name을 가리킨다.
        //console.log(formData);
    }
 
    const submitForm = (e) => {
        e.preventDefault();
        
        if (!sessionId) {
            console.error("세션 ID가 없습니다. 공개키를 다시 요청하세요.");
            setError(true);
            return;
        }
 
        const params = {
            username: formData.userID,
            password: encrypt.encrypt(formData.password), // 비밀번호 암호화
            //password: formData.password, 
            sessionId: sessionId // 세션 ID 포함
        }
        console.log(params);
        axios.post(baseUrl + '/login', params)
            .then((res) => {
                console.log(res);
                if (res.status === 200) {
                    console.log(res.data);
                    localStorage.setItem("accessToken", res.data.token);
                    axios.defaults.headers.common["Authorization"= "Bearer " + res.data.token;
                    navigate('/');
                } else {
                    console.log(res.data.message);
                    setError(true);
                }
            })
            .catch(error => {
                console.log(error.response)
            });
    }
 
    return (
        <div className="container h-100 mt-5">
            <div className="row d-flex justify-content-center align-items-center h-100">
                <div className="col-12 col-md-9 col-lg-7 col-xl-6">
                    <div className="card">
                        <div className="card-body p-5">
                            <h2 className="text-uppercase text-center mb-5">로그인</h2>
                            <form onSubmit={submitForm}>
                                <div className="form-outline mb-4">
                                    <label className="form-label" htmlFor="userID">userID</label>
                                    <input type="text" name="userID" onChange={onChangeInput} id="userID"
                                            className="form-control form-control-lg" value={formData.userID}
                                            required/>
                                </div>
 
                                <div className="form-outline mb-4">
                                    <label className="form-label" htmlFor="password">Password</label>
                                    <input type="password" name="password" onChange={onChangeInput} id="password"
                                            className="form-control form-control-lg" value={formData.password}
                                            required/>
                                </div>
 
                                { error &&
                                <div className="alert alert-danger" role="alert">
                                    로그인 정보를 다시 한번 확인하세요!
                                </div>
                                }
 
                                <div className="d-flex justify-content-center">
                                    <button type="submit"
                                            className="btn btn-primary btn-block btn-lg gradient-custom-3 text-body">로그인
                                    </button>
                                </div>
 
                                <p className="text-center text-muted mt-5 mb-0">
                                    <Link to="/register" className="fw-bold text-body"><u>회원가입</u></Link>
                                </p>
 
                            </form>
 
                        </div>
                    </div>
                </div>
            </div>
        </div>
    )
}
 
export default Signup

 

 

백엔드 : Spring Boot 설정 파일

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
package com.example.springjwt.config;
 
 
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 CorsMvcConfig implements WebMvcConfigurer {
 
    @Override
    public void addCorsMappings(CorsRegistry corsRegistry) {
        corsRegistry.addMapping("/**")
                .allowedOrigins(
                        "https://spb.abc.com",
                        "http://localhost:3000"
                ) // 정확한 출처 지정
                .allowedMethods("GET""POST""PUT""DELETE""OPTIONS"// 허용할 메서드 명확히 설정
                .allowCredentials(true// 인증 정보 포함 허용
                .allowedHeaders("Authorization""Content-Type""Cache-Control");
    }
}
 
/**
 * 이 설정을 유지하려면 SecurityConfig.java에서 .cors() 설정을 제거해야 한다.
 * (권장) WebMvcConfigurer를 삭제하고, SecurityConfig.java에서 CORS를 관리하는 것이 좋다.
 */
 
package com.example.springjwt.config;
 
import com.example.springjwt.jwt.CustomLogoutFilter;
import com.example.springjwt.jwt.JWTFilter;
import com.example.springjwt.jwt.JWTUtil;
import com.example.springjwt.jwt.LoginFilter;
import com.example.springjwt.repository.RefreshRepository;
import com.example.springjwt.service.RSAService;
import jakarta.servlet.http.HttpServletRequest;
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.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.logout.LogoutFilter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
 
import java.util.Arrays;
import java.util.Collections;
 
@Configuration
@EnableWebSecurity
public class SecurityConfig {
 
    // AuthenticationManager 가 인자로 받을 AuthenticationConfiguraion 객체 생성자 주입
    private final AuthenticationConfiguration authenticationConfiguration;
    private final JWTUtil jwtUtil;
    private final RefreshRepository refreshRepository;
    private final RSAService rsaService;
 
    public SecurityConfig(AuthenticationConfiguration authenticationConfiguration, JWTUtil jwtUtil, RefreshRepository refreshRepository, RSAService rsaService) {
 
        this.authenticationConfiguration = authenticationConfiguration;
        this.jwtUtil = jwtUtil;
        this.refreshRepository = refreshRepository;
        this.rsaService = rsaService;
    }
 
    //AuthenticationManager Bean 등록
    @Bean
    public AuthenticationManager authenticationManager(AuthenticationConfiguration configuration) throws Exception {
 
        return configuration.getAuthenticationManager();
    }
 
    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }
 
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
 
        http
                .cors((corsCustomizer -> corsCustomizer.configurationSource(new CorsConfigurationSource() {
 
                    @Override
                    public CorsConfiguration getCorsConfiguration(HttpServletRequest request) {
 
                        CorsConfiguration configuration = new CorsConfiguration();
                        configuration.setAllowedOriginPatterns(Arrays.asList(
                                "https://spb.abc.com",
                                "http://localhost:3000"
                        )); // allowedOrigins("*")을 사용하지 않고, 구체적인 출처를 명시
                        configuration.setAllowCredentials(true);
 
                        // allowedMethods("*") 대신 GET, POST, PUT, DELETE, OPTIONS를 명확하게 설정
                        // configuration.setAllowedMethods(Collections.singletonList("*"));
                        configuration.setAllowedMethods(Arrays.asList("GET""POST""PUT""DELETE""OPTIONS"));
 
                        // allowedHeaders("*") 대신 Authorization, Content-Type, Cache-Control을 지정
                        // configuration.setAllowedHeaders(Collections.singletonList("*"));
                        configuration.setAllowedHeaders(Arrays.asList("Authorization""Content-Type""Cache-Control"));
 
                        configuration.setExposedHeaders(Collections.singletonList("Authorization"));
 
                        configuration.setMaxAge(3600L);
 
                        return configuration;
                    }
                })));
 
        //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("/api/join""/login""/""/api/public-key""/api/pub-key").permitAll()
                        .requestMatchers("/admin").hasRole("ADMIN")
                        .requestMatchers("/reissue").permitAll()
                        .anyRequest().authenticated());
 
        http
                .addFilterBefore(new JWTFilter(jwtUtil), LoginFilter.class);
 
        http
                .addFilterAt(new LoginFilter(authenticationManager(authenticationConfiguration), jwtUtil, refreshRepository, rsaService), UsernamePasswordAuthenticationFilter.class);
 
        http
                .addFilterBefore(new CustomLogoutFilter(jwtUtil, refreshRepository), LogoutFilter.class);
        
        //세션 설정
        http
                .sessionManagement((session) -> session
                        .sessionCreationPolicy(SessionCreationPolicy.STATELESS));
 
        http
                .csrf((auth) -> auth.disable());
 
        return http.build();
    }
}
 

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package com.example.springjwt.controller;
 
import com.example.springjwt.dto.JoinDTO;
import com.example.springjwt.service.JoinService;
import com.example.springjwt.service.RSAService;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
 
import java.util.Map;
import java.util.UUID;
 
@RestController
@RequestMapping("/api")
public class AuthController {
 
    private final RSAService rsaService;
    private final JoinService joinService;
 
    @Autowired
    public AuthController(RSAService rsaService, JoinService joinService) {
        this.rsaService = rsaService;
        this.joinService = joinService;
    }
 
    /**
     * 회원 가입용 공개키
     */
//    @GetMapping("/pub-key")
//    public Map<String, String> getPubKey() {
//        return Map.of("publicKey", rsaService.getPubKey());
//    }
 
    @GetMapping("/pub-key")
    public Map<StringString> getPubKey(HttpServletRequest request) {
        String clientIp = getClientIp(request);
        int clientPort = request.getRemotePort(); // ✅ 클라이언트 포트 가져오기
        System.out.println("📌 클라이언트 IP: " + clientIp + " | 포트: " + clientPort);
        return Map.of("publicKey", rsaService.getPubKey());
    }
 
    private String getClientIp(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }
 
 
    /**
     * 로그인 용 공개키
     */
    @GetMapping("/public-key")
    public Map<StringString> getPublicKey() {
        String sessionId = UUID.randomUUID().toString(); // 클라이언트마다 새로운 세션 ID 생성
        String publicKey = rsaService.generateNewPublicKey(sessionId);
        return Map.of("sessionId", sessionId, "publicKey", publicKey);
    }
 
 
    @PostMapping("/join")
    public Map<StringString> joinProcess(@RequestBody JoinDTO joinDTO) {
        joinService.joinProcess(joinDTO, rsaService.getPriKey());
        return Map.of("message""회원가입 성공");
    }
 
}
 
 

 

 

728x90
블로그 이미지

Link2Me

,
728x90

Windows 11 노트북에서 접속할 때는 인증서가 필요없이도 잘 접속이 되는데 도메인 URL을 통해 접속하는 리눅스 서버에서 443 포트로 접속하는 통신을 하려면 인증서가 필요하다.

 

# SSL 인증서 로컬 시스템에 등록 (Rocky 9)
PKCS12 (Public Key Cryptograhic Standards)의 줄임말로 패스워드로 보호된 형식으로써, 여러 인증서 및 키를 포함할 수 있다. Java뿐만 아니라 여러 플랫폼에서 사용 가능하다.
Letsencrypt 에서 얻는 키를 이용하여 생성하면 된다.

# PKC12생성하기 : Java KeyStore (keystore.p12)로 변환
SSL 인증서를 Spring Boot에 추가하여 HTTPS를 8080 포트에서 활성화하려면, 다음 단계를 따라 Java KeyStore (JKS) 또는 PKCS12 포맷으로 변환하고 설정해야 한다.


openssl pkcs12 -export -in cert1.pem -inkey privkey1.pem -out keystore.p12 -name tomcat -password pass:changeit

 


-export: PKCS12 파일을 생성
-in cert1.pem  → 공개 인증서 파일
-inkey privkey1.pem 개인 키 파일
-out keystore.p12 변환된 인증서 저장 위치
-name tomcat 별칭(alias) 설정
-password pass:changeit  비밀번호 설정 (Spring Boot 설정에서 동일하게 사용해야 함)

생성된 인증서를 위의 3번과 같이 Windows 11 환경의 IntelliJ IDEA 구동한 

spring boot 프로젝트의 resources 폴더에 넣고 build 해서 생성된 파일을 리눅스 시스템에 업로드하면 된다.

 

 

 

728x90
블로그 이미지

Link2Me

,
728x90

Spring Boot Security 를 적용한 예시 화면이다.

로그인을 누르면 공개키 정보를 서버에서 가져오는 걸 콘솔화면에 출력되도록 설정하고 확인하는 과정이다.

 

 

로그인 정보를 입력하고 이후 결과 화면을 보면

 

아이디 정보와 비밀번호가 RSA 암호화된 것을 확인할 수 있다.

sessionId 는 RSA 암호화/복호화 KEY 쌍을 사용자별로 일정시간동안만 유지될 수 있도록 구현했다.

로그인이 정상적으로 잘 되면 accessToken 정보를 반환하도록 테스트 했다.

 

JWT 토큰에 대한 강좌는

https://www.youtube.com/watch?v=NPRh2v7PTZg&list=PLJkjrxxiBSFCcOjy0AAVGNtIa08VLk1EJ

 

강좌 시리즈가 설명이 너무 잘 되어 있어서 이 동영상 강좌를 따라서 연습했다.

이 동영상 강좌는 Front-End 에 대한 부분은 POSTMan Web 사이트를 이용하여 테스트를 하기 때문에 실제 환경 구성과는 거리가 있을 수 있다.

 

Windows 11 환경에서 인털리전스 IDEA 툴과 VSCode 로 Spring Boot 예제와 React 예제를 만들어서 구현 테스트 하는 것까지는 어렵지 않게 구현하는데 성공했다.

 

클라우드 서버에 올리는 걸 테스트 하면서 삽질을 엄청나게 했다.

React http://localhost:3000, Spring Boot http://localhost:8080 으로 기본 설정되기 때문에 윈도우에서 둘 간에 어려움없이 개발 테스트를 할 수 있다.

하지만 Rocky 9.5 Linux 서버가 있는 환경에서 구동 테스트를 시도했더니 엄청난 난관에 부딪치게 된다.

문제에 부딪치면 밤을 세워서라도 해결하고픈 욕망 때문에 어젯밤을 꼴딱 샜다. 그리고 해결하고 정리를 하면서 기록을 해두고 있다. 지금 이 순간에는 알지만, 시간이 지나면 금방 잊어버리게 된다.

기록된 결과는 이 글을 보는 방문자에게도 도움되지만, 나에게 가장 큰 도움이 된다.

 

JMeter 로 로그인 처리하는 방법을 배우면서 토큰 인증에 대한 이해가 필요했고, 토큰 인증에 대한 이해를 위해서 샘플 코드를 직접 구현하고 실 사이트에서 테스트해보고, 다시 Spring Boot 환경 구성을 해보면서 결과를 얻으려고 한다.

지금 정리하는 것은 Spring Boot 를 단계적으로 배워서 정리하는 것이 아니라 골인 지점에 대한 구현을 단기 속성으로 하고 나서 거꾸로 Spring Boot 동영상 강좌를 듣고 있는 중이다.

 

PHP 로 구현한 Secure Coding 코드 기반으로 보안 검증을 몇년간 받아보면서 시큐어코딩에 대한 이해도가 높아졌고, 그걸 기반으로 React 와 Spring Boot 기반의 RSA 암호화/복호화 코드를 구현 테스트 했다.

Javascript 에서 RSA 암호화로 패스워드(password)를 암호화해서 전송하고, 서버단에서 RSA 암호화 문자열을 복호화하여 DB에 있는 정보와 일치 여부를 확인한다.

이처럼 이종 언어간에 RSA 암호화/복호화하는 방법으로 결과가 성공이어야 한다.

구글링으로 구한 RSA 암호화/복호화 샘플이 이종 언어간에 제대로 동작되지 않는 걸 많이 경험한다.

Andorid 앱에서 RSA 암호화를 하고, Back-End 언어어서 RSA 복호화 처리를 하는 걸 구현해야만 보안 검증에 통과되기 때문에 이때도 수많은 삽질을 했었고, 이종 언어간에 동작하는 함수를 구현해서 사용했었다.

 

chatGPT 가 나날이 발전하여 많은 도움을 받고 있지만, 잘못된 정보를 전달하기도 해서 시행착오를 많이 겪는다.

Android APP 에서 구현해서 사용했던 함수를 Spring Boot 용으로 변환 요청을 했더니 엉터리로 결과를 반환한다.

이종 언어로 결과 반환을 요청하면 대부분 실패된 결과를 제공하더라.

728x90
블로그 이미지

Link2Me

,
728x90

인텔리전트 IDEA 툴에서 빌드하는 방법이다.

 

빌드된 파일은 아래 경로에서 확인할 수 있다.

 

윈도우에서 빌드한 파일을 리눅스 서버(Rocky Linux 9.5)에 업로드 한다.

 

빌드된 파일은 java -jar 빌드파일명.jar 명령어를 입력하여 실행할 수 있다.

 

구동중에 에러가 발생하면 메시지가 출력되며, 출력된 메시지를 분석해서 에러 원인을 제거해 나가면 된다.

 

728x90

'Spring Boot > IDEA' 카테고리의 다른 글

IntelliJ IDEA Auto Import 설정  (0) 2025.03.01
Build Gradle Update  (0) 2025.02.27
IntelliJ IDEA 에서 Spring 프로젝트 생성  (0) 2021.10.20
블로그 이미지

Link2Me

,
728x90

아래 함수는 Javascript 에서 암호화된 문자열을 PHP 언어에서 복호화 성공한 암호화 KEY 문자열과 복호화 KEY 문자열을 가지고 테스트 진행했다. 함수가 제대로 동작되는 걸 확인했다.

Android Java 코드로 RSA 암호화/복호화 함수 구현 것을 chatGPT에게 변환 요청한 것은 성공되지 못하고 실패했다.

chatGPT가 이기종 언어에서 구현한 코드를 변환 요청하면 대부분 실패하는 거 같다.

Front-End 언어에서 암호화하고 Spring Boot 에서 복호화가 정상적으로 되어야 한다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package com.example.springjwt.util;
 
import org.springframework.stereotype.Component;
 
import javax.crypto.Cipher;
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
 
@Component
public class RSAUtil {
 
    /**
     * 2048비트 RSA 키 쌍 생성
     */
    public KeyPair generateRSAKeyPair() {
        try {
            KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
            keyPairGenerator.initialize(2048);
            return keyPairGenerator.generateKeyPair();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("Failed to generate RSA key pair", e);
        }
    }
 
    /**
     * Base64 인코딩된 공개키 문자열을 PublicKey 객체로 변환 (X.509)
     */
    public PublicKey getPublicKeyFromBase64(String base64PublicKey) {
        try {
            byte[] decodedKey = Base64.getDecoder().decode(base64PublicKey);
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            return keyFactory.generatePublic(new X509EncodedKeySpec(decodedKey));
        } catch (Exception e) {
            throw new RuntimeException("Failed to retrieve public key from Base64", e);
        }
    }
 
    /**
     * Base64 인코딩된 개인키 문자열을 PrivateKey 객체로 변환 (PKCS8)
     */
    public PrivateKey getPrivateKeyFromBase64(String base64PrivateKey) {
        try {
            byte[] decodedKey = Base64.getDecoder().decode(base64PrivateKey);
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            return keyFactory.generatePrivate(new PKCS8EncodedKeySpec(decodedKey));
        } catch (Exception e) {
            throw new RuntimeException("Failed to retrieve private key from Base64", e);
        }
    }
 
    /**
     * Base64 인코딩된 공개키 문자열을 받아 RSA 암호화 수행 (RSA/ECB/PKCS1Padding 사용)
     */
    public String encryptRSA(String plainText, String base64PublicKey) {
        try {
            PublicKey publicKey = getPublicKeyFromBase64(base64PublicKey);
            Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
            cipher.init(Cipher.ENCRYPT_MODE, publicKey);
            byte[] encryptedBytes = cipher.doFinal(plainText.getBytes(StandardCharsets.UTF_8));
            return Base64.getEncoder().encodeToString(encryptedBytes);
        } catch (Exception e) {
            throw new RuntimeException("RSA encryption failed", e);
        }
    }
 
    /**
     * Base64 인코딩된 개인키 문자열을 받아 RSA 복호화 수행 (RSA/ECB/PKCS1Padding 사용)
     */
    public String decryptRSA(String encryptedText, String base64PrivateKey) {
        try {
            PrivateKey privateKey = getPrivateKeyFromBase64(base64PrivateKey);
            Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
            cipher.init(Cipher.DECRYPT_MODE, privateKey);
            byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedText));
            return new String(decryptedBytes, StandardCharsets.UTF_8);
        } catch (Exception e) {
            throw new RuntimeException("RSA decryption failed", e);
        }
    }
 
}
 

 

 

 

테스트 하는 방법은 아래와 같이 파일을 추가해서 하면 된다.

RSA Key 쌍을 생성하지 않아도 된다. RSA Key 쌍을 Linux 시스템에서 파일로 생성한 것으로 테스트를 진행했고 잘 동작되는 걸 확인했다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
 
package com.example.springjwt.util;
 
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
 
import java.security.KeyPair;
import java.security.PrivateKey;
import java.security.PublicKey;
 
@Component
public class RSAUtilRunner implements CommandLineRunner {
 
    private final RSAUtil rsaUtil;
 
    public RSAUtilRunner(RSAUtil rsaUtil) {
        this.rsaUtil = rsaUtil;
    }
 
    @Override
    public void run(String... args) throws Exception {
        // 1. RSA 키 쌍 생성
        KeyPair keyPair = rsaUtil.generateRSAKeyPair();
        PublicKey publicKey = keyPair.getPublic();
        PrivateKey privateKey = keyPair.getPrivate();
 
        // 2. Base64로 인코딩하여 키 출력
        String base64PublicKey = java.util.Base64.getEncoder().encodeToString(publicKey.getEncoded());
        String base64PrivateKey = java.util.Base64.getEncoder().encodeToString(privateKey.getEncoded());
 
        System.out.println("----- RSA 키 쌍 생성 완료 -----");
        System.out.println("공개키 (Base64): " + base64PublicKey);
        System.out.println("개인키 (Base64): " + base64PrivateKey);
 
        // 3. 암호화 테스트
        String originalText = "Hello, Spring Boot with RSA!";
        System.out.println("\n원본 텍스트: " + originalText);
 
        String encryptedText = rsaUtil.encryptRSA(originalText, base64PublicKey);
        System.out.println("암호화된 텍스트: " + encryptedText);
 
        // 4. 복호화 테스트
        String decryptedText = rsaUtil.decryptRSA(encryptedText, base64PrivateKey);
        System.out.println("복호화된 텍스트: " + decryptedText);
 
    }
 
}
 

 

 

다음에는 실제 React 에서 비밀번호를 암호화해서 전송하고, Spring Boot 에서 복호화 성공 여부를 확인하려고 한다.

728x90
블로그 이미지

Link2Me

,
728x90

인텔리제이 IDEA 사용 시 Auto Import 기능은 반드시 설정해야 코딩시 편하다.

Import 해야 할 대상이 2개 이상인 경우를 제외하고, 1개인 것은 자동으로 모두 추가/제거를 해준다.

 

728x90

'Spring Boot > IDEA' 카테고리의 다른 글

Spring Boot Build 하기  (0) 2025.03.08
Build Gradle Update  (0) 2025.02.27
IntelliJ IDEA 에서 Spring 프로젝트 생성  (0) 2021.10.20
블로그 이미지

Link2Me

,
728x90

build gradle 을 변경하고 나면 업데이트 처리를 해줘야 한다.

728x90

'Spring Boot > IDEA' 카테고리의 다른 글

Spring Boot Build 하기  (0) 2025.03.08
IntelliJ IDEA Auto Import 설정  (0) 2025.03.01
IntelliJ IDEA 에서 Spring 프로젝트 생성  (0) 2021.10.20
블로그 이미지

Link2Me

,
728x90

위와 같이 설정하고 Generate 하면 파일이 zip 으로 만들어진다.

이 파일을 C 드라이브 폴더에 압축을 풀고 Intellij IDEA 툴로 접속한 다음 MariaDB 연결을 위한 설정을 해야 한다.

처음부터 MariaDB Driver를 선택해야 하는데 실수한 것이라는 걸 뒤늦게 알았다.

 

Spring Boot 에서 MariaDB 연결

안정적인 버전은 3.3.3 이라고 권고하고 있다.

 

MariaDB Driver 를 선택하면 설치된다.

 

application.yml 파일을 새로 생성하여 아래와 같이 추가해준다.

ddl-auto : create 는 처음에는 이렇게 설정하지만, 나중에는 none 으로 변경해야 한다.

 

MariaDB를 설치하고 MariaDB 연결이 제대로 된 것인지 확인한다.

 

MariaDB 를 선택하고 아래와 같이 설정해준다.

 

 

마지막으로 Run 을 했을 때 에러가 발생하지 않고 제대로 동작되는 걸 확인해야 한다.

 

728x90
블로그 이미지

Link2Me

,
728x90

내 PC에는 PHP 를 연습하기 위해서 Autoset10 (Apache + PHP + MariaDB)가 설치되어 있다.

이미 설치된 MariaDB 와 연동하여 데이터 추가되는 걸 테스트했다.

앞에서 설명한 MySQL 버전과 다른 부분만 추가로 적어둔다.

 

1. 의존성 추가(build.gradle)

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-web'
    implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
    //implementation 'mysql:mysql-connector-java'
    implementation 'org.mariadb.jdbc:mariadb-java-client'
 
    compileOnly 'org.projectlombok:lombok'
    annotationProcessor 'org.projectlombok:lombok'
 
    runtimeOnly ('org.springframework.boot:spring-boot-devtools')
    runtimeOnly 'org.mariadb.jdbc:mariadb-java-client'
 
    testImplementation 'org.springframework.boot:spring-boot-starter-test'
}

 

2. application.properties 에 DB 정보 추가하기

# MariaDB Driver
spring.datasource.driver-class-name=org.mariadb.jdbc.Driver
 
# DB Source URL
#spring.datasource.url=jdbc:mariadb://192.168.1.20:3306/studydb?useSSL=false
spring.datasource.url=jdbc:mariadb://localhost:3306/studydb?serverTimezone=Asia/Seoul
<IP>:<Port/<DB> ==> localhost:3306/study_db
 
# DB username
spring.datasource.username=codefox
 
# DB password
spring.datasource.password=Autoset12#$
 
spring.jpa.show-sql=true 
 
# 테이블 스키마를 생성하지 않았을 경우 자동으로 테이블 생성
#spring.jpa.hibernate.ddl-auto=update
 
 

 

3. 테이블 스키마

CREATE TABLE User (
  `uid` int(11) NOT NULL,
  `account` varchar(45) NOT NULL,
  `email` varchar(45) DEFAULT NULL,
  `phone_number` varchar(15) DEFAULT NULL COMMENT '전화번호',
  `created_at` datetime NOT NULL,
  `created_by` varchar(45) NOT NULL,
  `updated_at` datetime DEFAULT NULL,
  `updated_by` varchar(45) DEFAULT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
 
ALTER TABLE `user`
  ADD PRIMARY KEY (`uid`),
  ADD UNIQUE KEY `account` (`account`);
 
ALTER TABLE `user`
  MODIFY `uid` int(11) NOT NULL AUTO_INCREMENT;
COMMIT;
 
 
use mysql;
create user codefox@localhost;
grant all privileges on studydb.* to codefox@localhost identified by 'Autoset12#$';
flush privileges;
 

 

 

MariaDB 연결이 제대로 된 것인지 1차 확인하는 방법이다.

 

 

728x90

'Spring Boot > Basic' 카테고리의 다른 글

Spring Boot 배포(Deploy) 스크립트  (1) 2025.03.14
Spring Boot MariaDB 연결  (0) 2025.02.22
Spring Boot JPA(Java Persistence API ) - MySQL  (0) 2021.10.23
[SpringBoot] Lombok  (0) 2021.10.22
MariaDB 10.6 설치  (0) 2021.10.21
블로그 이미지

Link2Me

,
728x90

JPA는 자바 객체와 DB 테이블 간의 매핑을 처리하는 ORM(Object Relational Mapping) 기술의 표준이다.

JPA를 이용하기 위해서는 maven(메이븐)을 이용하거나 gradle(그래들)을 이용하여 패키지를 관리한다.

 

1. 프로젝트 의존성 추가(build.gradle)

dependencies {
    implementation 'mysql:mysql-connector-java'
    implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
}

 

2. application.properties 에 DB 정보 추가하기

# MySQL 설정 
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver 
 
# DB Source URL 
spring.datasource.url=jdbc:mysql://<IP>:<Port/<DB>?useSSL=false
<IP>:<Port/<DB> ==> localhost:3306/study_db
 
 
# DB username 
spring.datasource.username=<username> 
 
# DB password 
spring.datasource.password=<password> 
 
true 설정시 JPA 쿼리문을 볼 수 있다 
spring.jpa.show-sql=true 
 
# DDL(create, alter, drop) 정의시 DB의 고유 기능을 사용할 수 있다. 
spring.jpa.hibernate.ddl-auto=update 
 
# JPA의 구현체인 Hibernate가 동작하면서 발생한 SQL의 가독성을 높여준다. 
spring.jpa.properties.hibernate.format_sql=true
 

 

DB와 통신이 정상적으로 잘 되는지 먼저 확인을 해야 한다.

DB와 통신이 잘 되는데도 불구하고 에러가 발생해서 엄청 삽질을 했는데 결국 사소한 문제였다.

spring.datasource.password=<password> 패스워드 뒤에 공백이 추가되어 있는 줄 모르고 있었다.

 

3. 테이블 설계

   ㅇ DB 생성 : CREATE DATABASE studydb default CHARACTER SET UTF8;

 

   ㅇ 테이블 생성

       - 테이블을 직접 생성해주었는데, 테이블 생성하지 않고 자동으로 추가되는 것도 확인했다.

       - 테이블명을 User 로 첫글자를 대문자로 해서 생성후 테스트해보니, Spring Boot 에서 소문자 user 생성하더라.

CREATE TABLE `user` (
  `uid` int(11) NOT NULL,
  `account` varchar(45) NOT NULL,
  `email` varchar(45) DEFAULT NULL,
  `phone_number` varchar(15) DEFAULT NULL COMMENT '전화번호',
  `created_at` datetime NOT NULL,
  `created_by` varchar(45) NOT NULL,
  `updated_at` datetime DEFAULT NULL,
  `updated_by` varchar(45) DEFAULT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
 
ALTER TABLE `user`  ADD PRIMARY KEY (`uid`);
ALTER TABLE `user`  MODIFY `uid` int(11) NOT NULL AUTO_INCREMENT;
 

   ㅇ 사용자 권한 추가

MySQL 5.7 버전을 설치하고 테스트를 했더니, 패스워드 지정시 기본으로 영문 소문자, 대문자, 숫자, 특수문자를 포함해서 8자리 이상 입력해야 되더라.

// 비밀번호 정책 확인
show variables like 'validate_password%';

// DB 생성
create database studydb default character set utf8;

 

// 사용자 생성 및 권한 추가

use mysql;
create user codefox@localhost identified by 'Autoset12#$';
grant all privileges on studydb.* to codefox@localhost;
flush privileges;

use mysql;
create user codefox@'192.168.1.25' identified by 'Autoset12#$';
grant all privileges on studydb.* to codefox@'192.168.1.25';
flush privileges;

 

※ Virtual Box를 설치하여 CentOS 7 + MySQL 5.7 버전을 설치하고 192.168.1.X 동일 사설 네트워크 환경에서 테스트하기 위한 설정이다. 192.168.1.25 는 Windows 10 이 설치된 PC 의 IP주소이고 CentOS 7 서버의 IP주소는 192.168.1.20 이다.

 

4. Entity 클래스

package com.example.study.model.entity;
 
import lombok.*;
 
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import java.time.LocalDateTime;
import java.time.LocalTime;
 
@Data
@AllArgsConstructor
@NoArgsConstructor
@Entity
public class User {
    // DB의 테이블의 이름과 동일한 User 클래스 생성
 
    @Id  // @Id : Primary Key를 의미
    @GeneratedValue(strategy = GenerationType.IDENTITY) //MySQL의 AUTO_INCREMENT를 사용
    private Long idx;
    private String account;
    private String email;
    private String phoneNumber;
    private LocalDateTime createdAt;
    private String createdBy;
    private LocalDateTime updatedAt;
    private String updatedBy;
}
 

 

5. JPA Repository 생성

@Repository
- 따로 쿼리문 작성없이 생성, 조회, 업데이트, 삭제(CRUD)를 할 수 있게 기능을 제공해줌
- 제너릭 타입으로는 첫번째부터, <Entity, PrimaryKey의 타입>을 넣는다

 

package com.example.study.repository;
 
import com.example.study.model.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
 
@Repository
public interface UserRepository extends JpaRepository<User,Long> {
}
 

 

 

6. 테스트

테이블에 User 데이터가 잘 생성되는지 테스트하는 과정이다.

프로젝트 구조 확인

 

package com.example.study.repository;
 
import com.example.study.StudyApplicationTests;
import com.example.study.model.entity.User;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
 
import java.time.LocalDateTime;
 
@SpringBootTest
public class UserReposityTest extends StudyApplicationTests {
 
    // Dependency Injection(DI)
    @Autowired
    private UserRepository userRepository;
 
    @Test
    public void create(){
        User user = new User();
        user.setAccount("test01");
        user.setEmail("jsk005@naver.com");
        user.setPhoneNumber("010-0001-0000");
        user.setCreatedAt(LocalDateTime.now());
        user.setCreatedBy("admin01");
 
        User newUser = userRepository.save(user);
        System.out.println("newUser :" + newUser);
    }
 
    public void read(){
 
    }
 
    public void update(){
 
    }
 
    public void delete(){
 
    }
}
 

 

3번을 눌러서 테스트하면 DB에 데이터가 저장되는지 여부를 확인할 수 있다.

 

 

 

MySQL 과 MariaDB 모두 테스트를 했고, User 데이터가 잘 생성되는걸 확인할 수 있다.

Run 정보를 확인해보면....

 

728x90

'Spring Boot > Basic' 카테고리의 다른 글

Spring Boot 배포(Deploy) 스크립트  (1) 2025.03.14
Spring Boot MariaDB 연결  (0) 2025.02.22
Spring Boot JPA(Java Persistence API ) - MariaDB  (0) 2021.10.23
[SpringBoot] Lombok  (0) 2021.10.22
MariaDB 10.6 설치  (0) 2021.10.21
블로그 이미지

Link2Me

,
728x90

Lombok이란 어노테이션 기반으로 코드를 자동완성 해주는 라이브러리이다. Lombok을 이용하면 Getter, Setter, Equlas, ToString 등과 다양한 방면의 코드를 자동완성 시킬 수 있다.

 

 

package com.example.study.model;
 
import lombok.AllArgsConstructor;
import lombok.Data;
 
// getter, setter 를 annotation 으로 생성시켜주는 라이브러리 : lombok
@Data
@AllArgsConstructor
public class SearchParam {
    private String account;
    private String email;
    private int page;
}
 

 

@Data 어노테이션을 활용하면 @ToString, @EqualsAndHashCode, @Getter, @Setter, @RequiredArgsConstructor를 자동완성 시켜준다.

 

@AllArgsConstructor는 모든 변수를 사용하는 생성자를 자동완성 시켜주는 어노테이션이다.

 

@NoArgsConstructor는 어떠한 변수도 사용하지 않는 기본 생성자를 자동완성 시켜주는 어노테이션이다.

 

@RequiredArgsConstructor는 특정 변수만을 활용하는 생성자를 자동완성 시켜주는 어노테이션이다. 생성자의 인자로 추가할 변수에 @NonNull 어노테이션을 붙여서 해당 변수를 생성자의 인자로 추가할 수 있다. 아니면 해당 변수를 final로 선언해도 의존성을 주입받을 수 있다.

 

@EqualsAndHashCode 어노테이션을 활용하면 클래스에 대한 equals 함수와 hashCode 함수를 자동으로 생성해준다.

https://mangkyu.tistory.com/78 에 어노테이션과 예제가 상세히 설명되어 있다.

 

Lombok 은 코틀린 data class 와 유사한 거 같다.

Android Studio 개발 툴과 IntelliJ IDEA 툴은 Jetbrains 에서 만든 툴이라 메뉴 사용법이 거의 동일하다.

 

IntelliJ IDEA 툴에서 아래 그림과 같이 확인해 보면 getter, setter, constructor 가 생성되어 있는 걸 확인할 수 있다.

 

 

@Getter @Setter 만 적용할 경우

 

 

 

728x90
블로그 이미지

Link2Me

,
728x90

익숙하게 사용하기 위해서 Autoset10 을 설치하고 MariaDB를 구동하였으나 구동 자체가 안된다.

그래서 별도로 MariaDB 10.6을 다운로드 받아서 설치했다.

윈도우 기반에서 Spring boot 을 배우기 위해서 MariaDB 를 설치하는 것이다.

https://mariadb.org/ 사이트에 접속하여 파일을 다운로드한다.

 

 

 

 

 

 

여기까지 설정하고 나면 자동으로 MairaDB 데몬이 떠있다.

DB 생성 및 테이블 추가하는 것은 phpMyAdmin 을 이용하여 할 것이다.

윈도우10 기반으로 서버를 운용은 하지 않을 것이고, 단지 개발 연습용으로 활용할 것이기 때문에 익숙한 툴을 이용하여 DB 구조 설계 및 연습을 하면 된다.

 

728x90
블로그 이미지

Link2Me

,
728x90

온라인 강의가 IDEA 로 되어 있어서 기본 개발 환경을 설정하는 방법을 적어둔다.

인텔리제이(IntelliJ IDEA)에서 스프링 프레임워크(Spring Framework) 프로젝트를 생성하는 과정이다.

 

 

 

Type 을 Maven 대신 Gradle 로 선택한다.

 

 

 

 

Settings -> Build, Execution, Deployment -> Annotation Processors

 

 

 

 

 

실행버튼을 누르면 컴파일 되고 Tomcat 이 8080포트로 구동되었다는 걸 확인할 수 있다.

 

이제 크롬 브라우저에서 확인해본다.

http://localhost:8080/api/getMethod/

 

 

GET Method

GET 메소드에 대한 처리를 알아보기 위한 코드 작성이다.

 

 

package com.example.study.model;
 
public class SearchParam {
    private String account;
    private String email;
    private int page;
 
    public String getAccount() {
        return account;
    }
 
    public void setAccount(String account) {
        this.account = account;
    }
 
    public String getEmail() {
        return email;
    }
 
    public void setEmail(String email) {
        this.email = email;
    }
 
    public int getPage() {
        return page;
    }
 
    public void setPage(int page) {
        this.page = page;
    }
}
 

 

 

package com.example.study.controller;
 
import com.example.study.model.SearchParam;
import org.springframework.web.bind.annotation.*;
 
@RestController
@RequestMapping("/api")  // localhost:8080/api
public class GetController {
 
    @RequestMapping(method = RequestMethod.GET, path="/getMethod"// localhost:8080/api/getMethod
    public String getRequest(){
        return "Hi, getMethod";
    }
 
    @GetMapping("/getParameter")  // http://localhost:8080/api/getParameter?id=abc&password=12345
    public String getParameter(@RequestParam String id, @RequestParam String password){
        System.out.println("id : " + id);
        System.out.println("pw : " + password);
 
        return id+password;
    }
 
    // http://localhost:8080/api/getMultiParameter?account=abc&email=jsk005@naver.com&page=2
    @GetMapping("/getMultiParameter")
    public SearchParam getMultiParameter(SearchParam searchParam){
        System.out.println(searchParam.getAccount());
        System.out.println(searchParam.getEmail());
        System.out.println(searchParam.getPage());
 
        return searchParam;
    }
}
 

 

POST

크롬브라우저 확장 프로그램 설치

https://chrome.google.com/webstore/detail/talend-api-tester-free-ed/aejoelaoggembcahagimdiliamlcdmfm 를 설치한다.

 

 

package com.example.study.controller;
 
import com.example.study.model.SearchParam;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
 
@RestController
@RequestMapping("/api")
public class PostController {
 
    // http://localhost:8080/api/postMethod
    // 크롬 확장 프로그램을 설치하면 테스트할 수 있다.
    // https://chrome.google.com/webstore/detail/talend-api-tester-free-ed/aejoelaoggembcahagimdiliamlcdmfm
    @PostMapping(value = "/postMethod")
    public SearchParam postMethod(@RequestBody SearchParam searchParam){
        return searchParam;
    }
}
 

 

 

전송 결과

728x90

'Spring Boot > IDEA' 카테고리의 다른 글

Spring Boot Build 하기  (0) 2025.03.08
IntelliJ IDEA Auto Import 설정  (0) 2025.03.01
Build Gradle Update  (0) 2025.02.27
블로그 이미지

Link2Me

,