새소식

반응형
Java/Spring Boot

[Spring Security] 로그인 시 아이디 저장하기 기능 구현(Cookie)

  • -
728x90
반응형

웹브라우저 쿠키(Cookie)란?

웹브라우저 쿠키란 인터넷 사용자가 웹사이트를 접속했을 때 사용자의 개인장치에 방문 기록 등

브라우저의 정보들이 저장된 텍스트 파일이다.

쿠키의 데이터 형태는 Key, Value 형태로 String 형이며, 4KB 이상 저장이 불가능하다.

 

이러한 웹브라우저 쿠키를 이용해 인터넷 사용자의 아이디를 쿠키에 저장해놓고

저장된 아이디를 불러와 재사용할 수 있다.

 

특정 웹사이트에서 로그인할 때 자주 볼 수 있는 아이디 저장하기 기능을 구현해보자.

 

환경구성 : Spring Boot, Spring Security(로그인 기능), Thymeleaf(템플릿 엔진)

 

1. CookieUtils 클래스 생성

아래 내용과 같이 CookieUtils 라는 클래스를 생성한다.

public class CookieUtils {

    private HashMap<String, Cookie> cookieMap;

    public CookieUtils(HttpServletRequest request) {
        cookieMap = new HashMap<String, Cookie>();
        Cookie[] cookies = request.getCookies();

        if(cookies != null && cookies.length > 0) {
            for(int i = 0 ; i < cookies.length ; i++) {
                cookieMap.put(cookies[i].getName(), cookies[i]);
            }
        }
  }

    /**
    * cookieMap 에 파라미터로 넘어온 name 의 키값으로 Value 값을 리턴한다. 
    * 지정된 키값의 쿠기가 없을 경우 null을 리턴한다.
    * @param name
    * @return
    */
    public String getValue(String name) {
       Cookie cookie = cookieMap.get(name);
        return cookie == null ? null : cookie.getValue();
    }


    public boolean exist(String name) {
        return cookieMap.get(name) != null ? true : false;
    }
}

 

 

 

public CookieUtils(HttpServletRequest request) { ... }

위 내용은 CookieUtils 객체를 생성하게 되면 생성자함수에 의해 현재 인터넷 사용자의

PC에 저장된 모든 Cookie 값을 cookieMap인 HashMap에 담게 된다.

 

public boolean exist(String name) { ... }

특정 name 의 쿠키가 존재하는지 확인하여 boolean 값을 리턴하는 메서드

 

 

2. View 설정(html 파일)

본인은 left bar 에 로그인 화면이 존재한다. 로그인 화면에 아이디 저장하기를 아래와 같이 check box로

구성했다.

아이디 저장하기 Check Box
서버로 넘기기 위한 아이디 저장하기 Check Box 체크 여부

 

첫번째 이미지는 화면에 보여지는 아이디 저장하기 Check Box 이다.

두번째 이미지는 실제로 아이디 저장하기 여부를 넘기기 위한 input hidden 값이다.

세번째는 Check Box 여부를 save_id input 태그에 저장하여 서버로 보내기 위한

javascript 코드이다.

 

3. 로그인 Cookie 설정

Spring Security 를 사용하여 로그인 기능을 구현했으며, 로그인 성공 핸들러인

AuthenticationSuccessHandler 를 커스텀하여 SuccessHandler를 만들었다.

 

public class AuthenticationCustomSeccessHandler extends SavedRequestAwareAuthenticationSuccessHandler  {

    public AuthenticationCustomSeccessHandler(String defaultTargetUrl) {
        this.setDefaultTargetUrl(defaultTargetUrl);
    }


    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
        Authentication authentication) throws IOException, ServletException {

            System.out.println("save id : "+request.getParameter("save_id"));
            System.out.println("login name : "+authentication.getName());

            if("true".equals(request.getParameter("save_id"))) {
                Cookie cookie = new Cookie(SecurityCommon.COOKIE_SAVE_ID, authentication.getName());
                cookie.setMaxAge(60);
                cookie.setPath("/");
                response.addCookie(cookie);
            }
            super.onAuthenticationSuccess(request, response, authentication);
        }
}

 

 public AuthenticationCustomSeccessHandler(String defaultTargetUrl) { ... }

defaultTargetUrl 은 로그인 성공 시 이동할 URL이다. 기본으로 "/" 로 설정되어 있으나

생성자 함수로 등록할 수 있도록 만들었다.

 

Spring Security 에서 로그인을 인증하는 필터인 AbstractAuthenticationProcessingFilter 를 보면

기본 SuccessHandler 를 SavedRequestAwareAuthenticationSuccessHandler 클래스를 사용한다.

 

SavedRequestAwareAuthenticationSuccessHandler 클래스를 살펴보면 부모 클래스가 있으며

해당 클래스에서는 defaultTargetUrl 을 사용하지는 않고 부모클래스에서 설정한다.

 

 

 

아래는 AuthenticationSuccessHandler의 implements 화면이다.

SavedRequestAwareAuthenticationSuccessHandler 클래스의 부모 클래스는

SimpleUrlAuthenticationSuccessHandler 이다.

 

 

부모 클래스인 SimpleUrlAuthenticationSuccessHandler 클래스는 setDefaultTargetUrl을

통해 로그인 성공 시 리다이렉션 URL을 설정한다.

설정하는 메서드가 존재하는 곳은 AbstractAuthenticationTargetUrlRequestHandler이다.

SimpleUrlAuthenticationSuccessHandler 의 부모 클래스중 하나이다.

 

기본 경로는 "/" 이며, 본인은 SavedRequestAwareAuthenticationSuccessHandler 클래스를

상속받아 직접 AbstractAuthenticationTargetUrlRequestHandler 클래스에 url 설정을 했다.

 

 

if("true".equals(request.getParameter("save_id"))) {
    Cookie cookie = new Cookie(SecurityCommon.COOKIE_SAVE_ID, authentication.getName());

    cookie.setMaxAge(60);
    cookie.setPath("/");
    response.addCookie(cookie);
}

아이디 저장하기 데이터인 save_id 값이 true 일 경우 쿠키값을 설정하며,

CookieUtils 클래스의 생성자함수를 이용해 생성한다.

 

setMaxAge() - 쿠키 최대 수명 설정(초 단위)

setPath() - 쿠키를 반환할 쿠키 경로 지정

 

이렇게 설정하게 되면 로그인 시 아이디 저정하기 Check Box를 클릭하게 되면 사용자 로컬에 쿠키값이 저장된다.

 

** 보안 관련 설정

- setSecure(true, false)

true 일 경우 HTTPS 일 때만 쿠키값을 서버에 전달한다. 즉, HTTPS 일 경우에만 ID가 자동 저장된다.

 

- setHttpOnly(true, false)

서버 요청이 있을 경우에만 쿠키가 전송되도록 설정하며, 임의로 다른 사용자에 의해 웹 브라우저에서

출력되지 않도록 설정한다.

웹 브라우저에서 특정 사용자에 의해 쿠키가 보여지지 않도록 설정하는 방법이다.

 

4. 로그인 화면 아이디 불러오기

로그인 화면을 불러오는 Controller 에서 아래와 같이 설정한다.

 

CookieUtils cookie = new CookieUtils(request);

if(cookie.exist(SecurityCommon.COOKIE_SAVE_ID)) {
    map.put("saveId", cookie.getValue(SecurityCommon.COOKIE_SAVE_ID));
}

CookieUtils 의 쿠키값 확인 메서드인 exist 메서드를 통해 SAVE ID 쿠키값이 존재하는 확인한다.

확인 후 있을 경우 View로 saveId 데이터를 넘긴다.

 

 

넘어온 saveId가 존재할 경우 로그인 id form 에다가 데이터를 넣어준다.

 

 

728x90
반응형
Contents

포스팅 주소를 복사했습니다

이 글이 도움이 되었다면 공감 부탁드립니다.