Secure transmission of sensitive information in session tokens
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class SessionServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
String token = request.getParameter("token");
// do something with the token
}
}
The above code represents a Servlet that handles GET requests. In the
doGet
method, it extracts a parameter named "token" from the request URL. This token is assumed to be a JWT session token.
The vulnerability lies in the line where we extract the token from the URL:
String token = request.getParameter("token");
Referer
header when the user clicks on a link to another site from the page that contains the sensitive information. This could allow an external site to gain access to the token.
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class SessionServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
String token = request.getHeader("Authorization");
// do something with the token
}
}
The above code fixes the vulnerability by changing the method of transmitting the session token from URL parameters to HTTP headers. This is done in the following way:
1. Change the HTTP method from GET to POST: The
doGet
method is changed to
doPost
. This is because sensitive data should not be sent in the URL, as it can be cached in the browsing history. POST requests do not have this issue as they send data in the request body.
2. Retrieve the token from the Authorization header: Instead of getting the token from the URL parameters with
request.getParameter("token")
, the token is now retrieved from the Authorization header with
request.getHeader("Authorization")
. This is a more secure way of transmitting the token as it is not exposed in the URL.
Remember, this is just one part of securing the session token. Other techniques should also be implemented, such as using secure cookies or session tokens with short expiration times, encrypting the session token, and implementing secure coding practices like input validation and output encoding.