2 package net.sourceforge.guacamole.net.basic;
4 import java.io.IOException;
5 import java.util.Collection;
7 import javax.servlet.ServletException;
8 import javax.servlet.http.HttpServlet;
9 import javax.servlet.http.HttpServletRequest;
10 import javax.servlet.http.HttpServletResponse;
11 import javax.servlet.http.HttpSession;
12 import net.sourceforge.guacamole.GuacamoleException;
13 import net.sourceforge.guacamole.net.auth.AuthenticationProvider;
14 import net.sourceforge.guacamole.net.auth.Credentials;
15 import net.sourceforge.guacamole.net.basic.event.SessionListenerCollection;
16 import net.sourceforge.guacamole.net.basic.properties.BasicGuacamoleProperties;
17 import net.sourceforge.guacamole.net.event.AuthenticationFailureEvent;
18 import net.sourceforge.guacamole.net.event.AuthenticationSuccessEvent;
19 import net.sourceforge.guacamole.net.event.listener.AuthenticationFailureListener;
20 import net.sourceforge.guacamole.net.event.listener.AuthenticationSuccessListener;
21 import net.sourceforge.guacamole.properties.GuacamoleProperties;
22 import net.sourceforge.guacamole.protocol.GuacamoleConfiguration;
23 import org.slf4j.Logger;
24 import org.slf4j.LoggerFactory;
27 * Abstract servlet which provides an authenticatedService() function that
28 * is only called if the HTTP request is authenticated, or the current
29 * HTTP session has already been authenticated.
31 * Authorized configurations are retrieved using the authentication provider
32 * defined in guacamole.properties. The authentication provider has access
33 * to the request and session, in addition to any submitted username and
34 * password, in order to authenticate the user.
36 * All authorized configurations will be stored in the current HttpSession.
38 * Success and failure are logged.
40 * @author Michael Jumper
42 public abstract class AuthenticatingHttpServlet extends HttpServlet {
44 private Logger logger = LoggerFactory.getLogger(AuthenticatingHttpServlet.class);
47 * The session attribute holding the map of configurations.
49 private static final String CONFIGURATIONS_ATTRIBUTE = "GUAC_CONFIGS";
52 * The session attribute holding the credentials authorizing this session.
54 private static final String CREDENTIALS_ATTRIBUTE = "GUAC_CREDS";
57 * The error message to be provided to the client user if authentication
58 * fails for ANY REASON.
60 private static final String AUTH_ERROR_MESSAGE =
61 "User not logged in or authentication failed.";
64 * The AuthenticationProvider to use to authenticate all requests.
66 private AuthenticationProvider authProvider;
69 public void init() throws ServletException {
71 // Get auth provider instance
73 authProvider = GuacamoleProperties.getRequiredProperty(BasicGuacamoleProperties.AUTH_PROVIDER);
75 catch (GuacamoleException e) {
76 logger.error("Error getting authentication provider from properties.", e);
77 throw new ServletException(e);
83 * Notifies all listeners in the given collection that authentication has
86 * @param listeners A collection of all listeners that should be notified.
87 * @param credentials The credentials associated with the authentication
88 * request that failed.
90 private void notifyFailed(Collection listeners, Credentials credentials) {
92 // Build event for auth failure
93 AuthenticationFailureEvent event = new AuthenticationFailureEvent(credentials);
95 // Notify all listeners
96 for (Object listener : listeners) {
98 if (listener instanceof AuthenticationFailureListener)
99 ((AuthenticationFailureListener) listener).authenticationFailed(event);
101 catch (GuacamoleException e) {
102 logger.error("Error notifying AuthenticationFailureListener.", e);
109 * Notifies all listeners in the given collection that authentication was
112 * @param listeners A collection of all listeners that should be notified.
113 * @param credentials The credentials associated with the authentication
114 * request that succeeded.
115 * @return true if all listeners are allowing the authentication success,
116 * or if there are no listeners, and false if any listener is
117 * canceling the authentication success. Note that once one
118 * listener cancels, no other listeners will run.
119 * @throws GuacamoleException If any listener throws an error while being
120 * notified. Note that if any listener throws an
121 * error, the success is canceled, and no other
122 * listeners will run.
124 private boolean notifySuccess(Collection listeners, Credentials credentials)
125 throws GuacamoleException {
127 // Build event for auth success
128 AuthenticationSuccessEvent event = new AuthenticationSuccessEvent(credentials);
130 // Notify all listeners
131 for (Object listener : listeners) {
132 if (listener instanceof AuthenticationSuccessListener) {
134 // Cancel immediately if hook returns false
135 if (!((AuthenticationSuccessListener) listener).authenticationSucceeded(event))
146 * Sends a predefined, generic error message to the user, along with a
147 * "403 - Forbidden" HTTP status code in the response.
149 * @param response The response to send the error within.
150 * @throws IOException If an error occurs while sending the error.
152 private void failAuthentication(HttpServletResponse response) throws IOException {
153 response.sendError(HttpServletResponse.SC_FORBIDDEN);
157 * Returns the credentials associated with the given session.
159 * @param session The session to retrieve credentials from.
160 * @return The credentials associated with the given session.
162 protected Credentials getCredentials(HttpSession session) {
163 return (Credentials) session.getAttribute(CREDENTIALS_ATTRIBUTE);
167 * Returns the configurations associated with the given session.
169 * @param session The session to retrieve configurations from.
170 * @return The configurations associated with the given session.
172 protected Map<String, GuacamoleConfiguration> getConfigurations(HttpSession session) {
173 return (Map<String, GuacamoleConfiguration>) session.getAttribute(CONFIGURATIONS_ATTRIBUTE);
177 protected void service(HttpServletRequest request, HttpServletResponse response)
178 throws IOException, ServletException {
180 HttpSession httpSession = request.getSession(true);
182 // Try to get configs from session
183 Map<String, GuacamoleConfiguration> configs = getConfigurations(httpSession);
185 // If no configs, try to authenticate the user to get the configs using
187 if (configs == null) {
189 SessionListenerCollection listeners;
191 listeners = new SessionListenerCollection(httpSession);
193 catch (GuacamoleException e) {
194 logger.error("Failed to retrieve listeners. Authentication canceled.", e);
195 failAuthentication(response);
199 // Retrieve username and password from parms
200 String username = request.getParameter("username");
201 String password = request.getParameter("password");
203 // Build credentials object
204 Credentials credentials = new Credentials();
205 credentials.setSession(httpSession);
206 credentials.setRequest(request);
207 credentials.setUsername(username);
208 credentials.setPassword(password);
210 // Get authorized configs
212 configs = authProvider.getAuthorizedConfigurations(credentials);
216 /******** HANDLE FAILED AUTHENTICATION ********/
218 // If error retrieving configs, fail authentication, notify listeners
219 catch (GuacamoleException e) {
220 logger.error("Error retrieving configuration(s) for user \"{}\".",
221 credentials.getUsername());
223 notifyFailed(listeners, credentials);
224 failAuthentication(response);
228 // If no configs, fail authentication, notify listeners
229 if (configs == null) {
230 logger.warn("Authentication attempt from {} for user \"{}\" failed.",
231 request.getRemoteAddr(), credentials.getUsername());
233 notifyFailed(listeners, credentials);
234 failAuthentication(response);
239 /******** HANDLE SUCCESSFUL AUTHENTICATION ********/
243 // Otherwise, authentication has been succesful
244 logger.info("User \"{}\" successfully authenticated from {}.",
245 credentials.getUsername(), request.getRemoteAddr());
247 // Notify of success, cancel if requested
248 if (!notifySuccess(listeners, credentials)) {
249 logger.info("Successful authentication canceled by hook.");
250 failAuthentication(response);
255 catch (GuacamoleException e) {
257 // Cancel authentication success if hook throws exception
258 logger.error("Successful authentication canceled by error in hook.");
259 failAuthentication(response);
264 // Associate configs and credentials with session
265 httpSession.setAttribute(CONFIGURATIONS_ATTRIBUTE, configs);
266 httpSession.setAttribute(CREDENTIALS_ATTRIBUTE, credentials);
271 // Allow servlet to run now that authentication has been validated
272 authenticatedService(configs, request, response);
276 protected abstract void authenticatedService(
277 Map<String, GuacamoleConfiguration> configs,
278 HttpServletRequest request, HttpServletResponse response)
279 throws ServletException, IOException;