Ricardo Marimon
Ricardo Marimon

Reputation: 10687

Listen to tomcat realm authentication events

I need to know when tomcat accepts a login using realm authentication for a given context. I've been looking at the possible listeners available (ServletContextListener and ServletContextAttributeListener) but can't figure out how to be notified when a login occurs. This should also work when using tomcat single sign on for multiple contexts. Any ideas?

Upvotes: 2

Views: 2704

Answers (2)

BalusC
BalusC

Reputation: 1108802

Unfortunately there's no standard/abstract way to hook on it using the Servlet API. You need either to write appserver specific logic or to implement a global Filter which checks the HttpServletRequest#getUserPrincipal() everytime. E.g.:

public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) {
    HttpServletRequest request = (HttpServletRequest) req;
    Principal user = request.getUserPrincipal();
    HttpSession session = request.getSession(false);

    if (user != null && (session == null || session.getAttribute("user") == null)) {
        request.getSession().setAttribute("user", user);

        // First-time login. You can do your intercepting thing here.
    }

    chain.doFilter(req, res);
}

Upvotes: 8

cjstehno
cjstehno

Reputation: 13994

If you have access to the server configuration, you might try writing a LifecycleListener (http://tomcat.apache.org/tomcat-6.0-doc/api/org/apache/catalina/LifecycleListener.html), which are configured with the server (see the tomcat server config docs for your version).

Not sure if it will do the trick or not, but a good place to check.

Good luck.

Upvotes: 1

Related Questions