@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:
@CookieValue는HttpServletRequest없이도 쿠키 접근이 가능하므로, 간결한 코드 작성이 가능하다.
| 메서드 | 기능 | 설명 |
|---|---|---|
getRoleFromCookie() | 쿠키로부터 권한(Role) 추출 | JWT decode 후 Role 정보 확인 |
isLoginUser() | 로그인 여부 판단 | 쿠키 존재 여부로 로그인 상태 판별 |
logoutCookie() | 쿠키 삭제 | setMaxAge(0) 으로 만료 처리 |
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에서 사용자 권한(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 | 권한이 없는 경우 리다이렉션 수행 |
<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) 설정 필요 setAllowCredentials(true) 필수