390108 Servlet 3.0 API for programmatic login doesn't appear to work

This commit is contained in:
Jan Bartel 2012-10-12 19:00:28 +11:00
parent 7625f0b8b3
commit 785e06d347
15 changed files with 221 additions and 96 deletions

View File

@ -31,6 +31,8 @@ import javax.security.auth.message.config.ServerAuthConfig;
import javax.security.auth.message.config.ServerAuthContext;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.eclipse.jetty.security.Authenticator;
import org.eclipse.jetty.security.IdentityService;
@ -38,15 +40,21 @@ import org.eclipse.jetty.security.ServerAuthException;
import org.eclipse.jetty.security.UserAuthentication;
import org.eclipse.jetty.security.authentication.DeferredAuthentication;
import org.eclipse.jetty.security.authentication.LoginAuthenticator;
import org.eclipse.jetty.security.authentication.SessionAuthentication;
import org.eclipse.jetty.security.jaspi.modules.BaseAuthModule;
import org.eclipse.jetty.server.Authentication;
import org.eclipse.jetty.server.UserIdentity;
import org.eclipse.jetty.server.Authentication.User;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.Logger;
/**
* @version $Rev: 4793 $ $Date: 2009-03-19 00:00:01 +0100 (Thu, 19 Mar 2009) $
*/
public class JaspiAuthenticator extends LoginAuthenticator
{
private static final Logger LOG = Log.getLogger(JaspiAuthenticator.class.getName());
private final ServerAuthConfig _authConfig;
private final Map _authProperties;
@ -107,6 +115,28 @@ public class JaspiAuthenticator extends LoginAuthenticator
}
/**
* @see org.eclipse.jetty.security.authentication.LoginAuthenticator#login(java.lang.String, java.lang.Object, javax.servlet.ServletRequest)
*/
@Override
public UserIdentity login(String username, Object password, ServletRequest request)
{
UserIdentity user = _loginService.login(username, password);
if (user != null)
{
renewSession((HttpServletRequest)request, null);
HttpSession session = ((HttpServletRequest)request).getSession(true);
if (session != null)
{
SessionAuthentication sessionAuth = new SessionAuthentication(getAuthMethod(), user, password);
session.setAttribute(SessionAuthentication.__J_AUTHENTICATED, sessionAuth);
}
}
return user;
}
public Authentication validateRequest(JaspiMessageInfo messageInfo) throws ServerAuthException
{
try
@ -151,6 +181,12 @@ public class JaspiAuthenticator extends LoginAuthenticator
String[] groups = groupPrincipalCallback == null ? null : groupPrincipalCallback.getGroups();
userIdentity = _identityService.newUserIdentity(clientSubject, principal, groups);
}
HttpSession session = ((HttpServletRequest)messageInfo.getRequestMessage()).getSession(false);
Authentication cached = (session == null?null:(SessionAuthentication)session.getAttribute(SessionAuthentication.__J_AUTHENTICATED));
if (cached != null)
return cached;
return new UserAuthentication(getAuthMethod(), userIdentity);
}
if (authStatus == AuthStatus.SEND_SUCCESS)

View File

@ -43,7 +43,10 @@ import org.eclipse.jetty.util.security.Password;
import org.eclipse.jetty.security.CrossContextPsuedoSession;
import org.eclipse.jetty.security.authentication.DeferredAuthentication;
import org.eclipse.jetty.security.authentication.LoginCallbackImpl;
import org.eclipse.jetty.security.authentication.SessionAuthentication;
import org.eclipse.jetty.security.jaspi.callback.CredentialValidationCallback;
import org.eclipse.jetty.server.Authentication;
import org.eclipse.jetty.server.UserIdentity;
import org.eclipse.jetty.util.StringUtil;
import org.eclipse.jetty.util.URIUtil;
import org.eclipse.jetty.util.log.Log;
@ -214,21 +217,22 @@ public class FormAuthModule extends BaseAuthModule
// Check if the session is already authenticated.
FormCredential form_cred = (FormCredential) session.getAttribute(__J_AUTHENTICATED);
if (form_cred != null)
SessionAuthentication sessionAuth = (SessionAuthentication)session.getAttribute(SessionAuthentication.__J_AUTHENTICATED);
if (sessionAuth != null)
{
//TODO: ideally we would like the form auth module to be able to invoke the
//loginservice.validate() method to check the previously authed user, but it is not visible
//to FormAuthModule
if (form_cred._subject == null)
if (sessionAuth.getUserIdentity().getSubject() == null)
return AuthStatus.SEND_FAILURE;
Set<Object> credentials = form_cred._subject.getPrivateCredentials();
Set<Object> credentials = sessionAuth.getUserIdentity().getSubject().getPrivateCredentials();
if (credentials == null || credentials.isEmpty())
return AuthStatus.SEND_FAILURE; //if no private credentials, assume it cannot be authenticated
clientSubject.getPrivateCredentials().addAll(credentials);
clientSubject.getPrivateCredentials().add(sessionAuth.getUserIdentity());
//boolean success = tryLogin(messageInfo, clientSubject, response, session, form_cred._jUserName, new Password(new String(form_cred._jPassword)));
return AuthStatus.SUCCESS;
}
else if (ssoSource != null)
@ -300,8 +304,14 @@ public class FormAuthModule extends BaseAuthModule
if (!loginCallbacks.isEmpty())
{
LoginCallbackImpl loginCallback = loginCallbacks.iterator().next();
FormCredential form_cred = new FormCredential(username, pwdChars, loginCallback.getUserPrincipal(), loginCallback.getSubject());
session.setAttribute(__J_AUTHENTICATED, form_cred);
Set<UserIdentity> userIdentities = clientSubject.getPrivateCredentials(UserIdentity.class);
if (!userIdentities.isEmpty())
{
UserIdentity userIdentity = userIdentities.iterator().next();
SessionAuthentication sessionAuth = new SessionAuthentication(Constraint.__FORM_AUTH, userIdentity, password);
session.setAttribute(SessionAuthentication.__J_AUTHENTICATED, sessionAuth);
}
}
// Sign-on to SSO mechanism
@ -320,61 +330,4 @@ public class FormAuthModule extends BaseAuthModule
return pathInContext != null && (pathInContext.equals(_formErrorPath) || pathInContext.equals(_formLoginPath));
}
/* ------------------------------------------------------------ */
/**
* FORM Authentication credential holder.
*/
private static class FormCredential implements Serializable, HttpSessionBindingListener
{
String _jUserName;
char[] _jPassword;
transient Principal _userPrincipal;
transient Subject _subject;
private FormCredential(String _jUserName, char[] _jPassword, Principal _userPrincipal, Subject subject)
{
this._jUserName = _jUserName;
this._jPassword = _jPassword;
this._userPrincipal = _userPrincipal;
this._subject = subject;
}
public void valueBound(HttpSessionBindingEvent event)
{
}
public void valueUnbound(HttpSessionBindingEvent event)
{
if (LOG.isDebugEnabled()) LOG.debug("Logout " + _jUserName);
// TODO jaspi call cleanSubject()
// if (_realm instanceof SSORealm)
// ((SSORealm) _realm).clearSingleSignOn(_jUserName);
//
// if (_realm != null && _userPrincipal != null)
// _realm.logout(_userPrincipal);
}
public int hashCode()
{
return _jUserName.hashCode() + _jPassword.hashCode();
}
public boolean equals(Object o)
{
if (!(o instanceof FormCredential)) return false;
FormCredential fc = (FormCredential) o;
return _jUserName.equals(fc._jUserName) && Arrays.equals(_jPassword, fc._jPassword);
}
public String toString()
{
return "Cred[" + _jUserName + "]";
}
}
}

View File

@ -54,6 +54,8 @@ public class BasicAuthenticator extends LoginAuthenticator
return Constraint.__BASIC_AUTH;
}
/* ------------------------------------------------------------ */
/**
* @see org.eclipse.jetty.security.Authenticator#validateRequest(javax.servlet.ServletRequest, javax.servlet.ServletResponse, boolean)
@ -85,10 +87,9 @@ public class BasicAuthenticator extends LoginAuthenticator
String username = credentials.substring(0,i);
String password = credentials.substring(i+1);
UserIdentity user = _loginService.login(username,password);
UserIdentity user = login (username, password, request);
if (user!=null)
{
renewSession(request,response);
return new UserAuthentication(getAuthMethod(),user);
}
}

View File

@ -81,6 +81,8 @@ public class ClientCertAuthenticator extends LoginAuthenticator
return Constraint.__CERT_AUTH;
}
/**
* @return Authentication for request
* @throws ServerAuthException
@ -121,10 +123,9 @@ public class ClientCertAuthenticator extends LoginAuthenticator
final char[] credential = B64Code.encode(cert.getSignature());
UserIdentity user = _loginService.login(username,credential);
UserIdentity user = login(username, credential, req);
if (user!=null)
{
renewSession(request,response);
return new UserAuthentication(getAuthMethod(),user);
}
}

View File

@ -29,6 +29,7 @@ import javax.servlet.ServletOutputStream;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.security.Authenticator;
@ -73,6 +74,7 @@ public class DeferredAuthentication implements Authentication.Deferred
if (identity_service!=null)
_previousAssociation=identity_service.associate(((Authentication.User)authentication).getUserIdentity());
return authentication;
}
}
@ -80,6 +82,7 @@ public class DeferredAuthentication implements Authentication.Deferred
{
LOG.debug(e);
}
return this;
}
@ -110,21 +113,16 @@ public class DeferredAuthentication implements Authentication.Deferred
/**
* @see org.eclipse.jetty.server.Authentication.Deferred#login(java.lang.String, java.lang.String)
*/
public Authentication login(String username, String password)
public Authentication login(String username, Object password, ServletRequest request)
{
LoginService login_service= _authenticator.getLoginService();
IdentityService identity_service=login_service.getIdentityService();
if (login_service!=null)
UserIdentity identity = _authenticator.login(username, password, request);
if (identity != null)
{
UserIdentity user = login_service.login(username,password);
if (user!=null)
{
UserAuthentication authentication = new UserAuthentication("API",user);
if (identity_service!=null)
_previousAssociation=identity_service.associate(user);
return authentication;
}
IdentityService identity_service = _authenticator.getLoginService().getIdentityService();
UserAuthentication authentication = new UserAuthentication("API",identity);
if (identity_service != null)
_previousAssociation=identity_service.associate(identity);
return authentication;
}
return null;
}

View File

@ -116,6 +116,8 @@ public class DigestAuthenticator extends LoginAuthenticator
{
return true;
}
/* ------------------------------------------------------------ */
public Authentication validateRequest(ServletRequest req, ServletResponse res, boolean mandatory) throws ServerAuthException
@ -185,10 +187,10 @@ public class DigestAuthenticator extends LoginAuthenticator
if (n > 0)
{
UserIdentity user = _loginService.login(digest.username,digest);
//UserIdentity user = _loginService.login(digest.username,digest);
UserIdentity user = login(digest.username, digest, req);
if (user!=null)
{
renewSession(request,response);
return new UserAuthentication(getAuthMethod(),user);
}
}

View File

@ -179,6 +179,22 @@ public class FormAuthenticator extends LoginAuthenticator
_formErrorPath = _formErrorPath.substring(0, _formErrorPath.indexOf('?'));
}
}
/* ------------------------------------------------------------ */
@Override
public UserIdentity login(String username, Object password, ServletRequest request)
{
UserIdentity user = super.login(username,password,request);
if (user!=null)
{
HttpSession session = ((HttpServletRequest)request).getSession(true);
Authentication cached=new SessionAuthentication(getAuthMethod(),user,password);
session.setAttribute(SessionAuthentication.__J_AUTHENTICATED, cached);
}
return user;
}
/* ------------------------------------------------------------ */
public Authentication validateRequest(ServletRequest req, ServletResponse res, boolean mandatory) throws ServerAuthException
@ -206,11 +222,10 @@ public class FormAuthenticator extends LoginAuthenticator
final String username = request.getParameter(__J_USERNAME);
final String password = request.getParameter(__J_PASSWORD);
UserIdentity user = _loginService.login(username,password);
UserIdentity user = login(username, password, request);
session = request.getSession(true);
if (user!=null)
{
session=renewSession(request,response);
{
// Redirect to original request
String nuri;
synchronized(session)
@ -223,9 +238,6 @@ public class FormAuthenticator extends LoginAuthenticator
if (nuri.length() == 0)
nuri = URIUtil.SLASH;
}
Authentication cached=new SessionAuthentication(getAuthMethod(),user,password);
session.setAttribute(SessionAuthentication.__J_AUTHENTICATED, cached);
}
response.setContentLength(0);
response.sendRedirect(response.encodeRedirectURL(nuri));

View File

@ -18,6 +18,7 @@
package org.eclipse.jetty.security.authentication;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
@ -25,6 +26,8 @@ import javax.servlet.http.HttpSession;
import org.eclipse.jetty.security.Authenticator;
import org.eclipse.jetty.security.IdentityService;
import org.eclipse.jetty.security.LoginService;
import org.eclipse.jetty.server.Authentication;
import org.eclipse.jetty.server.UserIdentity;
import org.eclipse.jetty.server.session.AbstractSessionManager;
public abstract class LoginAuthenticator implements Authenticator
@ -37,6 +40,20 @@ public abstract class LoginAuthenticator implements Authenticator
{
}
/* ------------------------------------------------------------ */
public UserIdentity login(String username, Object password, ServletRequest request)
{
UserIdentity user = _loginService.login(username,password);
if (user!=null)
{
renewSession((HttpServletRequest)request, null);
return user;
}
return null;
}
public void setConfiguration(AuthConfiguration configuration)
{
_loginService=configuration.getLoginService();

View File

@ -98,8 +98,8 @@ public class SessionAuthentication implements Authentication.User, Serializable,
{
if (_session!=null && _session.getAttribute(__J_AUTHENTICATED)!=null)
_session.removeAttribute(__J_AUTHENTICATED);
else
doLogout();
doLogout();
}
private void doLogout()

View File

@ -60,6 +60,8 @@ public class SpnegoAuthenticator extends LoginAuthenticator
return _authMethod;
}
public Authentication validateRequest(ServletRequest request, ServletResponse response, boolean mandatory) throws ServerAuthException
{
HttpServletRequest req = (HttpServletRequest)request;
@ -96,7 +98,7 @@ public class SpnegoAuthenticator extends LoginAuthenticator
{
String spnegoToken = header.substring(10);
UserIdentity user = _loginService.login(null,spnegoToken);
UserIdentity user = login(null,spnegoToken, request);
if ( user != null )
{

View File

@ -85,7 +85,7 @@ public interface Authentication
* @param password
* @return The new Authentication state
*/
Authentication login(String username,String password);
Authentication login(String username,Object password,ServletRequest request);
}

View File

@ -1312,6 +1312,7 @@ public class Request implements HttpServletRequest
UserIdentity user = ((Authentication.User)_authentication).getUserIdentity();
return user.getUserPrincipal();
}
return null;
}
@ -1980,7 +1981,7 @@ public class Request implements HttpServletRequest
{
if (_authentication instanceof Authentication.Deferred)
{
setAuthentication(((Authentication.Deferred)_authentication).authenticate(this,response));
setAuthentication(((Authentication.Deferred)_authentication).authenticate(this,response));
return !(_authentication instanceof Authentication.ResponseSent);
}
response.sendError(HttpStatus.UNAUTHORIZED_401);
@ -2069,7 +2070,7 @@ public class Request implements HttpServletRequest
{
if (_authentication instanceof Authentication.Deferred)
{
_authentication=((Authentication.Deferred)_authentication).login(username,password);
_authentication=((Authentication.Deferred)_authentication).login(username,password,this);
if (_authentication == null)
throw new ServletException();
}

View File

@ -0,0 +1,87 @@
// ========================================================================
// Copyright (c) 1996-2009 Mort Bay Consulting Pty. Ltd.
// ------------------------------------------------------------------------
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
package com.acme;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Calendar;
import java.util.GregorianCalendar;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.Logger;
/* ------------------------------------------------------------ */
/** Dump Servlet Request.
*
*/
public class LoginServlet extends HttpServlet
{
private static final Logger LOG = Log.getLogger(SecureModeServlet.class);
/* ------------------------------------------------------------ */
@Override
public void init(ServletConfig config) throws ServletException
{
super.init(config);
}
/* ------------------------------------------------------------ */
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
doGet(request, response);
}
/* ------------------------------------------------------------ */
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
response.setContentType("text/html");
ServletOutputStream out = response.getOutputStream();
out.println("<html>");
out.println("<br/>Before getUserPrincipal="+request.getUserPrincipal());
out.println("<br/>Before getRemoteUser="+request.getRemoteUser());
String param = request.getParameter("action");
if ("login".equals(param))
{
request.login("jetty", "jetty");
}
else if ("logout".equals(param))
{
request.logout();
}
else if ("wrong".equals(param))
{
request.login("jetty", "123");
}
out.println("<br/>After getUserPrincipal="+request.getUserPrincipal());
out.println("<br/>After getRemoteUser="+request.getRemoteUser());
out.println("</html>");
out.flush();
}
}

View File

@ -105,6 +105,17 @@
<dispatcher>REQUEST</dispatcher>
</filter-mapping>
-->
<servlet>
<servlet-name>Login</servlet-name>
<servlet-class>com.acme.LoginServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Login</servlet-name>
<url-pattern>/login/*</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>Hello</servlet-name>

View File

@ -20,6 +20,10 @@ This page contains several links to test the authentication constraints:
<li><a href="dump/auth/ssl/info">dump/auth/ssl/*</a> - Confidential</li>
<li><a href="rego/info">rego/info/*</a> - Authenticated admin role from programmatic security (<a href="session/?Action=Invalidate">click</a> to invalidate session)</li>
<li><a href="rego2/info">rego2/info/*</a> - Authenticated servlet-administrator role from programmatic security (login as admin/admin, <a href="session/?Action=Invalidate">click</a> to invalidate session)</li>
<li><a href="login?action=login">login</a> - Programmatically login as the user jetty/jetty</li>
<li><a href="login?action=x">check login status</a> - Check the request's login status</li>
<li><a href="login?action=logout">logout</a> - Programmatically logout the logged in user</li>
<li><a href="login?action=wrong">incorrect login</a> - Programmatically login with incorrect credentials</li>
</ul>
<p/>
<p>