spring

[로그인구현] Spring-React를 이용한 로그인 구현(세션)

[dev] hiro 2024. 12. 24. 02:01
제가 공부한 내용을 정리하는 블로그입니다.
아직 많이 부족하고 배울게 너무나도 많습니다. 틀린내용이 있으면 언제나 가감없이 말씀해주시면 감사하겠습니다😁

스프링부트와 리액트를 활용해 로그인을 구현 프로젝트를 진행합니다. 순서는
1. 프로젝트 초기화
2. 쿠키를 이용한 로그인 구현
3. 세션을 이용한 로그인 구현
4. JWT 토큰을 활용한 로그인 구현
입니다. 

세번째는 세션을 이용한 로그인 구현입니다.

서론

이전 쿠키 포스팅에서 STATELESS한 HTTP 프로토콜에서 STATEFUL한 서비스를 위한 장치로 헤더에 쿠키를 저장하는 로직으로 설계하였습니다.

하지만 해당 방법은 개인 정보들을 브라우저 단에 저장하여 위변조 및 도용이 쉽다는 문제가 있습니다. 보안적인 부분은 클라이언트가 아닌 서버에서 관리하여 외부로 해당 개인정보를 숨겨 보안성을 높여야합니다. 따라서 클라이언트는 키만 가지고 있으며 해당 정보는 서버에서 관리하고 있는 방법을 세션이라고 합니다.

저는 이 포스팅에서 세션을 두가지 방법으로 구현합니다. 첫번째는 쿠키를 이용한 세션속성 기반으로 세션을 구현할 예정입니다.

세션

정의

세션(Session)서버가 클라이언트의 상태를 유지하기 위해 일정 기간 동안 저장하는 정보를 의미합니다. 클라이언트의 요청마다 동일한 사용자임을 식별할 수 있도록 하는 상태 관리 방식입니다. 보통 서버는 클라이언트가 전달한 세션 ID를 기반으로 특정 사용자와 연결된 정보를 조회합니다.

 

역할

  • 사용자 식별: 세션 ID를 통해 동일 클라이언트의 요청임을 서버가 식별합니다.
  • 상태 유지: 로그인 상태, 장바구니 정보 등 사용자의 상태 정보를 서버에서 저장 및 관리합니다.
  • 보안 강화: 민감한 정보는 서버에 저장하고, 클라이언트는 세션 ID만 전달하므로 정보 위변조 위험을 줄입니다.

구조

세션 구조

 

  • 클라이언트 측
    • 브라우저는 서버로부터 세션 ID를 받아 저장(주로 쿠키에 저장)하고, 이후 요청마다 세션 ID를 포함하여 서버에 전달합니다.
  • 서버 측
    • 서버는 세션 저장소(메모리, 데이터베이스 등)에 세션 ID와 상태 정보를 저장하고, 세션 ID를 키로 사용하여 클라이언트 데이터를 관리합니다.

 

장점

  1. 보안성
    • 민감한 데이터가 서버에 저장되므로 클라이언트에서 정보가 노출될 위험이 줄어듭니다.
  2. 유연성
    • 상태 정보는 서버에 저장되므로 클라이언트가 브라우저를 닫더라도 세션이 만료되지 않으면 상태를 유지할 수 있습니다.
  3. 확장성
    • 서버의 세션 저장소를 확장하여 대량의 사용자 상태를 관리할 수 있습니다.

단점

 

  • 서버 부담
    • 세션 데이터를 서버에서 관리하므로 사용자 수가 많아질수록 서버 메모리나 저장소 사용량이 증가합니다.
  • 스케일링 문제
    • 서버가 분산 환경일 경우, 세션 데이터를 공유하기 위한 추가 작업(예: 세션 클러스터링)이 필요합니다.
  • 만료 관리
    • 세션 만료 시간 설정이 필요하며, 만료되지 않은 오래된 세션 데이터가 서버의 리소스를 점유할 수 있습니다.

 

Session-login(쿠키 기반)

Frontend

localhost:3000/login-session에 접근하기 위해 routepath를 지정합니다.

// RoutePath.ts
export enum RoutePath {
    HOMEPAGE = "/",
    COOKIE = "/login-cookie",
    SESSION = "/login-session"
}

// AppRoutes.tsx

const AppRoutes = () => {
    return (
      <Router>
          <Routes>
              <Route path={RoutePath.HOMEPAGE} element={<HomePage />} />
              <Route path={RoutePath.COOKIE} element={<CookieLogin />} />
              <Route path={RoutePath.SESSION} element={<SessionLogin />} />
          </Routes>
      </Router>
    )
  }
  
  export default AppRoutes

로그인과 로그아웃 기능입니다. 이전 쿠키와 동일하지만 credential을 include 속성을 넣어줍니다.

const loginV1 = async () => {
    try {
        const response = await fetch('http://localhost:8080/session/loginV1', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: new URLSearchParams({
                username: username,
                password: password
            }),
            credentials: 'include'
        });

        if (response.ok) {
            const data = await response.text(); // 서버의 응답 메시지
            console.log(data);
            setLoginMessage(data);
            setIsAuthenticated(true);
        } else {
            const errorData = await response.text();
            setLoginMessage('Login failed: ' + errorData);
        }
    } catch (error) {
        setLoginMessage('Login failed: ' + error);
    }
};

// 로그아웃 V1 (세션 만료)
const logoutV1 = async () => {
  try {
      const response = await fetch('http://localhost:8080/session/logoutV1', {
          method: 'POST',
          credentials: 'include'
      });

      if (response.ok) {
          const data = await response.text(); // 서버의 응답 메시지
          console.log(data);
          setLogoutMessage(data);
          setIsAuthenticated(false);
      } else {
          const errorData = await response.text();
          setLogoutMessage('Logout failed: ' + errorData);
      }
  } catch (error) {
      setLogoutMessage('Logout failed: ' + error);
  }
};

Backend

마찬가지로 username과 password를 토대로 member가 존재하면 SessionManager를 통해 쿠키를 생성하여 response에 넣어줍니다.

@Slf4j
@RestController
@RequestMapping("/session")
@RequiredArgsConstructor
@CrossOrigin(origins = "http://localhost:3000", allowedHeaders = "*", allowCredentials = "true")
public class SessionController {

    private final AuthService authService;
    private final SessionManager sessionManager;


    @PostMapping("/loginV1")
    public ResponseEntity<String> loginV1(@RequestParam String username,
                                          @RequestParam String password,
                                          HttpServletResponse response) {
        log.info("session cookie login id: {}, password: {}", username, password);

        // Authorization User
        Member member = authService.login(username, password);

        if (member != null) {
            sessionManager.createSession(member, response);
            return ResponseEntity.ok("Success session-login");
        }

        return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Fail login");
    }

    @PostMapping("/logoutV1")
    public ResponseEntity<String> logoutV1(HttpServletRequest request) {
        log.info("logout session cookie");

        if (sessionManager.expire(request)) {
            return ResponseEntity.ok("Success session-logout");
        }

        return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Fail logout");
    }
}

이 프로젝트에서는 sessionManager를 메모리에서 관리합니다. 쿠키 이름을 spring-react-auth의 쿠키로 sessionId를 UUID 값으로 넣어줍니다. 

@Component
public class SessionManager {

    public static final String SESSION_COOKIE_NAME = "spring-react-auth";
    private final Map<String, Object> sessionStore = new ConcurrentHashMap<>();

    public void createSession(Object value, HttpServletResponse response) {
        // Generate a unique session ID and store the session data.
        String sessionId = UUID.randomUUID().toString();
        sessionStore.put(sessionId, value);

        // Create a session cookie with the generated session ID.
        Cookie sessionCookie = new Cookie(SESSION_COOKIE_NAME, sessionId);
        sessionCookie.setHttpOnly(true); // Enhance security by restricting client-side access
//        sessionCookie.setPath("/");      // Make the cookie accessible across the application
        response.addCookie(sessionCookie);
    }
    
    public boolean expire(HttpServletRequest request) {
        Cookie sessionCookie = findCookie(request, SESSION_COOKIE_NAME);
        System.out.println("sessionCookie = " + sessionCookie.getName());

        if (sessionCookie != null) {
            sessionStore.remove(sessionCookie.getValue());
            return true;
        }
        return false;
    }

    public Cookie findCookie(HttpServletRequest request, String cookieName) {
        if (request.getCookies() == null) {
            return null; // No cookies present in the request
        }
        return Arrays.stream(request.getCookies())
                .filter(cookie -> cookie.getName().equals(cookieName))
                .findFirst()
                .orElse(null);
    }
}

 

Session-login(속성 기반)

Frontend

로그인과 로그아웃 기능입니다. 앞선 기능들과 동일합니다.

// 로그인 V2 (세션 객체로 로그인)
const loginV2 = async () => {
  try {
      const response = await fetch('http://localhost:8080/session/loginV2', {
          method: 'POST',
          headers: {
              'Content-Type': 'application/x-www-form-urlencoded',
          },
          body: new URLSearchParams({
              username: username,
              password: password
          }),
          credentials: 'include'
      });

      if (response.ok) {
          const data = await response.text(); // 서버의 응답 메시지
          setLoginMessage(data);
          setIsAuthenticated(true);
      } else {
          const errorData = await response.text();
          setLoginMessage('Login failed: ' + errorData);
      }
  } catch (error) {
      setLoginMessage('Login failed: ' + error);
  }
};
  
// 로그아웃 V2 (세션 무효화)
const logoutV2 = async () => {
  try {
      const response = await fetch('http://localhost:8080/session/logoutV2', {
          method: 'POST',
          credentials: 'include'
      });

      if (response.ok) {
          const data = await response.text(); // 서버의 응답 메시지
          setLogoutMessage(data);
          setIsAuthenticated(false);
      } else {
          const errorData = await response.text();
          setLogoutMessage('Logout failed: ' + errorData);
      }
  } catch (error) {
      setLogoutMessage('Logout failed: ' + error);
  }
};

Backend

이번에는 속성을 통해서 넣어줍니다. LOGIN_MEMBER의 속성에 member를 넣어주면 JSESSIONID가 할당됩니다.

@Slf4j
@RestController
@RequestMapping("/session")
@RequiredArgsConstructor
@CrossOrigin(origins = "http://localhost:3000", allowedHeaders = "*", allowCredentials = "true")
public class SessionController {

    private final AuthService authService;
    private final SessionManager sessionManager;
    private final String LOGIN_MEMBER = "Spring-React-Session-Login";

    @PostMapping("/loginV2")
    public ResponseEntity<String> loginV2(@RequestParam String username,
                                          @RequestParam String password,
                                          HttpServletRequest request) {
        log.info("session Attribute login id: {}, password: {}", username, password);

        Member member = authService.login(username, password);
        if (member != null) {
            // Login success handling
            // Return the existing session if it exists; otherwise, create a new session
            HttpSession session = request.getSession();
            // Store login member information in the session
            session.setAttribute(LOGIN_MEMBER, member);

            return ResponseEntity.ok("Success session-login using request");
        }

        // Return an error response if login fails (optional: add this block for clarity)
        return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Invalid username or password");
    }

    @PostMapping("/logoutV2")
    public ResponseEntity<String> logoutV2(HttpServletRequest request) {
        log.info("logout session Attribute");

        StringBuilder sb = new StringBuilder();
        sb.append("Success session-logout: ");

        HttpSession session = request.getSession(false);
        if (session != null) {
            Member member = (Member) session.getAttribute(LOGIN_MEMBER);
            System.out.println("session value: " + (member == null ? "not found member" : member.getUsername()));
            session.invalidate();
            sb.append("expire session");
        }

        return ResponseEntity.ok(sb.toString());
    }
}

 

결과

로그인 창(쿠키기반 세션)
쿠키 값이 제대로 할당된 것을 볼 수 있습니다.
속성을 기반으로 한 세션
JESSIONID가 설정된 것을 확인할 수 있습니다.
logout되어 쿠키가 없는 것을 확인할 수 있습니다.

깃허브 및 참조