return proper status code to IsPassive requests
[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
24 import javax.security.auth.Subject;
25 import javax.security.auth.callback.Callback;
26 import javax.security.auth.callback.CallbackHandler;
27 import javax.security.auth.callback.NameCallback;
28 import javax.security.auth.callback.PasswordCallback;
29 import javax.security.auth.callback.UnsupportedCallbackException;
30 import javax.security.auth.login.LoginException;
31 import javax.servlet.ServletException;
32 import javax.servlet.http.HttpServlet;
33 import javax.servlet.http.HttpServletRequest;
34 import javax.servlet.http.HttpServletResponse;
35
36 import org.apache.log4j.Logger;
37 import org.opensaml.util.URLBuilder;
38 import org.opensaml.xml.util.DatatypeHelper;
39 import org.opensaml.xml.util.Pair;
40
41 import edu.internet2.middleware.shibboleth.idp.authn.AuthenticationEngine;
42 import edu.internet2.middleware.shibboleth.idp.authn.LoginHandler;
43
44 /**
45  * This servlet should be protected by a filter which populates REMOTE_USER. The serlvet will then set the remote user
46  * field in a LoginContext.
47  */
48 public class UsernamePasswordLoginServlet extends HttpServlet {
49
50     /** Serial version UID. */
51     private static final long serialVersionUID = -572799841125956990L;
52
53     /** Class logger. */
54     private final Logger log = Logger.getLogger(RemoteUserAuthServlet.class);
55
56     /** Name of JAAS configuration used to authenticate users. */
57     private final String jaasConfigName = "ShibUserPassAuth";
58
59     /** Login page name. */
60     private final String loginPage = "login.jsp";
61     
62     /** Parameter name to indicate login failure. */
63     private final String failureParam = "loginFailed";
64
65     /** HTTP request parameter containing the user name. */
66     private final String usernameAttribute = "j_username";
67
68     /** HTTP request parameter containing the user's password. */
69     private final String passwordAttribute = "j_password";
70
71     /** {@inheritDoc} */
72     protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException,
73             IOException {
74         String username = DatatypeHelper.safeTrimOrNullString(request.getParameter(usernameAttribute));
75         String password = DatatypeHelper.safeTrimOrNullString(request.getParameter(passwordAttribute));
76
77         if (username == null || password == null) {
78             redirectToLoginPage(request, response, null);
79             return;
80         }
81
82         if (authenticateUser(request)) {
83             AuthenticationEngine.returnToAuthenticationEngine(request, response);
84         } else {
85             List<Pair<String, String>> queryParams = new ArrayList<Pair<String, String>>();
86             queryParams.add(new Pair<String, String>(failureParam, "true"));
87             redirectToLoginPage(request, response, queryParams);
88             return;
89         }
90     }
91
92     /**
93      * Sends the user to the login page.
94      * 
95      * @param request current request
96      * @param response current response
97      * @param queryParams query parameters to pass to the login page
98      */
99     protected void redirectToLoginPage(HttpServletRequest request, HttpServletResponse response,
100             List<Pair<String, String>> queryParams) {
101         try {
102             StringBuilder pathBuilder = new StringBuilder();
103             pathBuilder.append(request.getContextPath());
104             pathBuilder.append("/");
105             pathBuilder.append(loginPage);
106
107             URLBuilder urlBuilder = new URLBuilder();
108             urlBuilder.setScheme(request.getScheme());
109             urlBuilder.setHost(request.getLocalName());
110             urlBuilder.setPort(request.getLocalPort());
111             urlBuilder.setPath(pathBuilder.toString());
112             if (queryParams != null) {
113                 urlBuilder.getQueryParams().addAll(queryParams);
114             }
115             
116             if (log.isDebugEnabled()) {
117                 log.debug("Redirecting to login page " + urlBuilder.buildURL());
118             }
119
120             response.sendRedirect(urlBuilder.buildURL());
121             return;
122         } catch (IOException ex) {
123             log.error("Unable to redirect to login page.", ex);
124         }
125     }
126
127     /**
128      * Authenticate a username and password against JAAS. If authentication succeeds the principal name and subject are
129      * placed into the request in their respective attributes.
130      * 
131      * @param request current authentication request
132      * 
133      * @return true of authentication succeeds, false if not
134      */
135     protected boolean authenticateUser(HttpServletRequest request) {
136
137         try {
138             String username = DatatypeHelper.safeTrimOrNullString(request.getParameter(usernameAttribute));
139             String password = DatatypeHelper.safeTrimOrNullString(request.getParameter(passwordAttribute));
140
141             SimpleCallbackHandler cbh = new SimpleCallbackHandler(username, password);
142
143             javax.security.auth.login.LoginContext jaasLoginCtx = new javax.security.auth.login.LoginContext(
144                     jaasConfigName, cbh);
145
146             jaasLoginCtx.login();
147             log.debug("Successfully authenticated user " + username);
148
149             Subject subject = jaasLoginCtx.getSubject();
150             Principal principal = subject.getPrincipals().iterator().next();
151             request.setAttribute(LoginHandler.PRINCIPAL_NAME_KEY, principal.getName());
152             request.setAttribute(LoginHandler.SUBJECT_KEY, jaasLoginCtx.getSubject());
153
154             return true;
155         } catch (LoginException e) {
156             if (log.isDebugEnabled()) {
157                 log.debug("User authentication failed", e);
158             }
159             return false;
160         }
161     }
162
163     /**
164      * A callback handler that provides static name and password data to a JAAS login process.
165      * 
166      * This handler only supports {@link NameCallback} and {@link PasswordCallback}.
167      */
168     protected class SimpleCallbackHandler implements CallbackHandler {
169
170         /** Name of the user. */
171         private String uname;
172
173         /** User's password. */
174         private String pass;
175
176         /**
177          * Constructor.
178          * 
179          * @param username The username
180          * @param password The password
181          */
182         public SimpleCallbackHandler(String username, String password) {
183             uname = username;
184             pass = password;
185         }
186
187         /**
188          * Handle a callback.
189          * 
190          * @param callbacks The list of callbacks to process.
191          * 
192          * @throws UnsupportedCallbackException If callbacks has a callback other than {@link NameCallback} or
193          *             {@link PasswordCallback}.
194          */
195         public void handle(final Callback[] callbacks) throws UnsupportedCallbackException {
196
197             if (callbacks == null || callbacks.length == 0) {
198                 return;
199             }
200
201             for (Callback cb : callbacks) {
202                 if (cb instanceof NameCallback) {
203                     NameCallback ncb = (NameCallback) cb;
204                     ncb.setName(uname);
205                 } else if (cb instanceof PasswordCallback) {
206                     PasswordCallback pcb = (PasswordCallback) cb;
207                     pcb.setPassword(pass.toCharArray());
208                 }
209             }
210         }
211     }
212 }