diff options
author | Jan Bartel | 2012-10-29 07:21:37 +0000 |
---|---|---|
committer | Jan Bartel | 2012-10-29 07:21:37 +0000 |
commit | a74c9f176cdd66cf61e6a2be85fe05cb608e84f1 (patch) | |
tree | c71904475395f0688973fa79d7cd95e70faa4687 /jetty-plus/src/main/java/org/eclipse/jetty | |
parent | 3ae56b8450184cfe99d9c66358bafdca2cc38d63 (diff) | |
download | org.eclipse.jetty.project-a74c9f176cdd66cf61e6a2be85fe05cb608e84f1.tar.gz org.eclipse.jetty.project-a74c9f176cdd66cf61e6a2be85fe05cb608e84f1.tar.xz org.eclipse.jetty.project-a74c9f176cdd66cf61e6a2be85fe05cb608e84f1.zip |
392237 Split jaas from jetty-plus into jetty-jaas and port the test-jaas-webapp from codehaus
Diffstat (limited to 'jetty-plus/src/main/java/org/eclipse/jetty')
18 files changed, 0 insertions, 2610 deletions
diff --git a/jetty-plus/src/main/java/org/eclipse/jetty/plus/jaas/JAASGroup.java b/jetty-plus/src/main/java/org/eclipse/jetty/plus/jaas/JAASGroup.java deleted file mode 100644 index 51fc5379db..0000000000 --- a/jetty-plus/src/main/java/org/eclipse/jetty/plus/jaas/JAASGroup.java +++ /dev/null @@ -1,152 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995-2012 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 org.eclipse.jetty.plus.jaas; - -import java.security.Principal; -import java.security.acl.Group; -import java.util.Enumeration; -import java.util.HashSet; -import java.util.Iterator; - - -public class JAASGroup implements Group -{ - public static final String ROLES = "__roles__"; - - private String _name = null; - private HashSet<Principal> _members = null; - - - - public JAASGroup(String n) - { - this._name = n; - this._members = new HashSet<Principal>(); - } - - /* ------------------------------------------------------------ */ - /** - * - * @param principal <description> - * @return <description> - */ - public synchronized boolean addMember(Principal principal) - { - return _members.add(principal); - } - - /** - * - * @param principal <description> - * @return <description> - */ - public synchronized boolean removeMember(Principal principal) - { - return _members.remove(principal); - } - - /** - * - * @param principal <description> - * @return <description> - */ - public boolean isMember(Principal principal) - { - return _members.contains(principal); - } - - - - /** - * - * @return <description> - */ - public Enumeration<? extends Principal> members() - { - - class MembersEnumeration implements Enumeration<Principal> - { - private Iterator<? extends Principal> itor; - - public MembersEnumeration (Iterator<? extends Principal> itor) - { - this.itor = itor; - } - - public boolean hasMoreElements () - { - return this.itor.hasNext(); - } - - - public Principal nextElement () - { - return this.itor.next(); - } - - } - - return new MembersEnumeration (_members.iterator()); - } - - - /** - * - * @return <description> - */ - public int hashCode() - { - return getName().hashCode(); - } - - - - /** - * - * @param object <description> - * @return <description> - */ - public boolean equals(Object object) - { - if (! (object instanceof JAASGroup)) - return false; - - return ((JAASGroup)object).getName().equals(getName()); - } - - /** - * - * @return <description> - */ - public String toString() - { - return getName(); - } - - /** - * - * @return <description> - */ - public String getName() - { - - return _name; - } - -} diff --git a/jetty-plus/src/main/java/org/eclipse/jetty/plus/jaas/JAASLoginService.java b/jetty-plus/src/main/java/org/eclipse/jetty/plus/jaas/JAASLoginService.java deleted file mode 100644 index b9d66da7a5..0000000000 --- a/jetty-plus/src/main/java/org/eclipse/jetty/plus/jaas/JAASLoginService.java +++ /dev/null @@ -1,333 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995-2012 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 org.eclipse.jetty.plus.jaas; - -import java.io.IOException; -import java.security.Principal; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.LinkedHashSet; -import java.util.Set; -import javax.security.auth.Subject; -import javax.security.auth.callback.Callback; -import javax.security.auth.callback.CallbackHandler; -import javax.security.auth.callback.NameCallback; -import javax.security.auth.callback.PasswordCallback; -import javax.security.auth.callback.UnsupportedCallbackException; -import javax.security.auth.login.LoginContext; -import javax.security.auth.login.LoginException; - -import org.eclipse.jetty.plus.jaas.callback.ObjectCallback; -import org.eclipse.jetty.plus.jaas.callback.RequestParameterCallback; -import org.eclipse.jetty.security.DefaultIdentityService; -import org.eclipse.jetty.security.IdentityService; -import org.eclipse.jetty.security.LoginService; -import org.eclipse.jetty.server.HttpChannel; -import org.eclipse.jetty.server.Request; -import org.eclipse.jetty.server.UserIdentity; -import org.eclipse.jetty.util.Loader; -import org.eclipse.jetty.util.component.AbstractLifeCycle; -import org.eclipse.jetty.util.log.Log; -import org.eclipse.jetty.util.log.Logger; - -/* ---------------------------------------------------- */ -/** JAASLoginService - * - * @org.apache.xbean.XBean element="jaasUserRealm" description="Creates a UserRealm suitable for use with JAAS" - */ -public class JAASLoginService extends AbstractLifeCycle implements LoginService -{ - private static final Logger LOG = Log.getLogger(JAASLoginService.class); - - public static String DEFAULT_ROLE_CLASS_NAME = "org.eclipse.jetty.plus.jaas.JAASRole"; - public static String[] DEFAULT_ROLE_CLASS_NAMES = {DEFAULT_ROLE_CLASS_NAME}; - - protected String[] _roleClassNames = DEFAULT_ROLE_CLASS_NAMES; - protected String _callbackHandlerClass; - protected String _realmName; - protected String _loginModuleName; - protected JAASUserPrincipal _defaultUser = new JAASUserPrincipal(null, null, null); - protected IdentityService _identityService; - - /* ---------------------------------------------------- */ - /** - * Constructor. - * - */ - public JAASLoginService() - { - } - - - /* ---------------------------------------------------- */ - /** - * Constructor. - * - * @param name the name of the realm - */ - public JAASLoginService(String name) - { - this(); - _realmName = name; - _loginModuleName = name; - } - - - /* ---------------------------------------------------- */ - /** - * Get the name of the realm. - * - * @return name or null if not set. - */ - public String getName() - { - return _realmName; - } - - - /* ---------------------------------------------------- */ - /** - * Set the name of the realm - * - * @param name a <code>String</code> value - */ - public void setName (String name) - { - _realmName = name; - } - - /* ------------------------------------------------------------ */ - /** Get the identityService. - * @return the identityService - */ - public IdentityService getIdentityService() - { - return _identityService; - } - - /* ------------------------------------------------------------ */ - /** Set the identityService. - * @param identityService the identityService to set - */ - public void setIdentityService(IdentityService identityService) - { - _identityService = identityService; - } - - /* ------------------------------------------------------------ */ - /** - * Set the name to use to index into the config - * file of LoginModules. - * - * @param name a <code>String</code> value - */ - public void setLoginModuleName (String name) - { - _loginModuleName = name; - } - - /* ------------------------------------------------------------ */ - public void setCallbackHandlerClass (String classname) - { - _callbackHandlerClass = classname; - } - - /* ------------------------------------------------------------ */ - public void setRoleClassNames (String[] classnames) - { - ArrayList<String> tmp = new ArrayList<String>(); - - if (classnames != null) - tmp.addAll(Arrays.asList(classnames)); - - if (!tmp.contains(DEFAULT_ROLE_CLASS_NAME)) - tmp.add(DEFAULT_ROLE_CLASS_NAME); - _roleClassNames = tmp.toArray(new String[tmp.size()]); - } - - /* ------------------------------------------------------------ */ - public String[] getRoleClassNames() - { - return _roleClassNames; - } - - /* ------------------------------------------------------------ */ - /** - * @see org.eclipse.jetty.util.component.AbstractLifeCycle#doStart() - */ - protected void doStart() throws Exception - { - if (_identityService==null) - _identityService=new DefaultIdentityService(); - super.doStart(); - } - - /* ------------------------------------------------------------ */ - public UserIdentity login(final String username,final Object credentials) - { - try - { - CallbackHandler callbackHandler = null; - - - if (_callbackHandlerClass == null) - { - callbackHandler = new CallbackHandler() - { - public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException - { - for (Callback callback: callbacks) - { - if (callback instanceof NameCallback) - { - ((NameCallback)callback).setName(username); - } - else if (callback instanceof PasswordCallback) - { - ((PasswordCallback)callback).setPassword((char[]) credentials.toString().toCharArray()); - } - else if (callback instanceof ObjectCallback) - { - ((ObjectCallback)callback).setObject(credentials); - } - else if (callback instanceof RequestParameterCallback) - { - HttpChannel channel = HttpChannel.getCurrentHttpChannel(); - - if (channel == null) - return; - Request request = channel.getRequest(); - - if (request != null) - { - RequestParameterCallback rpc = (RequestParameterCallback)callback; - rpc.setParameterValues(Arrays.asList(request.getParameterValues(rpc.getParameterName()))); - } - } - else - throw new UnsupportedCallbackException(callback); - } - } - }; - } - else - { - Class clazz = Loader.loadClass(getClass(), _callbackHandlerClass); - callbackHandler = (CallbackHandler)clazz.newInstance(); - } - //set up the login context - //TODO jaspi requires we provide the Configuration parameter - Subject subject = new Subject(); - LoginContext loginContext = new LoginContext(_loginModuleName, subject, callbackHandler); - - loginContext.login(); - - //login success - JAASUserPrincipal userPrincipal = new JAASUserPrincipal(getUserName(callbackHandler), subject, loginContext); - subject.getPrincipals().add(userPrincipal); - - return _identityService.newUserIdentity(subject,userPrincipal,getGroups(subject)); - } - catch (LoginException e) - { - LOG.warn(e); - } - catch (IOException e) - { - LOG.warn(e); - } - catch (UnsupportedCallbackException e) - { - LOG.warn(e); - } - catch (InstantiationException e) - { - LOG.warn(e); - } - catch (IllegalAccessException e) - { - LOG.warn(e); - } - catch (ClassNotFoundException e) - { - LOG.warn(e); - } - return null; - } - - /* ------------------------------------------------------------ */ - public boolean validate(UserIdentity user) - { - // TODO optionally check user is still valid - return true; - } - - /* ------------------------------------------------------------ */ - private String getUserName(CallbackHandler callbackHandler) throws IOException, UnsupportedCallbackException - { - NameCallback nameCallback = new NameCallback("foo"); - callbackHandler.handle(new Callback[] {nameCallback}); - return nameCallback.getName(); - } - - /* ------------------------------------------------------------ */ - public void logout(UserIdentity user) - { - Set<JAASUserPrincipal> userPrincipals = user.getSubject().getPrincipals(JAASUserPrincipal.class); - LoginContext loginContext = userPrincipals.iterator().next().getLoginContext(); - try - { - loginContext.logout(); - } - catch (LoginException e) - { - LOG.warn(e); - } - } - - - /* ------------------------------------------------------------ */ - @SuppressWarnings({ "unchecked", "rawtypes" }) - private String[] getGroups (Subject subject) - { - //get all the roles of the various types - String[] roleClassNames = getRoleClassNames(); - Collection<String> groups = new LinkedHashSet<String>(); - try - { - for (String roleClassName : roleClassNames) - { - Class load_class = Thread.currentThread().getContextClassLoader().loadClass(roleClassName); - Set<Principal> rolesForType = subject.getPrincipals(load_class); - for (Principal principal : rolesForType) - { - groups.add(principal.getName()); - } - } - - return groups.toArray(new String[groups.size()]); - } - catch (ClassNotFoundException e) - { - throw new RuntimeException(e); - } - } - -} diff --git a/jetty-plus/src/main/java/org/eclipse/jetty/plus/jaas/JAASPrincipal.java b/jetty-plus/src/main/java/org/eclipse/jetty/plus/jaas/JAASPrincipal.java deleted file mode 100644 index b66f60033b..0000000000 --- a/jetty-plus/src/main/java/org/eclipse/jetty/plus/jaas/JAASPrincipal.java +++ /dev/null @@ -1,89 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995-2012 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 org.eclipse.jetty.plus.jaas; - -import java.io.Serializable; -import java.security.Principal; - - - -/* ---------------------------------------------------- */ -/** JAASPrincipal - * <p>Impl class of Principal interface. - * - * <p><h4>Notes</h4> - * <p> - * - * <p><h4>Usage</h4> - * <pre> - */ -/* - * </pre> - * - * @see - * @version 1.0 Tue Apr 15 2003 - * - */ -public class JAASPrincipal implements Principal, Serializable -{ - /** - * - */ - private static final long serialVersionUID = -5538962177019315479L; - - private String _name = null; - - - public JAASPrincipal(String userName) - { - this._name = userName; - } - - - public boolean equals (Object p) - { - if (! (p instanceof JAASPrincipal)) - return false; - - return getName().equals(((JAASPrincipal)p).getName()); - } - - - public int hashCode () - { - return getName().hashCode(); - } - - - public String getName () - { - return this._name; - } - - - public String toString () - { - return getName(); - } - - - -} - - diff --git a/jetty-plus/src/main/java/org/eclipse/jetty/plus/jaas/JAASRole.java b/jetty-plus/src/main/java/org/eclipse/jetty/plus/jaas/JAASRole.java deleted file mode 100644 index b6375ca935..0000000000 --- a/jetty-plus/src/main/java/org/eclipse/jetty/plus/jaas/JAASRole.java +++ /dev/null @@ -1,42 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995-2012 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 org.eclipse.jetty.plus.jaas; - - -public class JAASRole extends JAASPrincipal -{ - - /** - * - */ - private static final long serialVersionUID = 3465114254970134526L; - - public JAASRole(String name) - { - super (name); - } - - public boolean equals (Object o) - { - if (! (o instanceof JAASRole)) - return false; - - return getName().equals(((JAASRole)o).getName()); - } -} diff --git a/jetty-plus/src/main/java/org/eclipse/jetty/plus/jaas/JAASUserPrincipal.java b/jetty-plus/src/main/java/org/eclipse/jetty/plus/jaas/JAASUserPrincipal.java deleted file mode 100644 index e8415d0dad..0000000000 --- a/jetty-plus/src/main/java/org/eclipse/jetty/plus/jaas/JAASUserPrincipal.java +++ /dev/null @@ -1,78 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995-2012 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 org.eclipse.jetty.plus.jaas; - -import java.security.Principal; -import javax.security.auth.Subject; -import javax.security.auth.login.LoginContext; - - - -/* ---------------------------------------------------- */ -/** JAASUserPrincipal - * <p>Implements the JAAS version of the - * org.eclipse.jetty.http.UserPrincipal interface. - * - * @version $Id: JAASUserPrincipal.java 4780 2009-03-17 15:36:08Z jesse $ - * - */ -public class JAASUserPrincipal implements Principal -{ - private final String _name; - private final Subject _subject; - private final LoginContext _loginContext; - - /* ------------------------------------------------ */ - - public JAASUserPrincipal(String name, Subject subject, LoginContext loginContext) - { - this._name = name; - this._subject = subject; - this._loginContext = loginContext; - } - - /* ------------------------------------------------ */ - /** Get the name identifying the user - */ - public String getName () - { - return _name; - } - - - /* ------------------------------------------------ */ - /** Provide access to the Subject - * @return subject - */ - public Subject getSubject () - { - return this._subject; - } - - LoginContext getLoginContext () - { - return this._loginContext; - } - - public String toString() - { - return getName(); - } - -} diff --git a/jetty-plus/src/main/java/org/eclipse/jetty/plus/jaas/RoleCheckPolicy.java b/jetty-plus/src/main/java/org/eclipse/jetty/plus/jaas/RoleCheckPolicy.java deleted file mode 100644 index 105efb9a6d..0000000000 --- a/jetty-plus/src/main/java/org/eclipse/jetty/plus/jaas/RoleCheckPolicy.java +++ /dev/null @@ -1,36 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995-2012 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 org.eclipse.jetty.plus.jaas; - -import java.security.Principal; -import java.security.acl.Group; - - -public interface RoleCheckPolicy -{ - /* ------------------------------------------------ */ - /** Check if a role is either a runAsRole or in a set of roles - * @param roleName the role to check - * @param runAsRole a pushed role (can be null) - * @param roles a Group whose Principals are role names - * @return <code>true</code> if <code>role</code> equals <code>runAsRole</code> or is a member of <code>roles</code>. - */ - public boolean checkRole (String roleName, Principal runAsRole, Group roles); - -} diff --git a/jetty-plus/src/main/java/org/eclipse/jetty/plus/jaas/StrictRoleCheckPolicy.java b/jetty-plus/src/main/java/org/eclipse/jetty/plus/jaas/StrictRoleCheckPolicy.java deleted file mode 100644 index e279fd713e..0000000000 --- a/jetty-plus/src/main/java/org/eclipse/jetty/plus/jaas/StrictRoleCheckPolicy.java +++ /dev/null @@ -1,63 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995-2012 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 org.eclipse.jetty.plus.jaas; - -import java.security.Principal; -import java.security.acl.Group; -import java.util.Enumeration; - - -/* ---------------------------------------------------- */ -/** StrictRoleCheckPolicy - * <p>Enforces that if a runAsRole is present, then the - * role to check must be the same as that runAsRole and - * the set of static roles is ignored. - * - * - * - * @org.apache.xbean.XBean description ="Check only topmost role in stack of roles for user" - */ -public class StrictRoleCheckPolicy implements RoleCheckPolicy -{ - - public boolean checkRole (String roleName, Principal runAsRole, Group roles) - { - //check if this user has had any temporary role pushed onto - //them. If so, then only check if the user has that role. - if (runAsRole != null) - { - return (roleName.equals(runAsRole.getName())); - } - else - { - if (roles == null) - return false; - Enumeration<? extends Principal> rolesEnum = roles.members(); - boolean found = false; - while (rolesEnum.hasMoreElements() && !found) - { - Principal p = (Principal)rolesEnum.nextElement(); - found = roleName.equals(p.getName()); - } - return found; - } - - } - -} diff --git a/jetty-plus/src/main/java/org/eclipse/jetty/plus/jaas/callback/AbstractCallbackHandler.java b/jetty-plus/src/main/java/org/eclipse/jetty/plus/jaas/callback/AbstractCallbackHandler.java deleted file mode 100644 index 89c74cca25..0000000000 --- a/jetty-plus/src/main/java/org/eclipse/jetty/plus/jaas/callback/AbstractCallbackHandler.java +++ /dev/null @@ -1,59 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995-2012 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 org.eclipse.jetty.plus.jaas.callback; - -import java.io.IOException; -import javax.security.auth.callback.Callback; -import javax.security.auth.callback.CallbackHandler; -import javax.security.auth.callback.UnsupportedCallbackException; - - -public abstract class AbstractCallbackHandler implements CallbackHandler -{ - protected String _userName; - protected Object _credential; - - public void setUserName (String userName) - { - _userName = userName; - } - - public String getUserName () - { - return _userName; - } - - - public void setCredential (Object credential) - { - _credential = credential; - } - - public Object getCredential () - { - return _credential; - } - - public void handle (Callback[] callbacks) - throws IOException, UnsupportedCallbackException - { - } - - -} diff --git a/jetty-plus/src/main/java/org/eclipse/jetty/plus/jaas/callback/DefaultCallbackHandler.java b/jetty-plus/src/main/java/org/eclipse/jetty/plus/jaas/callback/DefaultCallbackHandler.java deleted file mode 100644 index c523efc225..0000000000 --- a/jetty-plus/src/main/java/org/eclipse/jetty/plus/jaas/callback/DefaultCallbackHandler.java +++ /dev/null @@ -1,96 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995-2012 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 org.eclipse.jetty.plus.jaas.callback; - -import java.io.IOException; -import java.util.Arrays; -import javax.security.auth.callback.Callback; -import javax.security.auth.callback.NameCallback; -import javax.security.auth.callback.PasswordCallback; -import javax.security.auth.callback.UnsupportedCallbackException; - -import org.eclipse.jetty.server.Request; -import org.eclipse.jetty.util.security.Password; - - - -/* ---------------------------------------------------- */ -/** DefaultUsernameCredentialCallbackHandler - * <p> - * - * <p><h4>Notes</h4> - * <p> - * - * <p><h4>Usage</h4> - * <pre> - */ -/* - * </pre> - * - * @see - * @version 1.0 Tue Apr 15 2003 - * - */ -public class DefaultCallbackHandler extends AbstractCallbackHandler -{ - - private Request _request; - - public void setRequest (Request request) - { - this._request = request; - } - - public void handle (Callback[] callbacks) - throws IOException, UnsupportedCallbackException - { - for (int i=0; i < callbacks.length; i++) - { - if (callbacks[i] instanceof NameCallback) - { - ((NameCallback)callbacks[i]).setName(getUserName()); - } - else if (callbacks[i] instanceof ObjectCallback) - { - ((ObjectCallback)callbacks[i]).setObject(getCredential()); - } - else if (callbacks[i] instanceof PasswordCallback) - { - if (getCredential() instanceof Password) - ((PasswordCallback)callbacks[i]).setPassword (((Password)getCredential()).toString().toCharArray()); - else if (getCredential() instanceof String) - { - ((PasswordCallback)callbacks[i]).setPassword (((String)getCredential()).toCharArray()); - } - else - throw new UnsupportedCallbackException (callbacks[i], "User supplied credentials cannot be converted to char[] for PasswordCallback: try using an ObjectCallback instead"); - } - else if (callbacks[i] instanceof RequestParameterCallback) - { - RequestParameterCallback callback = (RequestParameterCallback)callbacks[i]; - callback.setParameterValues(Arrays.asList(_request.getParameterValues(callback.getParameterName()))); - } - else - throw new UnsupportedCallbackException(callbacks[i]); - } - - } - -} - diff --git a/jetty-plus/src/main/java/org/eclipse/jetty/plus/jaas/callback/ObjectCallback.java b/jetty-plus/src/main/java/org/eclipse/jetty/plus/jaas/callback/ObjectCallback.java deleted file mode 100644 index 41bf4eafc7..0000000000 --- a/jetty-plus/src/main/java/org/eclipse/jetty/plus/jaas/callback/ObjectCallback.java +++ /dev/null @@ -1,67 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995-2012 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 org.eclipse.jetty.plus.jaas.callback; - -import javax.security.auth.callback.Callback; - - -/* ---------------------------------------------------- */ -/** ObjectCallback - * - * <p>Can be used as a LoginModule Callback to - * obtain a user's credential as an Object, rather than - * a char[], to which some credentials may not be able - * to be converted - * - * <p><h4>Notes</h4> - * <p> - * - * <p><h4>Usage</h4> - * <pre> - */ -/* - * </pre> - * - * @see - * @version 1.0 Tue Apr 15 2003 - * - */ -public class ObjectCallback implements Callback -{ - - protected Object _object; - - public void setObject(Object o) - { - _object = o; - } - - public Object getObject () - { - return _object; - } - - - public void clearObject () - { - _object = null; - } - - -} diff --git a/jetty-plus/src/main/java/org/eclipse/jetty/plus/jaas/callback/RequestParameterCallback.java b/jetty-plus/src/main/java/org/eclipse/jetty/plus/jaas/callback/RequestParameterCallback.java deleted file mode 100644 index c56b09af34..0000000000 --- a/jetty-plus/src/main/java/org/eclipse/jetty/plus/jaas/callback/RequestParameterCallback.java +++ /dev/null @@ -1,60 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995-2012 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 org.eclipse.jetty.plus.jaas.callback; - -import java.util.List; -import javax.security.auth.callback.Callback; - - -/** - * - * RequestParameterCallback - * - * Allows a JAAS callback handler to access any parameter from the j_security_check FORM. - * This means that a LoginModule can access form fields other than the j_username and j_password - * fields, and use it, for example, to authenticate a user. - * - * - * @version $Revision: 4780 $ $Date: 2009-03-17 16:36:08 +0100 (Tue, 17 Mar 2009) $ - * - */ -public class RequestParameterCallback implements Callback -{ - private String _paramName; - private List<?> _paramValues; - - public void setParameterName (String name) - { - _paramName = name; - } - public String getParameterName () - { - return _paramName; - } - - public void setParameterValues (List<?> values) - { - _paramValues = values; - } - - public List<?> getParameterValues () - { - return _paramValues; - } -} diff --git a/jetty-plus/src/main/java/org/eclipse/jetty/plus/jaas/spi/AbstractDatabaseLoginModule.java b/jetty-plus/src/main/java/org/eclipse/jetty/plus/jaas/spi/AbstractDatabaseLoginModule.java deleted file mode 100644 index 7535dd23d5..0000000000 --- a/jetty-plus/src/main/java/org/eclipse/jetty/plus/jaas/spi/AbstractDatabaseLoginModule.java +++ /dev/null @@ -1,143 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995-2012 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 org.eclipse.jetty.plus.jaas.spi; - -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import javax.security.auth.Subject; -import javax.security.auth.callback.CallbackHandler; - -import org.eclipse.jetty.util.log.Log; -import org.eclipse.jetty.util.log.Logger; -import org.eclipse.jetty.util.security.Credential; - -/** - * AbstractDatabaseLoginModule - * - * Abstract base class for LoginModules that interact with a - * database to retrieve authentication and authorization information. - * Used by the JDBCLoginModule and DataSourceLoginModule. - * - */ -public abstract class AbstractDatabaseLoginModule extends AbstractLoginModule -{ - private static final Logger LOG = Log.getLogger(AbstractDatabaseLoginModule.class); - - private String userQuery; - private String rolesQuery; - private String dbUserTable; - private String dbUserTableUserField; - private String dbUserTableCredentialField; - private String dbUserRoleTable; - private String dbUserRoleTableUserField; - private String dbUserRoleTableRoleField; - - - - - /** - * @return a java.sql.Connection from the database - * @throws Exception - */ - public abstract Connection getConnection () throws Exception; - - - - /* ------------------------------------------------ */ - /** Load info from database - * @param userName user info to load - * @exception SQLException - */ - public UserInfo getUserInfo (String userName) - throws Exception - { - Connection connection = null; - - try - { - connection = getConnection(); - - //query for credential - PreparedStatement statement = connection.prepareStatement (userQuery); - statement.setString (1, userName); - ResultSet results = statement.executeQuery(); - String dbCredential = null; - if (results.next()) - { - dbCredential = results.getString(1); - } - results.close(); - statement.close(); - - //query for role names - statement = connection.prepareStatement (rolesQuery); - statement.setString (1, userName); - results = statement.executeQuery(); - List<String> roles = new ArrayList<String>(); - - while (results.next()) - { - String roleName = results.getString (1); - roles.add (roleName); - } - - results.close(); - statement.close(); - - return dbCredential==null ? null : new UserInfo (userName, - Credential.getCredential(dbCredential), roles); - } - finally - { - if (connection != null) connection.close(); - } - } - - - public void initialize(Subject subject, - CallbackHandler callbackHandler, - Map<String,?> sharedState, - Map<String,?> options) - { - super.initialize(subject, callbackHandler, sharedState, options); - - //get the user credential query out of the options - dbUserTable = (String)options.get("userTable"); - dbUserTableUserField = (String)options.get("userField"); - dbUserTableCredentialField = (String)options.get("credentialField"); - - userQuery = "select "+dbUserTableCredentialField+" from "+dbUserTable+" where "+dbUserTableUserField+"=?"; - - - //get the user roles query out of the options - dbUserRoleTable = (String)options.get("userRoleTable"); - dbUserRoleTableUserField = (String)options.get("userRoleUserField"); - dbUserRoleTableRoleField = (String)options.get("userRoleRoleField"); - - rolesQuery = "select "+dbUserRoleTableRoleField+" from "+dbUserRoleTable+" where "+dbUserRoleTableUserField+"=?"; - - if(LOG.isDebugEnabled())LOG.debug("userQuery = "+userQuery); - if(LOG.isDebugEnabled())LOG.debug("rolesQuery = "+rolesQuery); - } -} diff --git a/jetty-plus/src/main/java/org/eclipse/jetty/plus/jaas/spi/AbstractLoginModule.java b/jetty-plus/src/main/java/org/eclipse/jetty/plus/jaas/spi/AbstractLoginModule.java deleted file mode 100644 index dd9448162b..0000000000 --- a/jetty-plus/src/main/java/org/eclipse/jetty/plus/jaas/spi/AbstractLoginModule.java +++ /dev/null @@ -1,288 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995-2012 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 org.eclipse.jetty.plus.jaas.spi; - -import java.io.IOException; -import java.security.Principal; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import javax.security.auth.Subject; -import javax.security.auth.callback.Callback; -import javax.security.auth.callback.CallbackHandler; -import javax.security.auth.callback.NameCallback; -import javax.security.auth.callback.PasswordCallback; -import javax.security.auth.callback.UnsupportedCallbackException; -import javax.security.auth.login.LoginException; -import javax.security.auth.spi.LoginModule; - -import org.eclipse.jetty.plus.jaas.JAASPrincipal; -import org.eclipse.jetty.plus.jaas.JAASRole; -import org.eclipse.jetty.plus.jaas.callback.ObjectCallback; - -/** - * AbstractLoginModule - * - * Abstract base class for all LoginModules. Subclasses should - * just need to implement getUserInfo method. - * - */ -public abstract class AbstractLoginModule implements LoginModule -{ - private CallbackHandler callbackHandler; - - private boolean authState = false; - private boolean commitState = false; - private JAASUserInfo currentUser; - private Subject subject; - - public class JAASUserInfo - { - private UserInfo user; - private Principal principal; - private List<JAASRole> roles; - - public JAASUserInfo (UserInfo u) - { - setUserInfo(u); - } - - public String getUserName () - { - return this.user.getUserName(); - } - - public Principal getPrincipal() - { - return this.principal; - } - - public void setUserInfo (UserInfo u) - { - this.user = u; - this.principal = new JAASPrincipal(u.getUserName()); - this.roles = new ArrayList<JAASRole>(); - if (u.getRoleNames() != null) - { - Iterator<String> itor = u.getRoleNames().iterator(); - while (itor.hasNext()) - this.roles.add(new JAASRole((String)itor.next())); - } - } - - public void setJAASInfo (Subject subject) - { - subject.getPrincipals().add(this.principal); - subject.getPrivateCredentials().add(this.user.getCredential()); - subject.getPrincipals().addAll(roles); - } - - public void unsetJAASInfo (Subject subject) - { - subject.getPrincipals().remove(this.principal); - subject.getPrivateCredentials().remove(this.user.getCredential()); - subject.getPrincipals().removeAll(this.roles); - } - - public boolean checkCredential (Object suppliedCredential) - { - return this.user.checkCredential(suppliedCredential); - } - } - - - - public Subject getSubject () - { - return this.subject; - } - - public void setSubject (Subject s) - { - this.subject = s; - } - - public JAASUserInfo getCurrentUser() - { - return this.currentUser; - } - - public void setCurrentUser (JAASUserInfo u) - { - this.currentUser = u; - } - - public CallbackHandler getCallbackHandler() - { - return this.callbackHandler; - } - - public void setCallbackHandler(CallbackHandler h) - { - this.callbackHandler = h; - } - - public boolean isAuthenticated() - { - return this.authState; - } - - public boolean isCommitted () - { - return this.commitState; - } - - public void setAuthenticated (boolean authState) - { - this.authState = authState; - } - - public void setCommitted (boolean commitState) - { - this.commitState = commitState; - } - /** - * @see javax.security.auth.spi.LoginModule#abort() - * @throws LoginException - */ - public boolean abort() throws LoginException - { - this.currentUser = null; - return (isAuthenticated() && isCommitted()); - } - - /** - * @see javax.security.auth.spi.LoginModule#commit() - * @return true if committed, false if not (likely not authenticated) - * @throws LoginException - */ - public boolean commit() throws LoginException - { - - if (!isAuthenticated()) - { - currentUser = null; - setCommitted(false); - return false; - } - - setCommitted(true); - currentUser.setJAASInfo(subject); - return true; - } - - - public Callback[] configureCallbacks () - { - - Callback[] callbacks = new Callback[3]; - callbacks[0] = new NameCallback("Enter user name"); - callbacks[1] = new ObjectCallback(); - callbacks[2] = new PasswordCallback("Enter password", false); //only used if framework does not support the ObjectCallback - return callbacks; - } - - - - public abstract UserInfo getUserInfo (String username) throws Exception; - - - - /** - * @see javax.security.auth.spi.LoginModule#login() - * @return true if is authenticated, false otherwise - * @throws LoginException - */ - public boolean login() throws LoginException - { - try - { - if (callbackHandler == null) - throw new LoginException ("No callback handler"); - - Callback[] callbacks = configureCallbacks(); - callbackHandler.handle(callbacks); - - String webUserName = ((NameCallback)callbacks[0]).getName(); - Object webCredential = null; - - webCredential = ((ObjectCallback)callbacks[1]).getObject(); //first check if ObjectCallback has the credential - if (webCredential == null) - webCredential = ((PasswordCallback)callbacks[2]).getPassword(); //use standard PasswordCallback - - if ((webUserName == null) || (webCredential == null)) - { - setAuthenticated(false); - return isAuthenticated(); - } - - UserInfo userInfo = getUserInfo(webUserName); - - if (userInfo == null) - { - setAuthenticated(false); - return isAuthenticated(); - } - - currentUser = new JAASUserInfo(userInfo); - setAuthenticated(currentUser.checkCredential(webCredential)); - return isAuthenticated(); - } - catch (IOException e) - { - throw new LoginException (e.toString()); - } - catch (UnsupportedCallbackException e) - { - throw new LoginException (e.toString()); - } - catch (Exception e) - { - e.printStackTrace(); - throw new LoginException (e.toString()); - } - } - - /** - * @see javax.security.auth.spi.LoginModule#logout() - * @return true always - * @throws LoginException - */ - public boolean logout() throws LoginException - { - this.currentUser.unsetJAASInfo(this.subject); - return true; - } - - /** - * @see javax.security.auth.spi.LoginModule#initialize(javax.security.auth.Subject, javax.security.auth.callback.CallbackHandler, java.util.Map, java.util.Map) - * @param subject - * @param callbackHandler - * @param sharedState - * @param options - */ - public void initialize(Subject subject, CallbackHandler callbackHandler, - Map<String,?> sharedState, Map<String,?> options) - { - this.callbackHandler = callbackHandler; - this.subject = subject; - } - -} diff --git a/jetty-plus/src/main/java/org/eclipse/jetty/plus/jaas/spi/DataSourceLoginModule.java b/jetty-plus/src/main/java/org/eclipse/jetty/plus/jaas/spi/DataSourceLoginModule.java deleted file mode 100644 index 4771399dd0..0000000000 --- a/jetty-plus/src/main/java/org/eclipse/jetty/plus/jaas/spi/DataSourceLoginModule.java +++ /dev/null @@ -1,89 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995-2012 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 org.eclipse.jetty.plus.jaas.spi; - -import java.sql.Connection; -import java.util.Map; -import javax.naming.InitialContext; -import javax.naming.NamingException; -import javax.security.auth.Subject; -import javax.security.auth.callback.CallbackHandler; -import javax.sql.DataSource; - -/** - * DataSourceLoginModule - * - * A LoginModule that uses a DataSource to retrieve user authentication - * and authorisation information. - * - * @see JDBCLoginModule - */ -public class DataSourceLoginModule extends AbstractDatabaseLoginModule -{ - - private String dbJNDIName; - private DataSource dataSource; - - /* ------------------------------------------------ */ - /** Init LoginModule. - * Called once by JAAS after new instance created. - * @param subject - * @param callbackHandler - * @param sharedState - * @param options - */ - public void initialize(Subject subject, - CallbackHandler callbackHandler, - Map<String,?> sharedState, - Map<String,?> options) - { - try - { - super.initialize(subject, callbackHandler, sharedState, options); - - //get the datasource jndi name - dbJNDIName = (String)options.get("dbJNDIName"); - - InitialContext ic = new InitialContext(); - dataSource = (DataSource)ic.lookup("java:comp/env/"+dbJNDIName); - } - catch (NamingException e) - { - throw new IllegalStateException (e.toString()); - } - } - - - /** - * Get a connection from the DataSource - * @see AbstractDatabaseLoginModule#getConnection() - * @return the connection for the datasource - * @throws Exception - */ - public Connection getConnection () - throws Exception - { - return dataSource.getConnection(); - } - - - - - -} diff --git a/jetty-plus/src/main/java/org/eclipse/jetty/plus/jaas/spi/JDBCLoginModule.java b/jetty-plus/src/main/java/org/eclipse/jetty/plus/jaas/spi/JDBCLoginModule.java deleted file mode 100644 index 0e6ac5e8a1..0000000000 --- a/jetty-plus/src/main/java/org/eclipse/jetty/plus/jaas/spi/JDBCLoginModule.java +++ /dev/null @@ -1,126 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995-2012 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 org.eclipse.jetty.plus.jaas.spi; - -import java.sql.Connection; -import java.sql.DriverManager; -import java.util.Map; -import javax.security.auth.Subject; -import javax.security.auth.callback.CallbackHandler; - -import org.eclipse.jetty.util.Loader; -import org.eclipse.jetty.util.log.Log; -import org.eclipse.jetty.util.log.Logger; - - - -/* ---------------------------------------------------- */ -/** JDBCLoginModule - * <p>JAAS LoginModule to retrieve user information from - * a database and authenticate the user. - * - * <p><h4>Notes</h4> - * <p>This version uses plain old JDBC connections NOT - * Datasources. - * - * <p><h4>Usage</h4> - * <pre> - * </pre> - * - * @version 1.0 Tue Apr 15 2003 - */ -public class JDBCLoginModule extends AbstractDatabaseLoginModule -{ - private static final Logger LOG = Log.getLogger(JDBCLoginModule.class); - - private String dbDriver; - private String dbUrl; - private String dbUserName; - private String dbPassword; - - - /** - * Get a connection from the DriverManager - * @see AbstractDatabaseLoginModule#getConnection() - * @return the connection for this datasource - * @throws Exception - */ - public Connection getConnection () - throws Exception - { - if (!((dbDriver != null) - && - (dbUrl != null))) - throw new IllegalStateException ("Database connection information not configured"); - - if(LOG.isDebugEnabled())LOG.debug("Connecting using dbDriver="+dbDriver+"+ dbUserName="+dbUserName+", dbPassword="+dbUrl); - - return DriverManager.getConnection (dbUrl, - dbUserName, - dbPassword); - } - - - - /* ------------------------------------------------ */ - /** Init LoginModule. - * Called once by JAAS after new instance created. - * @param subject - * @param callbackHandler - * @param sharedState - * @param options - */ - public void initialize(Subject subject, - CallbackHandler callbackHandler, - Map<String,?> sharedState, - Map<String,?> options) - { - try - { - super.initialize(subject, callbackHandler, sharedState, options); - - //get the jdbc username/password, jdbc url out of the options - dbDriver = (String)options.get("dbDriver"); - dbUrl = (String)options.get("dbUrl"); - dbUserName = (String)options.get("dbUserName"); - dbPassword = (String)options.get("dbPassword"); - - if (dbUserName == null) - dbUserName = ""; - - if (dbPassword == null) - dbPassword = ""; - - if (dbDriver != null) - Loader.loadClass(this.getClass(), dbDriver).newInstance(); - } - catch (ClassNotFoundException e) - { - throw new IllegalStateException (e.toString()); - } - catch (InstantiationException e) - { - throw new IllegalStateException (e.toString()); - } - catch (IllegalAccessException e) - { - throw new IllegalStateException (e.toString()); - } - } -} diff --git a/jetty-plus/src/main/java/org/eclipse/jetty/plus/jaas/spi/LdapLoginModule.java b/jetty-plus/src/main/java/org/eclipse/jetty/plus/jaas/spi/LdapLoginModule.java deleted file mode 100644 index 676233f008..0000000000 --- a/jetty-plus/src/main/java/org/eclipse/jetty/plus/jaas/spi/LdapLoginModule.java +++ /dev/null @@ -1,687 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995-2012 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 org.eclipse.jetty.plus.jaas.spi; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Hashtable; -import java.util.List; -import java.util.Map; -import java.util.Properties; -import javax.naming.Context; -import javax.naming.NamingEnumeration; -import javax.naming.NamingException; -import javax.naming.directory.Attribute; -import javax.naming.directory.Attributes; -import javax.naming.directory.DirContext; -import javax.naming.directory.InitialDirContext; -import javax.naming.directory.SearchControls; -import javax.naming.directory.SearchResult; -import javax.security.auth.Subject; -import javax.security.auth.callback.Callback; -import javax.security.auth.callback.CallbackHandler; -import javax.security.auth.callback.NameCallback; -import javax.security.auth.callback.UnsupportedCallbackException; -import javax.security.auth.login.LoginException; - -import org.eclipse.jetty.plus.jaas.callback.ObjectCallback; -import org.eclipse.jetty.util.log.Log; -import org.eclipse.jetty.util.log.Logger; -import org.eclipse.jetty.util.security.Credential; - -/** - * A LdapLoginModule for use with JAAS setups - * <p/> - * The jvm should be started with the following parameter: - * <br><br> - * <code> - * -Djava.security.auth.login.config=etc/ldap-loginModule.conf - * </code> - * <br><br> - * and an example of the ldap-loginModule.conf would be: - * <br><br> - * <pre> - * ldaploginmodule { - * org.eclipse.jetty.server.server.plus.jaas.spi.LdapLoginModule required - * debug="true" - * useLdaps="false" - * contextFactory="com.sun.jndi.ldap.LdapCtxFactory" - * hostname="ldap.example.com" - * port="389" - * bindDn="cn=Directory Manager" - * bindPassword="directory" - * authenticationMethod="simple" - * forceBindingLogin="false" - * userBaseDn="ou=people,dc=alcatel" - * userRdnAttribute="uid" - * userIdAttribute="uid" - * userPasswordAttribute="userPassword" - * userObjectClass="inetOrgPerson" - * roleBaseDn="ou=groups,dc=example,dc=com" - * roleNameAttribute="cn" - * roleMemberAttribute="uniqueMember" - * roleObjectClass="groupOfUniqueNames"; - * }; - * </pre> - * - * - * - * - */ -public class LdapLoginModule extends AbstractLoginModule -{ - private static final Logger LOG = Log.getLogger(LdapLoginModule.class); - - /** - * hostname of the ldap server - */ - private String _hostname; - - /** - * port of the ldap server - */ - private int _port; - - /** - * Context.SECURITY_AUTHENTICATION - */ - private String _authenticationMethod; - - /** - * Context.INITIAL_CONTEXT_FACTORY - */ - private String _contextFactory; - - /** - * root DN used to connect to - */ - private String _bindDn; - - /** - * password used to connect to the root ldap context - */ - private String _bindPassword; - - /** - * object class of a user - */ - private String _userObjectClass = "inetOrgPerson"; - - /** - * attribute that the principal is located - */ - private String _userRdnAttribute = "uid"; - - /** - * attribute that the principal is located - */ - private String _userIdAttribute = "cn"; - - /** - * name of the attribute that a users password is stored under - * <p/> - * NOTE: not always accessible, see force binding login - */ - private String _userPasswordAttribute = "userPassword"; - - /** - * base DN where users are to be searched from - */ - private String _userBaseDn; - - /** - * base DN where role membership is to be searched from - */ - private String _roleBaseDn; - - /** - * object class of roles - */ - private String _roleObjectClass = "groupOfUniqueNames"; - - /** - * name of the attribute that a username would be under a role class - */ - private String _roleMemberAttribute = "uniqueMember"; - - /** - * the name of the attribute that a role would be stored under - */ - private String _roleNameAttribute = "roleName"; - - private boolean _debug; - - /** - * if the getUserInfo can pull a password off of the user then - * password comparison is an option for authn, to force binding - * login checks, set this to true - */ - private boolean _forceBindingLogin = false; - - /** - * When true changes the protocol to ldaps - */ - private boolean _useLdaps = false; - - private DirContext _rootContext; - - /** - * get the available information about the user - * <p/> - * for this LoginModule, the credential can be null which will result in a - * binding ldap authentication scenario - * <p/> - * roles are also an optional concept if required - * - * @param username - * @return the userinfo for the username - * @throws Exception - */ - public UserInfo getUserInfo(String username) throws Exception - { - String pwdCredential = getUserCredentials(username); - - if (pwdCredential == null) - { - return null; - } - - pwdCredential = convertCredentialLdapToJetty(pwdCredential); - Credential credential = Credential.getCredential(pwdCredential); - List<String> roles = getUserRoles(_rootContext, username); - - return new UserInfo(username, credential, roles); - } - - protected String doRFC2254Encoding(String inputString) - { - StringBuffer buf = new StringBuffer(inputString.length()); - for (int i = 0; i < inputString.length(); i++) - { - char c = inputString.charAt(i); - switch (c) - { - case '\\': - buf.append("\\5c"); - break; - case '*': - buf.append("\\2a"); - break; - case '(': - buf.append("\\28"); - break; - case ')': - buf.append("\\29"); - break; - case '\0': - buf.append("\\00"); - break; - default: - buf.append(c); - break; - } - } - return buf.toString(); - } - - /** - * attempts to get the users credentials from the users context - * <p/> - * NOTE: this is not an user authenticated operation - * - * @param username - * @return - * @throws LoginException - */ - private String getUserCredentials(String username) throws LoginException - { - String ldapCredential = null; - - SearchControls ctls = new SearchControls(); - ctls.setCountLimit(1); - ctls.setDerefLinkFlag(true); - ctls.setSearchScope(SearchControls.SUBTREE_SCOPE); - - String filter = "(&(objectClass={0})({1}={2}))"; - - LOG.debug("Searching for users with filter: \'" + filter + "\'" + " from base dn: " + _userBaseDn); - - try - { - Object[] filterArguments = {_userObjectClass, _userIdAttribute, username}; - NamingEnumeration<SearchResult> results = _rootContext.search(_userBaseDn, filter, filterArguments, ctls); - - LOG.debug("Found user?: " + results.hasMoreElements()); - - if (!results.hasMoreElements()) - { - throw new LoginException("User not found."); - } - - SearchResult result = findUser(username); - - Attributes attributes = result.getAttributes(); - - Attribute attribute = attributes.get(_userPasswordAttribute); - if (attribute != null) - { - try - { - byte[] value = (byte[]) attribute.get(); - - ldapCredential = new String(value); - } - catch (NamingException e) - { - LOG.debug("no password available under attribute: " + _userPasswordAttribute); - } - } - } - catch (NamingException e) - { - throw new LoginException("Root context binding failure."); - } - - LOG.debug("user cred is: " + ldapCredential); - - return ldapCredential; - } - - /** - * attempts to get the users roles from the root context - * <p/> - * NOTE: this is not an user authenticated operation - * - * @param dirContext - * @param username - * @return - * @throws LoginException - */ - private List<String> getUserRoles(DirContext dirContext, String username) throws LoginException, NamingException - { - String userDn = _userRdnAttribute + "=" + username + "," + _userBaseDn; - - return getUserRolesByDn(dirContext, userDn); - } - - private List<String> getUserRolesByDn(DirContext dirContext, String userDn) throws LoginException, NamingException - { - List<String> roleList = new ArrayList<String>(); - - if (dirContext == null || _roleBaseDn == null || _roleMemberAttribute == null || _roleObjectClass == null) - { - return roleList; - } - - SearchControls ctls = new SearchControls(); - ctls.setDerefLinkFlag(true); - ctls.setSearchScope(SearchControls.SUBTREE_SCOPE); - ctls.setReturningAttributes(new String[]{_roleNameAttribute}); - - String filter = "(&(objectClass={0})({1}={2}))"; - Object[] filterArguments = {_roleObjectClass, _roleMemberAttribute, userDn}; - NamingEnumeration<SearchResult> results = dirContext.search(_roleBaseDn, filter, filterArguments, ctls); - - LOG.debug("Found user roles?: " + results.hasMoreElements()); - - while (results.hasMoreElements()) - { - SearchResult result = (SearchResult) results.nextElement(); - - Attributes attributes = result.getAttributes(); - - if (attributes == null) - { - continue; - } - - Attribute roleAttribute = attributes.get(_roleNameAttribute); - - if (roleAttribute == null) - { - continue; - } - - NamingEnumeration<?> roles = roleAttribute.getAll(); - while (roles.hasMore()) - { - roleList.add(roles.next().toString()); - } - } - - return roleList; - } - - - /** - * since ldap uses a context bind for valid authentication checking, we override login() - * <p/> - * if credentials are not available from the users context or if we are forcing the binding check - * then we try a binding authentication check, otherwise if we have the users encoded password then - * we can try authentication via that mechanic - * - * @return true if authenticated, false otherwise - * @throws LoginException - */ - public boolean login() throws LoginException - { - try - { - if (getCallbackHandler() == null) - { - throw new LoginException("No callback handler"); - } - - Callback[] callbacks = configureCallbacks(); - getCallbackHandler().handle(callbacks); - - String webUserName = ((NameCallback) callbacks[0]).getName(); - Object webCredential = ((ObjectCallback) callbacks[1]).getObject(); - - if (webUserName == null || webCredential == null) - { - setAuthenticated(false); - return isAuthenticated(); - } - - if (_forceBindingLogin) - { - return bindingLogin(webUserName, webCredential); - } - - // This sets read and the credential - UserInfo userInfo = getUserInfo(webUserName); - - if (userInfo == null) - { - setAuthenticated(false); - return false; - } - - setCurrentUser(new JAASUserInfo(userInfo)); - - if (webCredential instanceof String) - { - return credentialLogin(Credential.getCredential((String) webCredential)); - } - - return credentialLogin(webCredential); - } - catch (UnsupportedCallbackException e) - { - throw new LoginException("Error obtaining callback information."); - } - catch (IOException e) - { - if (_debug) - { - e.printStackTrace(); - } - throw new LoginException("IO Error performing login."); - } - catch (Exception e) - { - if (_debug) - { - e.printStackTrace(); - } - throw new LoginException("Error obtaining user info."); - } - } - - /** - * password supplied authentication check - * - * @param webCredential - * @return true if authenticated - * @throws LoginException - */ - protected boolean credentialLogin(Object webCredential) throws LoginException - { - setAuthenticated(getCurrentUser().checkCredential(webCredential)); - return isAuthenticated(); - } - - /** - * binding authentication check - * This method of authentication works only if the user branch of the DIT (ldap tree) - * has an ACI (access control instruction) that allow the access to any user or at least - * for the user that logs in. - * - * @param username - * @param password - * @return true always - * @throws LoginException - */ - public boolean bindingLogin(String username, Object password) throws LoginException, NamingException - { - SearchResult searchResult = findUser(username); - - String userDn = searchResult.getNameInNamespace(); - - LOG.info("Attempting authentication: " + userDn); - - Hashtable<Object,Object> environment = getEnvironment(); - environment.put(Context.SECURITY_PRINCIPAL, userDn); - environment.put(Context.SECURITY_CREDENTIALS, password); - - DirContext dirContext = new InitialDirContext(environment); - List<String> roles = getUserRolesByDn(dirContext, userDn); - - UserInfo userInfo = new UserInfo(username, null, roles); - setCurrentUser(new JAASUserInfo(userInfo)); - setAuthenticated(true); - - return true; - } - - private SearchResult findUser(String username) throws NamingException, LoginException - { - SearchControls ctls = new SearchControls(); - ctls.setCountLimit(1); - ctls.setDerefLinkFlag(true); - ctls.setSearchScope(SearchControls.SUBTREE_SCOPE); - - String filter = "(&(objectClass={0})({1}={2}))"; - - LOG.info("Searching for users with filter: \'" + filter + "\'" + " from base dn: " + _userBaseDn); - - Object[] filterArguments = new Object[]{ - _userObjectClass, - _userIdAttribute, - username - }; - NamingEnumeration<SearchResult> results = _rootContext.search(_userBaseDn, filter, filterArguments, ctls); - - LOG.info("Found user?: " + results.hasMoreElements()); - - if (!results.hasMoreElements()) - { - throw new LoginException("User not found."); - } - - return (SearchResult) results.nextElement(); - } - - - /** - * Init LoginModule. - * Called once by JAAS after new instance is created. - * - * @param subject - * @param callbackHandler - * @param sharedState - * @param options - */ - public void initialize(Subject subject, - CallbackHandler callbackHandler, - Map<String,?> sharedState, - Map<String,?> options) - { - super.initialize(subject, callbackHandler, sharedState, options); - - _hostname = (String) options.get("hostname"); - _port = Integer.parseInt((String) options.get("port")); - _contextFactory = (String) options.get("contextFactory"); - _bindDn = (String) options.get("bindDn"); - _bindPassword = (String) options.get("bindPassword"); - _authenticationMethod = (String) options.get("authenticationMethod"); - - _userBaseDn = (String) options.get("userBaseDn"); - - _roleBaseDn = (String) options.get("roleBaseDn"); - - if (options.containsKey("forceBindingLogin")) - { - _forceBindingLogin = Boolean.parseBoolean((String) options.get("forceBindingLogin")); - } - - if (options.containsKey("useLdaps")) - { - _useLdaps = Boolean.parseBoolean((String) options.get("useLdaps")); - } - - _userObjectClass = getOption(options, "userObjectClass", _userObjectClass); - _userRdnAttribute = getOption(options, "userRdnAttribute", _userRdnAttribute); - _userIdAttribute = getOption(options, "userIdAttribute", _userIdAttribute); - _userPasswordAttribute = getOption(options, "userPasswordAttribute", _userPasswordAttribute); - _roleObjectClass = getOption(options, "roleObjectClass", _roleObjectClass); - _roleMemberAttribute = getOption(options, "roleMemberAttribute", _roleMemberAttribute); - _roleNameAttribute = getOption(options, "roleNameAttribute", _roleNameAttribute); - _debug = Boolean.parseBoolean(String.valueOf(getOption(options, "debug", Boolean.toString(_debug)))); - - try - { - _rootContext = new InitialDirContext(getEnvironment()); - } - catch (NamingException ex) - { - throw new IllegalStateException("Unable to establish root context", ex); - } - } - - public boolean commit() throws LoginException - { - try - { - _rootContext.close(); - } - catch (NamingException e) - { - throw new LoginException( "error closing root context: " + e.getMessage() ); - } - - return super.commit(); - } - - public boolean abort() throws LoginException - { - try - { - _rootContext.close(); - } - catch (NamingException e) - { - throw new LoginException( "error closing root context: " + e.getMessage() ); - } - - return super.abort(); - } - - private String getOption(Map<String,?> options, String key, String defaultValue) - { - Object value = options.get(key); - - if (value == null) - { - return defaultValue; - } - - return (String) value; - } - - /** - * get the context for connection - * - * @return the environment details for the context - */ - public Hashtable<Object, Object> getEnvironment() - { - Properties env = new Properties(); - - env.put(Context.INITIAL_CONTEXT_FACTORY, _contextFactory); - - if (_hostname != null) - { - env.put(Context.PROVIDER_URL, (_useLdaps?"ldaps://":"ldap://") + _hostname + (_port==0?"":":"+_port) +"/"); - } - - if (_authenticationMethod != null) - { - env.put(Context.SECURITY_AUTHENTICATION, _authenticationMethod); - } - - if (_bindDn != null) - { - env.put(Context.SECURITY_PRINCIPAL, _bindDn); - } - - if (_bindPassword != null) - { - env.put(Context.SECURITY_CREDENTIALS, _bindPassword); - } - - return env; - } - - public static String convertCredentialJettyToLdap(String encryptedPassword) - { - if ("MD5:".startsWith(encryptedPassword.toUpperCase())) - { - return "{MD5}" + encryptedPassword.substring("MD5:".length(), encryptedPassword.length()); - } - - if ("CRYPT:".startsWith(encryptedPassword.toUpperCase())) - { - return "{CRYPT}" + encryptedPassword.substring("CRYPT:".length(), encryptedPassword.length()); - } - - return encryptedPassword; - } - - public static String convertCredentialLdapToJetty(String encryptedPassword) - { - if (encryptedPassword == null) - { - return encryptedPassword; - } - - if ("{MD5}".startsWith(encryptedPassword.toUpperCase())) - { - return "MD5:" + encryptedPassword.substring("{MD5}".length(), encryptedPassword.length()); - } - - if ("{CRYPT}".startsWith(encryptedPassword.toUpperCase())) - { - return "CRYPT:" + encryptedPassword.substring("{CRYPT}".length(), encryptedPassword.length()); - } - - return encryptedPassword; - } -} diff --git a/jetty-plus/src/main/java/org/eclipse/jetty/plus/jaas/spi/PropertyFileLoginModule.java b/jetty-plus/src/main/java/org/eclipse/jetty/plus/jaas/spi/PropertyFileLoginModule.java deleted file mode 100644 index bd4f8cbbe4..0000000000 --- a/jetty-plus/src/main/java/org/eclipse/jetty/plus/jaas/spi/PropertyFileLoginModule.java +++ /dev/null @@ -1,129 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995-2012 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 org.eclipse.jetty.plus.jaas.spi; - -import java.security.Principal; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; -import javax.security.auth.Subject; -import javax.security.auth.callback.CallbackHandler; - -import org.eclipse.jetty.security.PropertyUserStore; -import org.eclipse.jetty.server.UserIdentity; -import org.eclipse.jetty.util.log.Log; -import org.eclipse.jetty.util.log.Logger; -import org.eclipse.jetty.util.security.Credential; - -/** - * PropertyFileLoginModule - * - * - */ -public class PropertyFileLoginModule extends AbstractLoginModule -{ - public static final String DEFAULT_FILENAME = "realm.properties"; - - private static final Logger LOG = Log.getLogger(PropertyFileLoginModule.class); - - private static Map<String, PropertyUserStore> _propertyUserStores = new HashMap<String, PropertyUserStore>(); - - private int _refreshInterval = 0; - private String _filename = DEFAULT_FILENAME; - - /** - * Read contents of the configured property file. - * - * @see javax.security.auth.spi.LoginModule#initialize(javax.security.auth.Subject, javax.security.auth.callback.CallbackHandler, java.util.Map, - * java.util.Map) - * @param subject - * @param callbackHandler - * @param sharedState - * @param options - */ - public void initialize(Subject subject, CallbackHandler callbackHandler, Map<String, ?> sharedState, Map<String, ?> options) - { - super.initialize(subject,callbackHandler,sharedState,options); - setupPropertyUserStore(options); - } - - private void setupPropertyUserStore(Map<String, ?> options) - { - if (_propertyUserStores.get(_filename) == null) - { - parseConfig(options); - - PropertyUserStore _propertyUserStore = new PropertyUserStore(); - _propertyUserStore.setConfig(_filename); - _propertyUserStore.setRefreshInterval(_refreshInterval); - LOG.debug("setupPropertyUserStore: Starting new PropertyUserStore. PropertiesFile: " + _filename + " refreshInterval: " + _refreshInterval); - - try - { - _propertyUserStore.start(); - } - catch (Exception e) - { - LOG.warn("Exception while starting propertyUserStore: ",e); - } - - _propertyUserStores.put(_filename,_propertyUserStore); - } - } - - private void parseConfig(Map<String, ?> options) - { - _filename = (String)options.get("file") != null?(String)options.get("file"):DEFAULT_FILENAME; - String refreshIntervalString = (String)options.get("refreshInterval"); - _refreshInterval = refreshIntervalString == null?_refreshInterval:Integer.parseInt(refreshIntervalString); - } - - /** - * Don't implement this as we want to pre-fetch all of the users. - * - * @param userName - * @throws Exception - */ - public UserInfo getUserInfo(String userName) throws Exception - { - PropertyUserStore propertyUserStore = _propertyUserStores.get(_filename); - if (propertyUserStore == null) - throw new IllegalStateException("PropertyUserStore should never be null here!"); - - UserIdentity userIdentity = propertyUserStore.getUserIdentity(userName); - if(userIdentity==null) - return null; - - Set<Principal> principals = userIdentity.getSubject().getPrincipals(); - - List<String> roles = new ArrayList<String>(); - - for ( Principal principal : principals ) - { - roles.add( principal.getName() ); - } - - Credential credential = (Credential)userIdentity.getSubject().getPrivateCredentials().iterator().next(); - LOG.debug("Found: " + userName + " in PropertyUserStore"); - return new UserInfo(userName, credential, roles); - } - -} diff --git a/jetty-plus/src/main/java/org/eclipse/jetty/plus/jaas/spi/UserInfo.java b/jetty-plus/src/main/java/org/eclipse/jetty/plus/jaas/spi/UserInfo.java deleted file mode 100644 index c40010046a..0000000000 --- a/jetty-plus/src/main/java/org/eclipse/jetty/plus/jaas/spi/UserInfo.java +++ /dev/null @@ -1,73 +0,0 @@ -// -// ======================================================================== -// Copyright (c) 1995-2012 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 org.eclipse.jetty.plus.jaas.spi; - -import java.util.ArrayList; -import java.util.List; - -import org.eclipse.jetty.util.security.Credential; - -/** - * UserInfo - * - * This is the information read from the external source - * about a user. - * - * Can be cached by a UserInfoCache implementation - */ -public class UserInfo -{ - - private String _userName; - private Credential _credential; - private List<String> _roleNames; - - - public UserInfo (String userName, Credential credential, List<String> roleNames) - { - _userName = userName; - _credential = credential; - _roleNames = new ArrayList<String>(); - if (roleNames != null) - { - _roleNames.addAll(roleNames); - } - } - - public String getUserName() - { - return this._userName; - } - - public List<String> getRoleNames () - { - return new ArrayList<String>(_roleNames); - } - - public boolean checkCredential (Object suppliedCredential) - { - return _credential.check(suppliedCredential); - } - - protected Credential getCredential () - { - return _credential; - } - -} |