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