[Spring] 쿠키 활용하기 - 자동 로그인

2024. 10. 25. 00:37·Spring

쿠키란?

쿠키(Cookie)는 클라이언트(브라우저)에 저장되는 작은 데이터다.

서버는 HTTP 응답에 쿠키를 포함하여 클라이언트에 전달하고, 클라이언트는 이후 요청 시 해당 쿠키를 다시 서버로 보낸다. 이를 통해 서버는 클라이언트의 상태나 정보를 추적할 수 있다. 

 

쿠키는 로그인 유지, 사용자 정보 저장 등의 기능에 주로 사용된다.

 그중 로그인 유지하는 코드에 대해 중점적으로 다뤄볼 예정이다.


쿠키의 주요 메서드와 속성

 

getName(): 쿠키의 이름을 가져옴

getValue(): 쿠키에 저장된 값을 가져옴

setMaxAge(int seconds): 쿠키의 유효 기간을 설정

getMaxAge(): 쿠키의 만료 시간을 확인

setValue(String value): 쿠키의 값을 설정


Spring AOP 와 쿠키를 활용한 코드 예시 (자동 로그인)

Spring AOP를 사용하면 로그인 체크와 같은 공통된 기능을 코드 여러 곳에서 중복하지 않고 한 곳에서 처리할 수 있다.

여기서는 @Around 어노테이션을 이용해 로그인 여부를 체크하고, 로그인되지 않은 경우에는 로그인 페이지로 redirect하는 기능을 구현한다.

LoginAspect 클래스

LoginAspect 클래스는 로그인 체크를 수행하는 AOP 클래스이다.

@Around 어노테이션을 사용하여 @LoginCheck가 붙은 메서드에 대해 로그인 상태를 확인하고, 쿠키와 세션 정보를 활용한다.

@Aspect
@Component
public class LoginAspect {
    @Around("@annotation(com.coma.app.view.function.LoginCheck)") // @LoginCheck 어노테이션이 붙은 메서드에 로그인 체크 적용
    public Object checkLogin(ProceedingJoinPoint joinPoint) throws Throwable {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest(); // 현재 요청 객체 가져오기
        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getResponse(); // 현재 응답 객체 가져오기
        HttpSession session = request.getSession(); // 세션 정보 가져오기

        // 로그인 정보 확인
        String[] loginInfo = checkLoginInformation(request, response, session);

        if (loginInfo[0] == null) {
            return "redirect:login.do"; // 로그인되지 않았을 경우 로그인 페이지로 리다이렉트
        }

        return joinPoint.proceed(); // 로그인된 경우 메서드 실행
    }
}

 

 

쿠키와 세션을 활용해서 로그인 정보 체크하기 

checkLoginInformation() 메서드는 쿠키와 세션에서 로그인 정보를 가져와 사용자의 로그인 상태를 확인한다.

쿠키가 있으면 자동 로그인을 위해 쿠키 유효 기간을 연장하고, 세션에 저장된 정보와 비교하여 로그인 상태를 유지한다.

아래는 checkLoginInformation() 메서드이다.

private String[] checkLoginInformation(HttpServletRequest request, HttpServletResponse response, HttpSession session) {
    String[] loginInformation = new String[2]; // [MEMBER_ID, CREW_CHECK] 정보를 저장할 배열

    // 쿠키에서 로그인 정보 가져오기
    Cookie[] cookies = request.getCookies();
    if (cookies != null) {
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals("MEMBER_ID")) {
                cookie.setMaxAge(60 * 60 * 24 * 7); // 7일 동안 쿠키 유지
                response.addCookie(cookie);
                loginInformation[0] = cookie.getValue(); // 쿠키에서 MEMBER_ID 값 가져오기
            } else if (cookie.getName().equals("CREW_CHECK")) {
                cookie.setMaxAge(60 * 60 * 24 * 7);
                response.addCookie(cookie);
                loginInformation[1] = cookie.getValue(); // 쿠키에서 CREW_CHECK 값 가져오기
            }
        }
    }

    // 세션에서 로그인 정보 가져오기
    String sessionMemberID = (String) session.getAttribute("MEMBER_ID");
    String sessionMemberCrew = (String) session.getAttribute("CREW_CHECK");

    if (sessionMemberID == null && loginInformation[0] != null) {
        session.setAttribute("MEMBER_ID", loginInformation[0]); // 세션에 MEMBER_ID 저장
        if (sessionMemberCrew == null || sessionMemberCrew.equals("0")) {
            session.setAttribute("CREW_CHECK", loginInformation[1]); // 세션에 CREW_CHECK 저장
        }
    } else if (sessionMemberID != null && loginInformation[0] == null) {
        loginInformation[0] = sessionMemberID; // 세션에서 MEMBER_ID 가져오기
        if (sessionMemberCrew.equals("0")) {
            loginInformation[1] = "0";
        }
    }

    return loginInformation;
}

자동 로그인 기능

자동 로그인은 사용자가 로그인할 때 '자동 로그인'을 선택한 경우, 해당 정보를 쿠키에 저장하여 이후 로그인 과정에서 쿠키를 통해 자동으로 로그인 상태를 유지하는 방식이다.

 

setCookies() 메서드를 사용하여 쿠키를 설정하고, 로그인 유지 기간을 7일로 설정했다.

private void setCookies(MemberDTO memberDTO, HttpServletResponse response, HttpServletRequest request) {
    String auto = request.getParameter("VIEW_AUTO_LOGIN"); // 자동 로그인 체크 여부 가져오기

    if (auto != null) { // 자동 로그인 체크되어 있다면
        Cookie member_id_cookie = new Cookie("MEMBER_ID", memberDTO.getMember_id()); // MEMBER_ID 쿠키 생성
        Cookie member_crew_cookie = new Cookie("CREW_CHECK", String.valueOf(memberDTO.getMember_crew_num())); // CREW_CHECK 쿠키 생성

        member_id_cookie.setMaxAge(60 * 60 * 24 * 7); // 7일 동안 쿠키 유지
        member_crew_cookie.setMaxAge(60 * 60 * 24 * 7);

        response.addCookie(member_id_cookie); // 쿠키 응답에 추가
        response.addCookie(member_crew_cookie);
    }
}

로그아웃 처리

로그아웃 시에는 쿠키의 유효 기간을 0으로 설정하여 쿠키를 삭제하고, 세션에서 로그인 정보를 제거한다.

public static void logout(HttpServletRequest request, HttpServletResponse response) {
    Cookie[] cookies = request.getCookies();
    if (cookies != null) {
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals("MEMBER_ID") || cookie.getName().equals("CREW_CHECK")) {
                cookie.setMaxAge(0); // 쿠키 삭제
                response.addCookie(cookie); 
            }
        }
    }
    request.getSession().removeAttribute("MEMBER_ID"); // 세션에서 MEMBER_ID 삭제
    request.getSession().removeAttribute("CREW_CHECK"); // 세션에서 CREW_CHECK 삭제
}

 

'Spring' 카테고리의 다른 글

[Spring] 롬복(Lombok) 라이브러리  (0) 2024.10.30
[Spring] 횡단 로직 - AOP를 활용한 로그인 체크 기능 구현하기  (0) 2024.10.28
[Spring] Multipart & 파일 업로드  (1) 2024.10.23
[Spring] 커스텀 어노테이션  (1) 2024.10.23
[Spring] AOP와 어노테이션  (0) 2024.10.16
'Spring' 카테고리의 다른 글
  • [Spring] 롬복(Lombok) 라이브러리
  • [Spring] 횡단 로직 - AOP를 활용한 로그인 체크 기능 구현하기
  • [Spring] Multipart & 파일 업로드
  • [Spring] 커스텀 어노테이션
yn98
yn98
좌우명 : 여전할 것 인가, 역전할 것 인가? 백엔드 개발자가 되고싶은 역전하고 있는 개발자 꿈나무의 블로그입니다. 개발을 하면서 공부한 것들을 기록합니다. 24.06 ~
  • yn98
    개발 꿈나무
    yn98
  • 전체
    오늘
    어제
    • 분류 전체보기 (131)
      • Python (3)
      • 공부 (7)
      • DB (7)
      • JAVA (24)
      • JSP (9)
      • jQuery (2)
      • HTML (3)
      • Spring (20)
      • 웹 (4)
      • C (1)
      • Git (2)
      • 에러일기 (19)
      • 프로젝트 (6)
      • 책 (21)
        • 멘토씨리즈 자바 (14)
        • 2024 수제비 정보처리기사 (7)
      • 기타 (2)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

    • GitHub
    • Notion
  • 공지사항

  • 인기 글

  • 태그

    이벤트 스케줄러
    DispatcherServlet
    recoverabledataaccessexception
    2-layered 아키텍처
    정처기 실기
    오블완
    @repository
    정보처리기사 실기
    Spring
    수제비
    jsp
    멘토씨리즈 자바
    ViewResolver
    정처기
    스프링 프레임워크
    MVC
    Di
    @Component
    티스토리챌린지
    정보처리기사
    상속
    객체지향
    오버로딩
    java
    html
    aop
    @service
    어노테이션
    생성자
    codeup 4891 : 행복
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.0
yn98
[Spring] 쿠키 활용하기 - 자동 로그인
상단으로

티스토리툴바