Notice
Recent Posts
Recent Comments
Link
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
Archives
Today
Total
관리 메뉴

의미없는 블로그

[Spring] HttpOnly / Secure Cookie 본문

# 나/source Code

[Spring] HttpOnly / Secure Cookie

SaltLee 2024. 3. 15. 13:55
HttpOnly  브라우저에 쿠키값 안뜨게 하는거 
 
Secure Cookie HTTPS 에서만 쿠키 전송되게 하는거

 

스프링에서 설정할 수도 있고

톰캣에서 설정할 수도 있는데

어디서 설정할지는..

 

application.properties 에서 설정

# 쿠키 보안 설정
server.servlet.session.cookie.http-only=true
server.servlet.session.cookie.secure=true

application.yml 에서 설정

server:
  servlet:
    session:
      cookie:
        http-only: true
server:
  servlet:
    session:
      cookie:
        secure: true

자바 코드로 설정 (new Cookie 로 생성할때 설정)

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CookieUtil {

    public static void addCookie(HttpServletResponse response, String name, String value, int maxAge, boolean httpOnly, boolean secure) {
        Cookie cookie = new Cookie(name, value);
        cookie.setMaxAge(maxAge);
        cookie.setHttpOnly(httpOnly);
        cookie.setSecure(secure);
        response.addCookie(cookie);
    }

    public static Cookie getCookie(HttpServletRequest request, String name) {
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals(name)) {
                    return cookie;
                }
            }
        }
        return null;
    }
}
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class YourServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response) {
        // HTTPOnly 및 Secure 쿠키를 추가합니다.
        CookieUtil.addCookie(response, "sessionId", "123456789", 3600, true, true);
    }
}

 

톰캣 server.xml 에 설정

<Context useHttpOnly="true">
    <!-- 다른 설정들 -->
    <CookieProcessor className="org.apache.tomcat.util.http.Rfc6265CookieProcessor"
                    httpOnly="true" />
</Context>
<Context useHttpOnly="true">
    <!-- 다른 설정들 -->
    <CookieProcessor className="org.apache.tomcat.util.http.Rfc6265CookieProcessor"
                    secure="true" />
</Context>

 

'# 나 > source Code' 카테고리의 다른 글

팝빌(popbill) API  (0) 2024.03.22
[Spring] @Aspect 도 봐야됨  (0) 2024.03.19
[Spring] HSTS 설정  (0) 2024.03.15
[Spring] Json XSS 필터 (escapeHTML4)  (0) 2024.03.11
[Spring] 스프링 설정파일 (개발/운영 Profile 분리)  (0) 2024.03.07
Comments