>  기사  >  Java  >  Java에서 HttpOnly 쿠키를 설정하는 방법은 무엇입니까?

Java에서 HttpOnly 쿠키를 설정하는 방법은 무엇입니까?

PHPz
PHPz앞으로
2023-04-22 18:37:081696검색

Httponly 쿠키는 쿠키 보안 솔루션입니다.

httponly 쿠키(IE6+, FF3.0+)를 지원하는 브라우저에서 쿠키에 "httponly" 속성이 설정되어 있으면 JavaScript 스크립트가 쿠키 정보를 읽을 수 없으므로 XSS 공격을 효과적으로 방지하고 웹사이트 애플리케이션이 더 안전해졌습니다.

그러나 J2EE4 및 J2EE5 쿠키는 httponly 속성을 설정하는 방법을 제공하지 않으므로 httponly 속성을 설정해야 하는 경우 직접 처리해야 합니다.

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
 
/**
 * Cookie Tools
 */
public class CookieUtil {
 
    /**
           * Set httponly cookie
     * @param  Response HTTP response
     * @param  Cookie cookie object
     * @param  Ishttponly is httponly
     */
    public static void addCookie(HttpServletResponse response, Cookie cookie, boolean isHttpOnly) {
        String name = cookie.getName();//Cookie name
        String value = cookie.getValue();//Cookie value
        int maxAge = cookie.getMaxAge();//Maximum survival time (milliseconds, 0 representative deletion, -1 represents the same as the browser session)
        String path = cookie.getPath();//path
        String domain = cookie.getDomain();//area
        boolean isSecure = cookie.getSecure();//Is there a security protocol? 
 
        StringBuilder buffer = new StringBuilder();
 
        buffer.append(name).append("=").append(value).append(";");
 
        if (maxAge == 0) {
            buffer.append("Expires=Thu Jan 01 08:00:00 CST 1970;");
        } else if (maxAge > 0) {
            buffer.append("Max-Age=").append(maxAge).append(";");
        }
 
        if (domain != null) {
            buffer.append("domain=").append(domain).append(";");
        }
 
        if (path != null) {
            buffer.append("path=").append(path).append(";");
        }
 
        if (isSecure) {
            buffer.append("secure;");
        }
 
        if (isHttpOnly) {
            buffer.append("HTTPOnly;");
        }
 
        response.addHeader("Set-Cookie", buffer.toString());
    }
 
}

Java Ee 6.0의 쿠키는 httponly를 설정했기 때문에 Java EE 6.0 호환 컨테이너(예: Tomcat 7)와 호환되는 경우 cookie.sethttponly를 사용하여 HTTPONLY를 설정할 수 있습니다.

cookie.setHttpOnly(true);

Java HttpCookie 클래스 setHttpOnly(Boolean httpOnly) 메소드는 쿠키가 HTTPOnly로 간주될 수 있는지 여부를 나타내는 데 사용됩니다. true로 설정하면 JavaScript와 같은 스크립팅 엔진에서 쿠키에 액세스할 수 없습니다.

Syntax

public void setHttpOnly(boolean httpOnly)

Scope

위 메소드에는 단 하나의 매개변수만 필요합니다:

httpOnly - 쿠키가 HTTP 전용이면 true입니다. 즉, 쿠키가 HTTP 요청의 일부로 표시된다는 뜻입니다.

반환

해당 없음

예제 1

import java.net.HttpCookie;  
public class JavaHttpCookieSetHttpOnlyExample1 {  
  public static void main(String[] args) {  
    HttpCookie  cookie = new HttpCookie("Student", "1");  
    // Indicate whether the cookie can be considered as HTTP Only or not.  
        cookie.setHttpOnly(true);  
    // Return true if the cookie is considered as HTTPOnly.  
System.out.println("Check whether the cookie is HTTPOnly: "+cookie.isHttpOnly());  
     }  
 }

출력:

쿠키가 HTTPOnly인지 확인: true

예제 2

import java.net.HttpCookie;  
public class JavaHttpCookieSetHttpOnlyExample2 {  
    public static void main(String[] args) {  
        HttpCookie  cookie = new HttpCookie("Student", "1");  
        // Indicate whether the cookie can be considered as HTTP Only or not.  
            cookie.setHttpOnly(false);  
        // Return false if the cookie is not considered as HTTPOnly.  
    System.out.println("Check whether the cookie is HTTPOnly: "+cookie.isHttpOnly());  
   }  
}

출력:

쿠키가 HTTPOn인지 확인 ly: 거짓

예 3

import java.net.HttpCookie;  
public class JavaHttpCookieSetHttpOnlyExample3 {  
    public static void main(String[] args) {  
        HttpCookie cookie1 = new HttpCookie("Student1", "1");  
        HttpCookie cookie2 = new HttpCookie("Student2", "2");  
        //Indicate whether the cookie can be considered as HTTP Only or not.  
        cookie1.setHttpOnly(true);  
        cookie2.setHttpOnly(false);  
        System.out.println("Check whether the first cookie is HTTPOnly:"+cookie1.isHttpOnly());  
        System.out.println("Check whether the second cookie is HTTPOnly:"+cookie2.isHttpOnly());  
       }  
    }

출력:

첫 번째 쿠키가 HTTPOnly:true인지 확인하세요.
두 번째 쿠키가 HTTPOnly:false

인지 확인하세요.

위 내용은 Java에서 HttpOnly 쿠키를 설정하는 방법은 무엇입니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
이 기사는 yisu.com에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제