Search code examples
javareactjsajaxglassfishbasic-authentication

Avoid basic auth popup when querying rest-backend application from frontend application


I have two applications, two wars, app-rest and app-web. App-rest is the backend holding a rest-api and app-web is the frontend holding a react GUI.

I want to secure the backend using basic auth but when doing this the frontend ajax requests trigger a basic auth popup in the browser.

I am using Glassfish as an application server.

I have tried securing both applications in hopes of them sharing the session cookie but that does not seem to be the case.

Also tried java filters to try and remove WWW-authenticate header when unauthorized since I have read that that header is the one triggering the popup, but filters are not activated during basic auth initialization.

I have tried using form-based login and that kind of works but then I loose the ability to use applications like postman to test my rest-api (at least I think this is the case since I cant authenticate in the request itself)

How can I avoid showing the basic auth popup when doing requests from the frontend to the backend ?


Solution

  • This wonderful human being solved it: How to change response before send

    What he did was to add this to the web.xml

    <error-page>
       <error-code>401</error-code>
       <location>/error.jsp</location>
    </error-page>
    

    And in error.jsp:

    <%@page contentType="text/html" pageEncoding="UTF-8"%>
        <!DOCTYPE html>
        <html>
            <head>
                <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
                <title></title>
            </head>
            <body>
                <%
                int status = response.getStatus();
                if (status == 401) {
                    response.setStatus(403);
                }
                %>
            </body>
        </html>
    

    Then in your javascript you can just look for status code 403 and show a custom login screen without basic auth popup.