0

In the project I'm working on, we have a LoginFilter, that's meant to redirect users that are not logged in.

I've had some issues redirecting ajax requests, but made it work by using this approach: Authorization redirect on session expiration does not work on submitting a JSF form, page stays the same

Now I'm trying to add parameters to the redirect URL's query string, so the login logic can redirect the user to the correct view, and so the view knows if it should display a message. Here's a simplified version of my doFilter method:

String loginPath = contextPath + "/login.xhtml";
String AJAX_REDIRECT_XML =
        "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<partial-response><redirect url=\"%s\"></redirect></partial-response>";

if(userLoggedIn) {
    ...
} else if ("partial/ajax".equalsIgnoreCase(httpServletRequest.getHeader("Faces-Request")) {
    String queryString = "?destination="
    queryString += URLEncoder.encode(contextPath + "/home.xhtml", "UTF-8");
    queryString += "&display-message=true";

    httpServletResponse.setContentType("text/xml")
    httpServletResponse.setCharacterEncoding("UTF-8");
    httpServletResponse.getWriter().printf(AJAX_REDIRECT_XML, loginPath + queryString);
    return;
} else {
    ...
}

This works if I add only a single parameter to the query string, but doesn't if both are present. I get the correct XML response, but it seems that the client-side javascript doesn't know how to handle it? Here's an example of the XML returned from the ajax request.

<?xml version="1.0" encoding="UTF-8"?><partial-response><redirect url="/contextPath/login.xhtml?destination=%2FcontextPath%2Fhome.xhtml&display-message=true"></redirect></partial-response>

In the browser console I get this error:

 XML Parsing Error: not well-formed

What is the reason for this happening?

Kukeltje
  • 12,223
  • 4
  • 24
  • 47
kozeljko
  • 160
  • 2
  • 13

1 Answers1

0

So, I found the solution.

The issue was the ampersand in the query string. I didn't realize you have to escape those in XML.

Replaced:

queryString += "&display-message=true";

with:

queryString += "&amp;display-message=true";
kozeljko
  • 160
  • 2
  • 13
  • 1
    https://stackoverflow.com/questions/1328538/how-do-i-escape-ampersands-in-xml-so-they-are-rendered-as-entities-in-html – Kukeltje Jun 06 '18 at 14:11