2025년 11월 12일 수요일 (113일차)

Jeonghoon·2025년 11월 12일

jeonghoon's Study

목록 보기
116/128

🧩 프로젝트 관련 정리


🔐 [ 권한별 허용 설정 (Spring & React) ]

☕ Spring Security에서의 권한 설정

  • Spring Security를 사용하여 요청 경로별 권한 제어 가능

📘 예시 코드

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
    http.authorizeHttpRequests(auth -> auth
        .requestMatchers("/admin/**").hasRole("ADMIN")     // ADMIN 권한만 접근 가능
        .requestMatchers("/user/**").hasAnyRole("USER", "ADMIN") // USER, ADMIN 모두 가능
        .requestMatchers("/public/**").permitAll()          // 모든 사용자 접근 허용
    )
    .csrf(csrf -> csrf.disable()) // 개발 단계에서 CSRF 비활성화
    .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS));

    return http.build();
}

💡 Tip:

  • hasRole("권한명") : 특정 권한만 접근 가능
  • hasAnyRole("권한1", "권한2") : 여러 권한 허용
  • permitAll() : 누구나 접근 가능

⚛️ React에서의 권한별 라우팅

  • React에서는 라우터 보호(Protected Route) 형태로 권한 제어 구현

📘 예시 코드

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

const RoleRoute = ({ role, allow }) => {
  return allow.includes(role) ? <Outlet /> : <Navigate to="/denied" />;
};

// 사용 예시
<Route element={<RoleRoute role={userRole} allow={["ADMIN", "USER"]} />}>
  <Route path="/dashboard" element={<Dashboard />} />
</Route>

🧠 Tip:
Outlet은 자식 라우트를 렌더링하는 역할을 한다.
Navigate는 접근 권한이 없을 때 리다이렉트 처리에 사용된다.


🍪 [ 쿠키 보안 설정 ]

  • 쿠키는 사용자 브라우저에 데이터를 저장하는 방식으로, 보안 설정이 중요하다.

⚙️ 주요 설정

속성설명
setHttpOnly(true)자바스크립트를 통한 쿠키 접근 차단 (XSS 방지)
setSecure(true)HTTPS 환경에서만 쿠키 전송 허용
setPath("/")쿠키 접근 경로 지정
setMaxAge(3600)쿠키 유효기간 (초 단위) 설정

📘 예시 코드

Cookie cookie = new Cookie("loginUser", userToken);
cookie.setHttpOnly(true);
cookie.setSecure(true);     // HTTPS 환경에서만 사용 가능
cookie.setPath("/");
cookie.setMaxAge(3600);
response.addCookie(cookie);

⚠️ 주의:
setSecure(true)HTTPS 환경에서만 작동하며,
HTTP 환경(localhost 등) 에서는 작동하지 않는다.


🧩 [ AOP (Aspect Oriented Programming) ]

  • 관점 지향 프로그래밍으로, 공통 관심사를 모듈화하여 코드 중복 제거에 활용된다.

✨ 주요 개념

용어설명
Aspect공통 기능을 모듈화한 클래스
JoinPointAOP가 적용될 수 있는 지점 (메소드 호출 등)
Advice실제 실행될 공통 기능 (before, after, around 등)
PointcutAOP를 적용할 메소드나 패키지의 지정 경로

📘 예시 코드

@Aspect
@Component
public class LogAspect {

    @Before("execution(* com.example.service.*.*(..))")
    public void beforeLog(JoinPoint joinPoint) {
        System.out.println("[Before] 호출 메소드: " + joinPoint.getSignature().getName());
    }

    @AfterReturning("execution(* com.example.service.*.*(..))")
    public void afterLog(JoinPoint joinPoint) {
        System.out.println("[After] 실행 완료: " + joinPoint.getSignature().getName());
    }
}

💡 적용 효과:

  • 서비스 전후 로깅, 보안 검사, 트랜잭션 관리 등 중복 코드 제거 가능
  • 코드의 핵심 로직과 보조 로직을 명확히 분리할 수 있다.

0개의 댓글