본문 바로가기
Web Programming/JavaScript

[React + SpringSecurity + DB] 로그인 구현하기 (frontend)

by jaey0ng 2024. 1. 18.

 

리엑트와 스프링을 연결할 때 리엑트 설정을 하셨을 겁니다.

 

axiosInstance.jsx를 만들었다던가, App.jsx를 수정했다던가 저는 둘다 수정했기 때문에 전부 있는 상황에서 구현하겠습니다.

 

App.jsx

function App() {
    useEffect(() => {
        // 서버에서 렌더링된 HTML 문서에서 CSRF 토큰을 가져오는 로직
        const csrfTokenMeta = document.querySelector("meta[name='_csrf']");

        // CSRF 토큰이 존재하는지 확인 후 요청 헤더에 추가
        if (csrfTokenMeta) {
            const csrfToken = csrfTokenMeta.content;
            axios.defaults.headers.common["X-XSRF-TOKEN"] = csrfToken;
        }
    }, []);

    return (
        ...
    );
}

export default App;

 

useEffect 안에 CSRF 토큰 관련 로직을 추가해줍니다.

 

위 로직이 없다면 스프링시큐리티에서 CSRF 토큰을 비활성화하지 않고 조회는 불가능합니다.

 

axiosInstance.jsx

import axios from "axios";

const axiosInstance = axios.create({
    baseURL: "/api",
    headers: {
        "Content-Type": "application/json",
    },
    withCredentials: true,
});

export default axiosInstance;

 

withCredentials:true 도 꼭 붙여주셔야 합니다. (토큰인증을 진행할 시)

 

Login.jsx

import React, { useState } from "react";
import axiosInstance from "../../api/axiosInstance";

const SignInView = () => {
    const [loginInput, setLoginInput] = useState({
        userId: "",
        password: "",
    });

    const handleInputChange = (e) => {
        setLoginInput((prev) => ({ ...prev, [e.target.name]: e.target.value }));
    };

    const onLogin = async (e) => {
        e.preventDefault();

        try {
            const res = await axiosInstance.post(`/com/login`, {
                userId: loginInput.userId,
                password: loginInput.password,
            });
            if (res.status === 200) {
                console.log(res.data);
            }
        } catch (error) {
            console.log(error);
        }
    };

    return (
        <>
            <h2>로그인</h2>
            <form>
                <div>
                    <label
                        htmlFor="userId"
                    >
                        아이디
                    </label>
                    <input
                        type="userId"
                        id="userId"
                        name="userId"
                        value={loginInput.userId}
                        onChange={handleInputChange}
                        placeholder="아이디"
                        required
                    />
                </div>
                <div>
                    <label
                        htmlFor="password"
                    >
                        비밀번호
                    </label>
                    <input
                        type="password"
                        id="password"
                        name="password"
                        value={loginInput.password}
                        onChange={handleInputChange}
                        placeholder="비밀번호"
                        required
                    />
                </div>
                <button
                    type="submit"
                    onClick={onLogin}
                >
                    로그인
                </button>
            </form>
        </>
    );
};

export default SignInView;

 

CSS 부분은 직접하셔야합니다.

 

아이디, 비밀번호를 입력받고 loginInput에 담고나서 axios를 통해 백앤드로 데이터를 보내주고

if(res===200) {  } 로직을 통해 성공했을 때 로직을 작성하시면 되겠습니다.

 

 

백엔드 부분은 아래 링크로 들어가시면 되겠습니다.

2024.01.18 - [Web Programming/Java] - [React + SpringSecurity + DB] 로그인 구현하기 (Backend)

 

[React + SpringSecurity + DB] 로그인 구현하기 (Backend)

저의 예시는 스프링 2.5.5 버전입니다. 버전에 따라 코드가 다를 수 있으므로 버전에 맞게 코딩해주시면 되겠습니다. 스프링 시큐리티부터 만들어볼까 합니다. build.gradle implementation 'org.springframewo

jaey0ng.tistory.com