Listen to tomcat realm authentication events

前端 未结 2 853
余生分开走
余生分开走 2021-01-15 00:57

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 an

2条回答
  •  醉话见心
    2021-01-15 00:59

    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);
    }
    

提交回复
热议问题