KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jboss > web > tomcat > security > SecurityFlushSessionListener


1 /*
2  * JBoss, Home of Professional Open Source
3  * Copyright 2005, JBoss Inc., and individual contributors as indicated
4  * by the @authors tag. See the copyright.txt in the distribution for a
5  * full listing of individual contributors.
6  *
7  * This is free software; you can redistribute it and/or modify it
8  * under the terms of the GNU Lesser General Public License as
9  * published by the Free Software Foundation; either version 2.1 of
10  * the License, or (at your option) any later version.
11  *
12  * This software is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with this software; if not, write to the Free
19  * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
20  * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
21  */

22 package org.jboss.web.tomcat.security;
23
24 import java.security.Principal JavaDoc;
25 import java.security.acl.Group JavaDoc;
26 import java.util.Iterator JavaDoc;
27 import java.util.List JavaDoc;
28 import java.util.Set JavaDoc;
29
30 import javax.management.JMException JavaDoc;
31 import javax.management.MBeanServer JavaDoc;
32 import javax.management.ObjectName JavaDoc;
33 import javax.naming.InitialContext JavaDoc;
34 import javax.security.auth.Subject JavaDoc;
35 import javax.security.jacc.PolicyContext JavaDoc;
36 import javax.servlet.http.HttpSessionEvent JavaDoc;
37 import javax.servlet.http.HttpSessionListener JavaDoc;
38
39 import org.jboss.logging.Logger;
40 import org.jboss.mx.util.MBeanServerLocator;
41 import org.jboss.security.SubjectSecurityManager;
42
43 /**
44  * JBAS-2151: Look into implementing flushOnSessionInvalidation
45  * using a session listener
46  * @author < a HREF="mailto:Anil.Saldhana@jboss.org">Anil Saldhana</a>
47  * @since Jan 13, 2006
48  * @version $Revision: 41731 $
49  */

50 public class SecurityFlushSessionListener implements HttpSessionListener JavaDoc
51 {
52    private static Logger log = Logger.getLogger(SecurityFlushSessionListener.class);
53    
54    private boolean trace = log.isTraceEnabled();
55    
56    private String JavaDoc securityDomain = null;
57    
58    /**
59     *
60     * Create a new SecurityFlushSessionListener.
61     *
62     */

63    public SecurityFlushSessionListener()
64    {
65    }
66    
67    public void sessionCreated(HttpSessionEvent JavaDoc httpSessionEvent)
68    {
69       if(trace)
70          log.trace("Session Created with id=" + httpSessionEvent.getSession().getId());
71    }
72    
73    public void sessionDestroyed(HttpSessionEvent JavaDoc httpSessionEvent)
74    {
75       if(trace)
76          log.trace("Session Destroy with id=" + httpSessionEvent.getSession().getId());
77       try
78       {
79          Subject JavaDoc subject = getSubjectAndSecurityDomain();
80          if(trace)
81             log.trace("securityDomain="+ securityDomain);
82          if(securityDomain == null)
83             log.debug("Unable to obtain SecurityDomain");
84          Principal JavaDoc principal = getPrincipal(subject);
85          if(principal != null && securityDomain != null)
86             flushAuthenticationCache(principal);
87       }catch(Exception JavaDoc e)
88       {
89          log.error("Exception in sessionDestroyed:",e);
90       }
91    }
92    
93    /**
94     * Given the security domain and the Principal,
95     * flush the authentication cache
96     *
97     * @param principal
98     * @throws JMException
99     */

100    private void flushAuthenticationCache(Principal JavaDoc principal) throws JMException JavaDoc
101    {
102       MBeanServer JavaDoc server = MBeanServerLocator.locateJBoss();
103       ObjectName JavaDoc on = new ObjectName JavaDoc("jboss.security:service=JaasSecurityManager");
104       Object JavaDoc[] obj = new Object JavaDoc[] {securityDomain, principal};
105       String JavaDoc[] sig = new String JavaDoc[]{"java.lang.String", "java.security.Principal"};
106       if(trace)
107          logAuthenticatedPrincipals(on, true);
108       
109       //Flush the Authentication Cache
110
server.invoke(on,"flushAuthenticationCache", obj, sig);
111       if(trace)
112          logAuthenticatedPrincipals(on, false);
113    }
114    
115    /**
116     * Get the Principal given the authenticated Subject
117     * Currently the first principal that is not of type
118     * java.security.acl.Group is considered
119     *
120     * @param subject
121     * @return the authenticated principal
122     */

123    private Principal JavaDoc getPrincipal(Subject JavaDoc subject)
124    {
125       Principal JavaDoc principal = null;
126       if(subject != null)
127       {
128          Set JavaDoc principals = subject.getPrincipals();
129          if(principals != null || !principals.isEmpty())
130          {
131             Iterator JavaDoc iter = principals.iterator();
132             while(iter.hasNext())
133             {
134                principal = (Principal JavaDoc)iter.next();
135                if(principal instanceof Group JavaDoc == false)
136                   break;
137             }
138          }
139       }
140       if(trace)
141          log.trace("Authenticated Principal=" + principal);
142       return principal;
143    }
144    
145    /**
146     * Method that sets the securityDomain
147     * and then returns the authenticated subject
148     * First preference is given to the subject available
149     * from the Jacc SubjectContextPolicyContextHandler.
150     * As, a fallback, the Subject is obtained from the
151     * Security Manager Service
152     *
153     * @return
154     */

155    private Subject JavaDoc getSubjectAndSecurityDomain() throws Exception JavaDoc
156    {
157       SubjectSecurityManager mgr = null;
158       try
159       {
160          mgr = getSecurityManagerService();
161       }catch(Exception JavaDoc e)
162       {
163          log.debug("Obtaining SecurityManagerService failed::",e);
164       }
165       //First get the JACC Subject
166
String JavaDoc SUBJECT_CONTEXT_KEY = "javax.security.auth.Subject.container";
167       Subject JavaDoc subject = (Subject JavaDoc) PolicyContext.getContext(SUBJECT_CONTEXT_KEY);
168       if(trace)
169          log.trace("Jacc Subject = " + subject);
170       if(mgr != null)
171          securityDomain = mgr.getSecurityDomain();
172         
173       //Fallback
174
if(subject == null && mgr != null)
175       {
176          subject = mgr.getActiveSubject();
177          if(trace)
178             log.trace("Active Subject from security mgr service = " + subject);
179       }
180       return subject;
181    }
182    
183    /**
184     * Get the Security Manager Service
185     *
186     * @return
187     * @throws Exception
188     */

189    private SubjectSecurityManager getSecurityManagerService() throws Exception JavaDoc
190    {
191       //Get the SecurityManagerService from JNDI
192
InitialContext JavaDoc ctx = new InitialContext JavaDoc();
193       return (SubjectSecurityManager) ctx.lookup("java:comp/env/security/securityMgr");
194    }
195    
196    /**
197     * Method used to log authenticated principals
198     * remaining in cache (only when TRACE level logging is enabled)
199     *
200     * @param on ObjectName of the JaasSecurityManagerService
201     * @param isBeforeFlush Is the logging done before the auth cache flush
202     */

203    private void logAuthenticatedPrincipals(ObjectName JavaDoc on, boolean isBeforeFlush)
204    throws JMException JavaDoc
205    {
206       if(isBeforeFlush)
207         log.trace("Before flush of authentication cache::");
208       else
209          log.trace("After flush of authentication cache::");
210       MBeanServer JavaDoc server = MBeanServerLocator.locateJBoss();
211       
212       List JavaDoc list = (List JavaDoc)server.invoke(on,"getAuthenticationCachePrincipals",
213             new Object JavaDoc[]{securityDomain}, new String JavaDoc[] {"java.lang.String"} );
214       
215       int len = list != null ? list.size() : 0;
216       log.trace("Number of authenticated principals remaining in cache=" + len);
217       for(int i = 0 ; i < len; i++)
218          log.trace("Authenticated principal in cache=" + list.get(i));
219    }
220 }
221
Popular Tags