I've implemented a Bootstrap form that is submitted by clicking the createTicketButton
button, which triggers a jQuery call.
$('#createTicketButton').click(function(event)
{
$.ajax({
processData : false,
contentType : 'application/json',
url : 'myUrl',
"accept" : 'json',
"dataType" : 'json',
"type" : "POST",
data : JSON.stringify(data),
success : function(response)
{}
});
});
The submission then goes through a Filter to verify the CSRF token matches what is stored on the server.
If there's a token mismatch, it should redirect to the login page. However, the issue arises when attempting to redirect as it causes a 500 error (Internal Server Error), and the redirection doesn't happen while the popover remains visible. Any suggestions?
public class CsrfFilter implements Filter
{
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException
{
boolean validToken = realToken.equals(requestToken);
if (validToken)
{
chain.doFilter(request, response);
return;
}
else
{
UriBuilder redirectUri = UriBuilder.fromUri("/login");
try
{
String returnUrl = new URI(req.getHeader("referer")).getPath();
redirectUri.queryParam("r", returnUrl);
}
catch (URISyntaxException | NullPointerException e)
{
// We don't need a return URL
}
res.sendRedirect(redirectUri.build().toString());
}
}
}
Here's my HTML code:
<th:block th:fragment="createTicketFormModal">
<div id="createNewTicket" class="modal fade" role="dialog" aria-labelledby="myModalLabel" data-backdrop="static" aria-hidden="true" data-modal-index="1">
<div class="modal-dialog">
<div class="modal-content">
<div class="create-header modal-header">
<button class="close" type="button" data-dismiss="modal" aria-hidden="true">×</button>
<h4 id="edit-admin-modal" class="modal-title create-title">Create Ticket</h4>
</div>
<div class="modal-body">
<form id="create-ticket-form" class="create-form" method="POST" action="/cats/tickets/new">
<div class="alert alert-danger form-errors collapse"></div>
<!-- The form buttons -->
<input id="createTicketButton" class="btn btn-primary btn-block catsSubmit" type="button" value="Create Ticket" />
<button id="createTicketFormClearButton" class="btn btn-info btn-block" type="button">Clear</button>
<button class="btn btn-default btn-block" type="button" data-dismiss="modal">Close</button>
<input id="file-id" type="hidden" />
</form>
</div>
</div>
</div>
</div>
</th:block>
Below is the error stack:
java.lang.IllegalStateException: UT010019: Response already commited
io.undertow.servlet.spec.HttpServletResponseImpl.sendRedirect(HttpServletResponseImpl.java:173)
com.ephibian.j2ee.security.CsrfFilter.RedirectToLogin(CsrfFilter.java:194)