Setting Cookie Secure Flag – Java

Method #1

Create secure cookie by calling setSecure method, which allows cookie to be secure

Cookie newCookie = new Cookie("name","value");

Method #2

Add the following lines to web.xml file of the project to make the cookie secure.



Setting the HttpOnly Flag – Java

For older versions of servlet

Add the following on cookie creation

String sessionid = request.getSession().getId();
response.setHeader("SET-COOKIE", "JSESSIONID=" + sessionid + "; HttpOnly");

For servlet version 3.0 or later

Add the following lines into web.xml file



Clickjacking – Java Secure Coding

Method #1 Adding the X-Frame-Options in HTTP header

 // to prevent all framing of this content
 response.addHeader( "X-FRAME-OPTIONS", "DENY" );
 // to allow framing of this content only by this site
 response.addHeader( "X-FRAME-OPTIONS", "SAMEORIGIN" );

Method #2 Including frame busting code

<style> html{display : none ; } </style>
   if( self == top ) { = 'block' ; 
   } else {
       top.location = self.location ; 


Prevention of Web Page Caching – JAVA


Add the following codes into the page, in order to prevent the page being cached:

response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
response.setHeader("Pragma", "no-cache");
response.setDateHeader("Expires", 0);


Setting Session Timeout – Java


In servlet call getMaxInactiveInterval method with session object.

HttpSession session = request.getSession();

(In this example, session time out is set for 900 seconds.)


Set timeout through web.xml


(Here 10 minute is the time out .)


SQLi – JAVA Secure Coding

Use PreparedStatement instead of dynamic queries.

All data access techniques provide some means for escaping SQL meta-characters automatically.
Variables passed as arguments to prepared statements will automatically be escaped by the JDBC driver.

String selectStatement = "SELECT * FROM User WHERE userId = ? ";
PreparedStatement prepStmt = con.prepareStatement(selectStatement);
prepStmt.setString(1, userId);
ResultSet rs = prepStmt.executeQuery();


Anti CSRF Token – JAVA


  1. Download OWASP ESAPI Library from the ESAPI project page and add it to the library of the project.
  2. Generate a new CSRF token and add it to user login and store user in HTTP session.
  public String resetCSRFToken() {
    csrfToken = ESAPI.randomizer().getRandomString(8,DefaultEncoder.CHAR_ALPHANUMERICS);
    return csrfToken;

3. Add the token as a parameter / hidden field, on any forms or URLs that should be protected.

   final static String CSRF_TOKEN_NAME = "cftoken";
   public String addCSRFToken(String href) {
	User user = ESAPI.authenticator().getCurrentUser();
	String token = CSRF_TOKEN_NAME + "=" + user.getCSRFToken();
	return href.indexOf( '?') != -1 ? href + "&" + token : href + "?" + token;

   public String getCSRFToken() {
	User user = ESAPI.authenticator().getCurrentUser();
	if (user == null) return null;
	return user.getCSRFToken();

4. On the server-side, check that the submitted token matches the token from the user object in the session.

   public void verifyCSRFToken(HttpServletRequest request) throws IntrusionException {
	User user = ESAPI.authenticator().getCurrentUser();
	if( request.getAttribute(user.getCSRFToken()) != null ) {
	String token = request.getParameter(CSRF_TOKEN_NAME);
	if ( !user.getCSRFToken().equals( token ) ) {
		throw new IntrusionException("Authentication failed", "Possibly forged HTTP request without proper CSRF token detected");




XSS – Java Secure Coding

Using Security Encoding Library

  1. Download ESAPI.jar from the ESAPI Project page, and add it to library of the project.
  2. Import the package in jsp page: <%@ page language=”java” import=”org.owasp.esapi.*” %>
  3. Add code according to the different cases:

Case #1

HTML escape before inserting untrusted data into HTML element content.

String safe = ESAPI.encoder().encodeForHTML( request.getParameter( "input" ) );
<div><%= safe %></div>

Case #2

Attribute escape before inserting untrusted data into HTML common attributes.

String safe = ESAPI.encoder().encodeForHTMLAttribute( request.getParameter( "input" ) );
<div attr='<%= safe %>'></div>

Case #3

JavaScript escape before inserting untrusted data into JavaScript data values.

String safe = ESAPI.encoder().encodeForJavaScript( request.getParameter( "input" ) );
<script>alert('<%= safe %>')</script>
<input type=’button’ onclick=”alert('<%= safe %>')”>

Case #4
URL escape before inserting untrusted data into HTML URL parameter values.

String safe = ESAPI.encoder().encodeForURL( request.getParameter( "input" ) );
<a href='<%= safe %>'>link</a >