Logout from web app using tomcat Basic authentication

前端 未结 3 781
夕颜
夕颜 2021-02-06 02:32

I am using tomcat basic authentication for my web app:

I added following lines to web.xml in my web app:


    

        
3条回答
  •  暗喜
    暗喜 (楼主)
    2021-02-06 03:01

    You're using HTTP BASIC authentication instead of HTTP FORM authentication with j_security_check. The BASIC authentication is done by Authorization request header from the browser side, which is session independent.

    To force a "logout" on BASIC authentication, the server basically needs to return a 401 response.

    FacesContext facesContext = FacesContext.getCurrentInstance();
    ExternalContext externalContext = facesContext.getExternalContext();
    externalContext.invalidateSession();
    externalContext.responseSendError(401, "You are logged out.");
    facesContext.responseComplete();
    

    This will present a HTTP 401 error page which is customizable as in web.xml.

    You can instead also return a HTML page with meta refresh so that the enduser is redirected to the desired target page as specified in the meta refresh header content.

    FacesContext facesContext = FacesContext.getCurrentInstance();
    ExternalContext externalContext = facesContext.getExternalContext();
    externalContext.invalidateSession();
    externalContext.setResponseStatus(401);
    externalContext.getResponseOutputWriter().write("");
    facesContext.responseComplete();
    

    This seems indeed pretty low level and hacky, but the BASIC authentication is also pretty low level. This isn't necessary when using FORM authentication. Just invalidating the session and sending a normal redirect should work for FORM authentication.

提交回复
热议问题