apparently Chad doesn't like user feedback; well I'll show him! (fixes SIDP-42....
[java-idp.git] / src / edu / internet2 / middleware / shibboleth / idp / authn / provider / UsernamePasswordLoginServlet.java
1 /*
2  * Copyright [2006] [University Corporation for Advanced Internet Development, Inc.]
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 package edu.internet2.middleware.shibboleth.idp.authn.provider;
18
19 import java.io.IOException;
20 import java.security.Principal;
21 import java.util.ArrayList;
22 import java.util.List;
23 import java.util.Set;
24
25 import javax.security.auth.Subject;
26 import javax.security.auth.callback.Callback;
27 import javax.security.auth.callback.CallbackHandler;
28 import javax.security.auth.callback.NameCallback;
29 import javax.security.auth.callback.PasswordCallback;
30 import javax.security.auth.callback.UnsupportedCallbackException;
31 import javax.security.auth.login.LoginException;
32 import javax.servlet.ServletException;
33 import javax.servlet.http.HttpServlet;
34 import javax.servlet.http.HttpServletRequest;
35 import javax.servlet.http.HttpServletResponse;
36
37 import org.opensaml.util.URLBuilder;
38 import org.opensaml.xml.util.DatatypeHelper;
39 import org.opensaml.xml.util.Pair;
40 import org.slf4j.Logger;
41 import org.slf4j.LoggerFactory;
42
43 import edu.internet2.middleware.shibboleth.idp.authn.AuthenticationEngine;
44 import edu.internet2.middleware.shibboleth.idp.authn.LoginHandler;
45
46 /**
47  * This servlet should be protected by a filter which populates REMOTE_USER. The serlvet will then set the remote user
48  * field in a LoginContext.
49  */
50 public class UsernamePasswordLoginServlet extends HttpServlet {
51
52     /** Serial version UID. */
53     private static final long serialVersionUID = -572799841125956990L;
54
55     /** Class logger. */
56     private final Logger log = LoggerFactory.getLogger(RemoteUserAuthServlet.class);
57
58     /** Name of JAAS configuration used to authenticate users. */
59     private final String jaasConfigName = "ShibUserPassAuth";
60
61     /** Login page name. */
62     private final String loginPage = "login.jsp";
63     
64     /** Parameter name to indicate login failure. */
65     private final String failureParam = "loginFailed";
66
67     /** HTTP request parameter containing the user name. */
68     private final String usernameAttribute = "j_username";
69
70     /** HTTP request parameter containing the user's password. */
71     private final String passwordAttribute = "j_password";
72
73     /** {@inheritDoc} */
74     protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException,
75             IOException {
76         String username = DatatypeHelper.safeTrimOrNullString(request.getParameter(usernameAttribute));
77         String password = DatatypeHelper.safeTrimOrNullString(request.getParameter(passwordAttribute));
78
79         if (username == null || password == null) {
80             redirectToLoginPage(request, response, null);
81             return;
82         }
83
84         if (authenticateUser(request)) {
85             AuthenticationEngine.returnToAuthenticationEngine(request, response);
86         } else {
87             List<Pair<String, String>> queryParams = new ArrayList<Pair<String, String>>();
88             queryParams.add(new Pair<String, String>(failureParam, "true"));
89             redirectToLoginPage(request, response, queryParams);
90             return;
91         }
92     }
93
94     /**
95      * Sends the user to the login page.
96      * 
97      * @param request current request
98      * @param response current response
99      * @param queryParams query parameters to pass to the login page
100      */
101     protected void redirectToLoginPage(HttpServletRequest request, HttpServletResponse response,
102             List<Pair<String, String>> queryParams) {
103         try {
104             StringBuilder pathBuilder = new StringBuilder();
105             pathBuilder.append(request.getContextPath());
106             pathBuilder.append("/");
107             pathBuilder.append(loginPage);
108
109             URLBuilder urlBuilder = new URLBuilder();
110             urlBuilder.setScheme(request.getScheme());
111             urlBuilder.setHost(request.getLocalName());
112             urlBuilder.setPort(request.getLocalPort());
113             urlBuilder.setPath(pathBuilder.toString());
114             if (queryParams != null) {
115                 urlBuilder.getQueryParams().addAll(queryParams);
116             }
117
118             log.debug("Redirecting to login page {}", urlBuilder.buildURL());
119             response.sendRedirect(urlBuilder.buildURL());
120             return;
121         } catch (IOException ex) {
122             log.error("Unable to redirect to login page.", ex);
123         }
124     }
125
126     /**
127      * Authenticate a username and password against JAAS. If authentication succeeds the name of the first principal, or
128      * the username if that is empty, and the subject are placed into the request in their respective attributes.
129      * 
130      * @param request current authentication request
131      * 
132      * @return true of authentication succeeds, false if not
133      */
134     protected boolean authenticateUser(HttpServletRequest request) {
135
136         try {
137             String username = DatatypeHelper.safeTrimOrNullString(request.getParameter(usernameAttribute));
138             String password = DatatypeHelper.safeTrimOrNullString(request.getParameter(passwordAttribute));
139
140             SimpleCallbackHandler cbh = new SimpleCallbackHandler(username, password);
141
142             javax.security.auth.login.LoginContext jaasLoginCtx = new javax.security.auth.login.LoginContext(
143                     jaasConfigName, cbh);
144
145             jaasLoginCtx.login();
146             log.debug("Successfully authenticated user {}", username);
147
148             Subject subject = jaasLoginCtx.getSubject();
149             Set<Principal> principals = subject.getPrincipals();
150
151             if(principals.isEmpty()){
152                 request.setAttribute(LoginHandler.PRINCIPAL_NAME_KEY, username);
153             }else{       
154                 Principal principal = principals.iterator().next();
155                 String principalName = DatatypeHelper.safeTrimOrNullString(principal.getName());
156                 if(principalName == null){
157                     request.setAttribute(LoginHandler.PRINCIPAL_NAME_KEY, username);
158                 }else{
159                     request.setAttribute(LoginHandler.PRINCIPAL_NAME_KEY, principal.getName());
160                 }
161                 request.setAttribute(LoginHandler.SUBJECT_KEY, jaasLoginCtx.getSubject());
162             }
163
164             return true;
165         } catch (LoginException e) {
166             log.debug("User authentication failed", e);
167             return false;
168         }
169     }
170
171     /**
172      * A callback handler that provides static name and password data to a JAAS loging process.
173      * 
174      * This handler only supports {@link NameCallback} and {@link PasswordCallback}.
175      */
176     protected class SimpleCallbackHandler implements CallbackHandler {
177
178         /** Name of the user. */
179         private String uname;
180
181         /** User's password. */
182         private String pass;
183
184         /**
185          * Constructor.
186          * 
187          * @param username The username
188          * @param password The password
189          */
190         public SimpleCallbackHandler(String username, String password) {
191             uname = username;
192             pass = password;
193         }
194
195         /**
196          * Handle a callback.
197          * 
198          * @param callbacks The list of callbacks to process.
199          * 
200          * @throws UnsupportedCallbackException If callbacks has a callback other than {@link NameCallback} or
201          *             {@link PasswordCallback}.
202          */
203         public void handle(final Callback[] callbacks) throws UnsupportedCallbackException {
204
205             if (callbacks == null || callbacks.length == 0) {
206                 return;
207             }
208
209             for (Callback cb : callbacks) {
210                 if (cb instanceof NameCallback) {
211                     NameCallback ncb = (NameCallback) cb;
212                     ncb.setName(uname);
213                 } else if (cb instanceof PasswordCallback) {
214                     PasswordCallback pcb = (PasswordCallback) cb;
215                     pcb.setPassword(pass.toCharArray());
216                 }
217             }
218         }
219     }
220 }