View Javadoc

1   /*
2   jGuard is a security framework based on top of jaas (java authentication and authorization security).
3   it is written for web applications, to resolve simply, access control problems.
4   
5   http://sourceforge.net/projects/jguard/
6   
7   Copyright (C) 2004  Charles GAY
8   
9   This library is free software; you can redistribute it and/or
10  modify it under the terms of the GNU Lesser General Public
11  License as published by the Free Software Foundation; either
12  version 2.1 of the License, or (at your option) any later version.
13  
14  This library is distributed in the hope that it will be useful,
15  but WITHOUT ANY WARRANTY; without even the implied warranty of
16  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  Lesser General Public License for more details.
18  
19  You should have received a copy of the GNU Lesser General Public
20  License along with this library; if not, write to the Free Software
21  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
22  
23  
24  jGuard project home page:
25  http://sourceforge.net/projects/jguard/
26  
27  */
28  package net.sf.jguard.core.authentication.configuration;
29  
30  
31  import java.security.AccessController;
32  import java.security.Policy;
33  import java.security.PrivilegedAction;
34  import java.util.ArrayList;
35  import java.util.Arrays;
36  import java.util.Collection;
37  import java.util.HashMap;
38  import java.util.Iterator;
39  import java.util.List;
40  import java.util.Map;
41  
42  import javax.security.auth.AuthPermission;
43  import javax.security.auth.login.AppConfigurationEntry;
44  import javax.security.auth.login.Configuration;
45  import net.sf.jguard.core.CoreConstants;
46  import net.sf.jguard.core.PolicyEnforcementPointOptions;
47  import net.sf.jguard.core.authentication.manager.AuthenticationHelper;
48  import net.sf.jguard.core.authentication.manager.AuthenticationManager;
49  import org.slf4j.Logger;
50  import org.slf4j.LoggerFactory;
51  
52  
53  /**
54   * extends the <a href="http://java.sun.com/j2se/1.4.2/docs/api/javax/security/auth/login/Configuration.html">
55   * Configuration</a>
56   * this class is used to define the authentication stack scheme per application.
57   * @author <a href="mailto:diabolo512@users.sourceforge.net">Charles Gay</a>
58   *
59   */
60  public final class JGuardConfiguration extends Configuration {
61  
62      private Collection internalConfigs = null;
63      private Map<String,List> appConfigurations = null;
64      private static Logger logger = LoggerFactory.getLogger(JGuardConfiguration.class.getName());
65      /**
66       * constructor.
67       */
68      public JGuardConfiguration() {
69          super();
70          logger.debug("#####  JGuardConfiguration  #####");
71  
72          internalConfigs = new ArrayList();
73          appConfigurations = new HashMap<String,List>();
74          final JGuardConfiguration jconf = this;
75          final String applicationName = System.getProperty(CoreConstants.APPLICATION_NAME_SYSTEM_PROPERTY);
76          final String configurationLocation = System.getProperty(CoreConstants.AUTHENTICATION_CONFIGURATION_FILE);
77           if(applicationName==null ||"".equals(applicationName)){
78                          throw new IllegalStateException(CoreConstants.APPLICATION_NAME_SYSTEM_PROPERTY+" system property has not been set");
79           }
80          String appHomePath = System.getProperty(CoreConstants.APPLICATION_HOME_PATH);
81          if(appHomePath!=null && !appHomePath.endsWith("/")){
82              appHomePath+="/";
83          }
84  
85          if(appHomePath==null){
86              appHomePath="";
87          }
88          loadConfigDataAndAuthenticationManager(applicationName, configurationLocation,jconf,appHomePath);
89              
90          
91  
92      }
93  
94        /**
95       * constructor.
96       */
97      public JGuardConfiguration(String applicationName,String configurationLocation,String appHomePath) {
98          super();
99          logger.debug("#####  JGuardConfiguration  #####");
100 
101         internalConfigs = new ArrayList();
102         appConfigurations = new HashMap<String,List>();
103         final JGuardConfiguration jconf = this;
104         
105         if(applicationName==null ||"".equals(applicationName)){
106             throw new IllegalStateException(" String applicationName argument in the constructor is empty or null");
107         }
108         
109         loadConfigDataAndAuthenticationManager(applicationName,configurationLocation,jconf,appHomePath);
110 
111     }
112     
113     
114     /**
115      * reload the Configuration.
116      * @see javax.security.auth.login.Configuration#refresh()
117      */
118     public void refresh() {
119         AccessController.checkPermission(new AuthPermission("refreshLoginConfiguration"));
120 
121         if(internalConfigs.size()>0){
122             Iterator itConfigs = internalConfigs.iterator();
123             while(itConfigs.hasNext()){
124                 Configuration tempConfig = (Configuration) itConfigs.next();
125                 tempConfig.refresh();
126             }
127         }
128 
129     }
130 
131     /**
132      * retrieve the AppConfigurationEntry array for the corresponding application's name.
133      * @param applicationName
134      * @return array of AppConfigurationEntry
135      * @see javax.security.auth.login.Configuration#getAppConfigurationEntry(java.lang.String)
136      */
137     public AppConfigurationEntry[] getAppConfigurationEntry(
138             String applicationName) {
139         Collection appInternalEntries = new ArrayList();
140         Iterator itConfigs = internalConfigs.iterator();
141         while(itConfigs.hasNext()){
142         	Configuration tempConfig = (Configuration) itConfigs.next();
143         	if (tempConfig == null){
144         		itConfigs.remove();
145         		logger.warn("the default Configuration implementation has been removed from the JGuardConfiguration which imported it");
146         	} else if( tempConfig.getAppConfigurationEntry(applicationName)!= null){
147         		appInternalEntries.addAll(Arrays.asList(tempConfig.getAppConfigurationEntry(applicationName)));
148         	}
149         }
150 
151         List jGuardAppConfigEntries = (List)appConfigurations.get(applicationName);
152 
153        if(jGuardAppConfigEntries!=null){
154            appInternalEntries.addAll(jGuardAppConfigEntries);
155        }
156         if(appInternalEntries.size()>0){
157             return (AppConfigurationEntry[]) appInternalEntries.toArray(new AppConfigurationEntry[appInternalEntries.size()]);
158         }
159 
160         return null;
161 
162     }
163 
164 
165     /**
166      * add AppconfigurationEntries for a specified application.
167      * @param applicationName
168      * @param entries
169      * @see javax.security.auth.login.Configuration#getAppConfigurationEntry(java.lang.String)
170      */
171     public  void addConfigEntriesForApplication(String applicationName,List entries) {
172     	if(entries == null || entries.size() == 0){
173     		logger.warn(" entries provided are null or empty ");
174 	        return;
175 	    }
176 
177 	    List applicationEntries = appConfigurations.get(applicationName);
178 	    if(applicationEntries==null){
179 	    	//this application is not yet configured
180 	        appConfigurations.put(applicationName,entries);
181 	    }
182 
183 	    //we don't add other appConfigurationEntries if the application name already exists
184 	    //because when webapp stops and start (but not app server), configuration for the application
185 	    // will have twice loginmodules
186     }
187 
188     /**
189      * add the same AppconfigurationEntries like an already configured application.
190      * @param applicationName name of the application to configure
191      * @param applicationTemplateName name of the application
192      * which will be the template to configure the first one.
193      * @see javax.security.auth.login.Configuration#getAppConfigurationEntry(java.lang.String)
194      */
195     public  void addConfigEntriesLikeApplication(String applicationName,String applicationTemplateName) {
196         List applicationEntries = appConfigurations.get(applicationTemplateName);
197         if(applicationEntries== null){
198         	logger.error(" there is no applications registered with your applicationName and password ");
199         	return;
200         }
201         appConfigurations.put(applicationName,applicationEntries);
202     }
203 
204    
205 
206     /**
207      * include Configuration information.
208      * @param configuration
209      */
210     protected void includeConfiguration(Configuration configuration){
211     	//we do not include a jGuardConfiguration to prevent infinite loop
212     	if(!configuration.getClass().getName().equals(JGuardConfiguration.class.getName())
213     	&&!internalConfigs.contains(configuration)){
214          internalConfigs.add(configuration);
215     	}
216     }
217 
218     private boolean loadConfigDataAndAuthenticationManager(final String applicationName,final String configurationLocation , final JGuardConfiguration jconf,String appHomePath) throws IllegalArgumentException {
219         final String applicationHomePath = appHomePath;
220         final JGuardConfiguration conf = this;
221         AccessController.doPrivileged(new PrivilegedAction() {
222             public Object run() {
223                 logger.debug("#####  Policy.getPolicy= #####"+Policy.getPolicy().getClass().getName());
224                 Map authenticationSettings = ConfigurationHelper.loadConfiguration(configurationLocation, applicationHomePath);
225                 
226                 //set application name
227                 Map authManagerOptions = (Map)authenticationSettings.get(CoreConstants.AUTHENTICATION_MANAGER_OPTIONS);
228 		authManagerOptions.put(PolicyEnforcementPointOptions.APPLICATION_NAME.getLabel(), applicationName);
229                 
230                 //add AppConfiguraiton related to the application
231                 List webappEntries = ConfigurationHelper.buildAppConfigurationEntries(applicationName, authenticationSettings, true);
232                 addConfigEntriesForApplication(applicationName, webappEntries);
233                 
234                 String authenticationScope = (String)authenticationSettings.get(CoreConstants.SCOPE);
235                 if(CoreConstants.JVM_SCOPE.equalsIgnoreCase(authenticationScope)){
236 			boolean includeConfigFromJavaParam = Boolean.valueOf((String)authenticationSettings.get(CoreConstants.INCLUDE_CONFIG_FROM_JAVA_PARAM));
237 			ConfigurationHelper.installConfiguration(conf,includeConfigFromJavaParam);
238 		}
239                 
240                 AuthenticationManager authenticationManager = AuthenticationHelper.initAuthenticationManager(jconf, authenticationSettings, applicationName);
241                 return authenticationManager;
242             }
243         });
244         return false;
245     }
246 
247 
248 	
249 }