View Javadoc
1   /**
2    * Logback: the reliable, generic, fast and flexible logging framework.
3    * Copyright (C) 1999-2015, QOS.ch. All rights reserved.
4    *
5    * This program and the accompanying materials are dual-licensed under
6    * either the terms of the Eclipse Public License v1.0 as published by
7    * the Eclipse Foundation
8    *
9    *   or (per the licensee's choosing)
10   *
11   * under the terms of the GNU Lesser General Public License version 2.1
12   * as published by the Free Software Foundation.
13   */
14  package chapters.mdc;
15  
16  import java.io.IOException;
17  import java.security.Principal;
18  
19  import jakarta.servlet.Filter;
20  import jakarta.servlet.FilterChain;
21  import jakarta.servlet.FilterConfig;
22  import jakarta.servlet.ServletException;
23  import jakarta.servlet.ServletRequest;
24  import jakarta.servlet.ServletResponse;
25  import jakarta.servlet.http.HttpServletRequest;
26  
27  import org.slf4j.MDC;
28  
29  /**
30   * A simple servlet filter that puts the username
31   * found either in the Principal.
32   * 
33   * <p> The value is removed from the MDC once the request has been
34   * fully processed.
35   *
36   * @author S&eacute;bastien Pennec
37   */
38  public class UserServletFilter implements Filter {
39  
40      private final String USER_KEY = "username";
41  
42      public void destroy() {
43      }
44  
45      public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
46  
47          boolean successfulRegistration = false;
48          HttpServletRequest req = (HttpServletRequest) request;
49          Principal principal = req.getUserPrincipal();
50          // Please note that we also could have used a cookie to
51          // retrieve the user name
52  
53          if (principal != null) {
54              String username = principal.getName();
55              successfulRegistration = registerUsername(username);
56          }
57  
58          try {
59              chain.doFilter(request, response);
60          } finally {
61              if (successfulRegistration) {
62                  MDC.remove(USER_KEY);
63              }
64          }
65      }
66  
67      public void init(FilterConfig arg0) throws ServletException {
68      }
69  
70      /**
71       * Register the user in the MDC under USER_KEY.
72       * 
73       * @param username
74       * @return true id the user can be successfully registered
75       */
76      private boolean registerUsername(String username) {
77          if (username != null && username.trim().length() > 0) {
78              MDC.put(USER_KEY, username);
79              return true;
80          }
81          return false;
82      }
83  
84  }