Search code examples
authenticationtomcatbasic-authenticationjndi

How to configure Tomcat Realm timeout


I am using the Tomcat 9 and JNDIRealm with Basic Auth to authenticate users. The problem is that once the user closes the Web Browser he is challenged again for username & password. This is also according to the documentation I could find for Tomcat:

Once a user has been authenticated, the user (and his or her associated roles) are cached within Tomcat for the duration of the user's login. (For FORM-based authentication, that means until the session times out or is invalidated; for BASIC authentication, that means until the user closes their browser)

This behaviour is pretty annoying as the users have to login every time after they closed the browser. My wish would be that a user login is cached for 1 week. Only then a challenge for the credentials should happen. Is there any way to change this default behaviour?


Solution

  • In the default configuration authentication is cached for the duration of Tomcat's session (cf. the cache attribute on the authenticators).

    If your application does not use HttpSessions (e.g. a REST API), the authenticators will try to function without it:

    • the BASIC authenticator will rely on browsers behavior of caching the credentials supplied by the user for the duration of the browser's session,
    • the FORM authenticator must use a cookie, so it always creates a Tomcat session.

    However this behavior is configurable: just set the alwaysUseSession attribute on your BasicAuthenticator in your application's context file (or the default conf/context.xml file to apply the setting to all applications):

    <Context>
        <Valve
            className="org.apache.catalina.authenticator.BasicAuthenticator"
            alwaysUseSession="true"/>
        ...
    </Context>
    

    Remark: The JSESSIONID cookie itself expires by default at the end of the browser's session (check this answer), hence Tomcat's sessions expire usually when you close the browser. You need to configure the appropriate <max-age> value in your application's web.xml descriptor (or Tomcat's default conf/web.xml file).