1

I have a bootstrap form its submitted by clicking createTicketButton button it executes 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) 
                {}
            });
});

finally, it passed to Filter to make sure CSFR token passed and match what exists in the server

if tokens mismatch it should redirect to the login page here is the problem redirect cause 500 error (Internal Server Error) and not redirecting and popover still showing any help?

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());
        }
    }
}

my HTML

    <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">&times;</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>

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)
Mina Fawzy
  • 20,852
  • 17
  • 133
  • 156
  • Can you redirect a POST? – Scary Wombat Aug 30 '19 at 02:49
  • @ScaryWombat Sure you can, most of the login forms out there use POST and the server responds with a `302` redirect header. – Accountant م Aug 30 '19 at 05:22
  • *"here is the problem redirect cause error"* ... What error do you get ? – Accountant م Aug 30 '19 at 05:22
  • @Accountantم Thanks, I thought you could but best to ask. – Scary Wombat Aug 30 '19 at 07:18
  • @ScaryWombat You are welcome, but offcurse the browser will use **GET** to request the URL in the redirect header. Redirecting POST to POST can't be done without a [workaround](https://stackoverflow.com/questions/5576619/php-redirect-with-post-data). – Accountant م Aug 30 '19 at 07:39
  • I updated my question , I think the problem is not GET or POST request as redirect code working in different case , popOver be closed and redirect to login page but with popOver opened it throw error 5000 , any hint why this happen – Mina Fawzy Aug 30 '19 at 11:01
  • 500 Internal Server Errors should be logged in the webserver log files with the details you need, I don't know about servlet but it must be logging this error somewhere. – Accountant م Aug 30 '19 at 13:27
  • I updated my question by adding error stack please check it – Mina Fawzy Sep 02 '19 at 19:41

2 Answers2

0

It looks like an exception which occurs in your servlet. Try to jump in with your debugger and post the exception message here.

alexcodes
  • 404
  • 3
  • 11
0

Finally I figure why this happen , if you send request from Ajax , you cant redirect using response.sendRedirect("location") as the client-side who should handle this redirect

so its better to send an error message and handle this redirect in client-side

to be like this

//this mean its Ajax call 
if ("XMLHttpRequest".equals(req.getHeader("X-Requested-With"))) {
                res.sendError(Status.BAD_REQUEST.getStatusCode(),
                        String.format("Invalid %s", CSRF_TOKEN_PARAM));
            } 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());
            }

and in client-side

$('#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) 
                {}, error: function (xhr, ajaxOptions, thrownError) {
                if(xhr.responseText.search("Invalid csrf_token")){
                    window.location.replace("location"); --> here where we redirect the call
                }

            }
            });
});
Mina Fawzy
  • 20,852
  • 17
  • 133
  • 156