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.setHeader("X-Guacamole-Error-Message", AUTH_ERROR_MESSAGE);
154 response.sendError(HttpServletResponse.SC_FORBIDDEN);
158 * Returns the credentials associated with the given session.
160 * @param session The session to retrieve credentials from.
161 * @return The credentials associated with the given session.
163 protected Credentials getCredentials(HttpSession session) {
164 return (Credentials) session.getAttribute(CREDENTIALS_ATTRIBUTE);
168 * Returns the configurations associated with the given session.
170 * @param session The session to retrieve configurations from.
171 * @return The configurations associated with the given session.
173 protected Map<String, GuacamoleConfiguration> getConfigurations(HttpSession session) {
174 return (Map<String, GuacamoleConfiguration>) session.getAttribute(CONFIGURATIONS_ATTRIBUTE);
178 protected void service(HttpServletRequest request, HttpServletResponse response)
179 throws IOException, ServletException {
181 HttpSession httpSession = request.getSession(true);
183 // Try to get configs from session
184 Map<String, GuacamoleConfiguration> configs = getConfigurations(httpSession);
186 // If no configs, try to authenticate the user to get the configs using
188 if (configs == null) {
190 SessionListenerCollection listeners;
192 listeners = new SessionListenerCollection(httpSession);
194 catch (GuacamoleException e) {
195 logger.error("Failed to retrieve listeners. Authentication canceled.", e);
196 failAuthentication(response);
200 // Retrieve username and password from parms
201 String username = request.getParameter("username");
202 String password = request.getParameter("password");
204 // Build credentials object
205 Credentials credentials = new Credentials();
206 credentials.setSession(httpSession);
207 credentials.setRequest(request);
208 credentials.setUsername(username);
209 credentials.setPassword(password);
211 // Get authorized configs
213 configs = authProvider.getAuthorizedConfigurations(credentials);
217 /******** HANDLE FAILED AUTHENTICATION ********/
219 // If error retrieving configs, fail authentication, notify listeners
220 catch (GuacamoleException e) {
221 logger.error("Error retrieving configuration(s) for user \"{}\".",
222 credentials.getUsername());
224 notifyFailed(listeners, credentials);
225 failAuthentication(response);
229 // If no configs, fail authentication, notify listeners
230 if (configs == null) {
231 logger.warn("Authentication attempt from {} for user \"{}\" failed.",
232 request.getRemoteAddr(), credentials.getUsername());
234 notifyFailed(listeners, credentials);
235 failAuthentication(response);
240 /******** HANDLE SUCCESSFUL AUTHENTICATION ********/
244 // Otherwise, authentication has been succesful
245 logger.info("User \"{}\" successfully authenticated from {}.",
246 credentials.getUsername(), request.getRemoteAddr());
248 // Notify of success, cancel if requested
249 if (!notifySuccess(listeners, credentials)) {
250 logger.info("Successful authentication canceled by hook.");
251 failAuthentication(response);
256 catch (GuacamoleException e) {
258 // Cancel authentication success if hook throws exception
259 logger.error("Successful authentication canceled by error in hook.");
260 failAuthentication(response);
265 // Associate configs and credentials with session
266 httpSession.setAttribute(CONFIGURATIONS_ATTRIBUTE, configs);
267 httpSession.setAttribute(CREDENTIALS_ATTRIBUTE, credentials);
272 // Allow servlet to run now that authentication has been validated
273 authenticatedService(configs, request, response);
277 protected abstract void authenticatedService(
278 Map<String, GuacamoleConfiguration> configs,
279 HttpServletRequest request, HttpServletResponse response)
280 throws ServletException, IOException;