2025년 10월 24일 금요일 (100일차)

Jeonghoon·2025년 10월 24일

jeonghoon's Study

목록 보기
103/128

🍪 @CookieValue & ⚛️ React 연동 가이드


🍪 @CookieValue

💡 개념 요약

  • Spring MVC에서 쿠키를 간편하게 가져오기 위한 어노테이션
  • 컨트롤러 메서드의 매개변수에 직접 주입하여 쿠키 값을 바로 사용할 수 있다.

🧩 사용 예시

@CookieValue(value = "loginUser", required = false) String token
항목설명
value가져올 쿠키의 이름 지정 (예: "loginUser")
required쿠키가 존재하지 않아도 예외 발생 방지 (false 권장)
token쿠키에 저장된 JWT 혹은 사용자 식별값

🔐 활용 예시 — 로그인 상태 확인

@GetMapping("/check-login")
public ResponseEntity<String> checkLogin(@CookieValue(value="loginUser", required=false) String token) {
    if (token != null) {
        return ResponseEntity.ok("로그인 상태입니다.");
    } else {
        return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("로그인이 필요합니다.");
    }
}

💡 Tip:
@CookieValueHttpServletRequest 없이도 쿠키 접근이 가능하므로, 간결한 코드 작성이 가능하다.


⚙️ 응용 — 쿠키 기반 권한 확인 메서드

메서드기능설명
getRoleFromCookie()쿠키로부터 권한(Role) 추출JWT decode 후 Role 정보 확인
isLoginUser()로그인 여부 판단쿠키 존재 여부로 로그인 상태 판별
logoutCookie()쿠키 삭제setMaxAge(0) 으로 만료 처리

⚛️ React 연동

🌍 CORS (Cross-Origin Resource Sharing)

React와 Spring Boot를 연동할 때는 CORS 설정이 필수이다.
특히 Spring Security를 사용하는 경우, 기본 CORS 정책이 차단되어 있기 때문에
CorsConfig를 명시적으로 설정해야 한다.

✅ 설정 방법

httpSecurity.cors(Customizer.withDefaults());
항목설명
httpSecurity.cors()Spring Security에서 CORS를 활성화
Customizer.withDefaults()기본 CORS 설정 사용 (필요 시 별도 설정 가능)
주의사항CORS 설정은 컨트롤러 @CrossOrigin 보다 Security 설정이 우선됨

💡 추가 확장 예시 (별도 설정 클래스)

@Configuration
public class CorsConfig {
    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.addAllowedOrigin("http://localhost:3000"); // React 개발 서버
        configuration.addAllowedMethod("*");
        configuration.addAllowedHeader("*");
        configuration.setAllowCredentials(true); // 쿠키 허용
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }
}

⚠️ 주의: setAllowCredentials(true) 를 설정할 경우 AllowedOrigin("*") 대신
정확한 도메인(URL) 을 지정해야 한다. (예: http://localhost:3000)


🔑 권한 확인 (React Routing)

React에서 사용자 권한(Role) 에 따라 접근 가능한 페이지를 제한하려면,
RoleRoute 컴포넌트를 만들어 조건부 렌더링을 수행한다.

✅ 예시 코드

import { Navigate, Outlet } from "react-router-dom";

const RoleRoute = ({ role, allow }) => {
  return allow.includes(role) ? <Outlet /> : <Navigate to="/unauthorized" />;
};
export default RoleRoute;
항목설명
role현재 로그인한 사용자의 권한 (예: "ADMIN", "USER")
allow접근을 허용할 권한 배열 (예: ["ADMIN"])
Outlet자식 라우트를 렌더링
Navigate권한이 없는 경우 리다이렉션 수행

🌈 사용 예시 (App.js)

<Route element={<RoleRoute role={userRole} allow={["ADMIN"]} />}>
  <Route path="/admin" element={<AdminPage />} />
</Route>

🧾 요약 정리

구분핵심 내용비고
🍪 @CookieValue쿠키를 매개변수로 직접 주입HttpServletRequest 불필요
🧱 JWT + Cookie 인증쿠키 내 JWT 값으로 로그인 상태 확인클라이언트 관리
⚛️ CORS 설정React와 연동 시 필수httpSecurity.cors() 설정
🔑 권한 확인 (RoleRoute)사용자 Role 기반 접근 제어React Router와 함께 사용
🚀 추가 권장axios 전역 설정에서 withCredentials: true 지정쿠키 전달 허용

💡 추가 팁

1️⃣ React Axios 설정 예시

axios.defaults.withCredentials = true;
axios.defaults.baseURL = "http://localhost:8080";

2️⃣ Spring Boot + React 통합 시 HTTPS 환경에서는

  • cookie.setSecure(true) 설정 필요
  • CORS의 setAllowCredentials(true) 필수

  • 추가 예시는 Web_Spring2 의 web2 확인

0개의 댓글