After doing some research on JSON Web Token (which is a new concept to me), I have learned about its secure mechanism for transmitting information between parties without the need for server Sessions.
Currently, I am in the process of building a web app from scratch using Java, Tomcat, the Jersey framework for Web Services, and JOSE4J for handling JWTs.
I have come across several articles recommending the use of httpOnly Cookies instead of localStorage when dealing with authentication.
As part of my development process, I have already created a RESTful method that utilizes a cookie along with the jwt for authentication.
@GET
@Path("/authenticate")
@Produces(MediaType.APPLICATION_JSON)
public Response authenticate(
@HeaderParam("username") String username,
@HeaderParam("password") String password) throws JSONException,
IOException, JoseException {
Service service = Service.getInstance();
EmployeeProfile employeeProfile = service.authenticate(username, password);
// For testing purposes, httpOnly and secure are set as false temporarily
NewCookie cookie = new NewCookie("jwt", service.getToken(), null, null, null, 900, false, false);
return Response.status(200).cookie(cookie).entity(employeeProfile).build();
}
return Response.status(204).entity(null).build();
}
Upon running my webapp in Chrome, I observed that the cookie was successfully saved.
However, a concern arises if Cookies are disabled. In such cases, retrieving the cookie proved impossible during testing in incognito mode. To address this issue, I can check if cookies are enabled and notify the user accordingly to proceed with the login process.
To verify the status of cookies, I implemented the following code:
$.cookie('test_cookie', 'cookie_value', { path: '/' });
if ($.cookie('test_cookie') !== 'cookie_value') {
// Show a modal indicating that cookies are disabled
}
Nevertheless, this approach seems restrictive. Therefore, I am contemplating alternative methods for retrieving the jwt from the server. One suggestion is to adjust the controller to include the jwt in the response as JSON and store it in the localStorage, despite the vulnerability to XSS attacks. On the other hand, using cookies may pose risks of CRSF attacks unless proper security measures like setting httpOnly and secure properties to true are applied. However, this would prevent reading the cookie with JavaScript. This dilemma has left me confused.
Your insights on this matter would be greatly appreciated.