improve authentication system

This commit is contained in:
Sebastian Sdorra
2010-12-02 20:44:13 +01:00
parent 1cacbc3c03
commit 1c6413c44b
9 changed files with 599 additions and 64 deletions

View File

@@ -29,12 +29,13 @@
*
*/
package sonia.scm.web.security;
//~--- non-JDK imports --------------------------------------------------------
import sonia.scm.Initable;
import sonia.scm.user.User;
//~--- JDK imports ------------------------------------------------------------
@@ -47,7 +48,7 @@ import javax.servlet.http.HttpServletResponse;
*
* @author Sebastian Sdorra
*/
public interface Authenticator extends Initable, Closeable
public interface AuthenticationManager extends Initable, Closeable
{
/**
@@ -61,7 +62,6 @@ public interface Authenticator extends Initable, Closeable
*
* @return
*/
public User authenticate(HttpServletRequest request,
HttpServletResponse response, String username,
String password);
public AuthenticationResult authenticate(HttpServletRequest request,
HttpServletResponse response, String username, String password);
}

View File

@@ -0,0 +1,137 @@
/**
* Copyright (c) 2010, Sebastian Sdorra
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of SCM-Manager; nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* http://bitbucket.org/sdorra/scm-manager
*
*/
package sonia.scm.web.security;
//~--- non-JDK imports --------------------------------------------------------
import sonia.scm.user.User;
/**
*
* @author Sebastian Sdorra
*/
public class AuthenticationResult
{
/** Field description */
public static final AuthenticationResult NEXT =
new AuthenticationResult(AuthenticationState.NEXT);
/** Field description */
public static final AuthenticationResult FAILED =
new AuthenticationResult(AuthenticationState.FAILED);
//~--- constructors ---------------------------------------------------------
/**
* Constructs ...
*
*
* @param state
*/
public AuthenticationResult(AuthenticationState state)
{
this.state = state;
}
/**
* Constructs ...
*
*
* @param user
* @param state
*/
public AuthenticationResult(User user, AuthenticationState state)
{
this.user = user;
this.state = state;
}
//~--- methods --------------------------------------------------------------
/**
* Method description
*
*
* @return
*/
@Override
public String toString()
{
StringBuilder out = new StringBuilder("user: ");
if (user != null)
{
out.append(user.getName());
}
else
{
out.append("null");
}
return out.append(", state: ").append(state.toString()).toString();
}
//~--- get methods ----------------------------------------------------------
/**
* Method description
*
*
* @return
*/
public AuthenticationState getState()
{
return state;
}
/**
* Method description
*
*
* @return
*/
public User getUser()
{
return user;
}
//~--- fields ---------------------------------------------------------------
/** Field description */
private AuthenticationState state;
/** Field description */
private User user;
}

View File

@@ -0,0 +1,73 @@
/**
* Copyright (c) 2010, Sebastian Sdorra
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of SCM-Manager; nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* http://bitbucket.org/sdorra/scm-manager
*
*/
package sonia.scm.web.security;
/**
*
* @author Sebastian Sdorra
*/
public enum AuthenticationState
{
CREATE_USER(true), MODIFY_USER(true), SUCCESS(true), NEXT(false),
FAILED(false);
/**
* Constructs ...
*
*
* @param successfully
*/
private AuthenticationState(boolean successfully)
{
this.successfully = successfully;
}
//~--- get methods ----------------------------------------------------------
/**
* Method description
*
*
* @return
*/
public boolean isSuccessfully()
{
return successfully;
}
//~--- fields ---------------------------------------------------------------
/** Field description */
private boolean successfully = false;
}

View File

@@ -29,6 +29,8 @@
*
*/
package sonia.scm.web.security;
//~--- non-JDK imports --------------------------------------------------------
@@ -36,7 +38,11 @@ package sonia.scm.web.security;
import com.google.inject.Inject;
import com.google.inject.servlet.SessionScoped;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sonia.scm.user.User;
import sonia.scm.user.UserManager;
//~--- JDK imports ------------------------------------------------------------
@@ -51,6 +57,29 @@ import javax.servlet.http.HttpServletResponse;
public class BasicSecurityContext implements WebSecurityContext
{
/** the logger for BasicSecurityContext */
private static final Logger logger =
LoggerFactory.getLogger(BasicSecurityContext.class);
//~--- constructors ---------------------------------------------------------
/**
* Constructs ...
*
*
* @param authenticator
* @param userManager
*/
@Inject
public BasicSecurityContext(AuthenticationManager authenticator,
UserManager userManager)
{
this.authenticator = authenticator;
this.userManager = userManager;
}
//~--- methods --------------------------------------------------------------
/**
* Method description
*
@@ -67,7 +96,31 @@ public class BasicSecurityContext implements WebSecurityContext
HttpServletResponse response, String username,
String password)
{
user = authenticator.authenticate(request, response, username, password);
AuthenticationResult result = authenticator.authenticate(request, response,
username, password);
if (result.getState().isSuccessfully())
{
user = result.getUser();
try
{
switch (result.getState())
{
case CREATE_USER :
userManager.create(user);
break;
case MODIFY_USER :
userManager.modify(user);
}
}
catch (Exception ex)
{
logger.error(ex.getMessage(), ex);
}
}
return user;
}
@@ -114,9 +167,11 @@ public class BasicSecurityContext implements WebSecurityContext
//~--- fields ---------------------------------------------------------------
/** Field description */
@Inject
private Authenticator authenticator;
private AuthenticationManager authenticator;
/** Field description */
private User user;
/** Field description */
private UserManager userManager;
}

View File

@@ -42,31 +42,44 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sonia.scm.SCMContextProvider;
import sonia.scm.security.EncryptionHandler;
import sonia.scm.user.User;
import sonia.scm.util.AssertUtil;
import sonia.scm.util.IOUtil;
//~--- JDK imports ------------------------------------------------------------
import java.io.IOException;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import sonia.scm.user.UserManager;
/**
*
* @author Sebastian Sdorra
*/
@Singleton
public class XmlAuthenticator implements Authenticator
public class ChainAuthenticatonManager implements AuthenticationManager
{
/** Field description */
public static final String NAME_DIRECTORY = "users";
/** the logger for XmlAuthenticator */
/** the logger for ChainAuthenticatonManager */
private static final Logger logger =
LoggerFactory.getLogger(XmlAuthenticator.class);
LoggerFactory.getLogger(ChainAuthenticatonManager.class);
//~--- constructors ---------------------------------------------------------
/**
* Constructs ...
*
*
* @param authenticatorSet
*/
@Inject
public ChainAuthenticatonManager(Set<AuthenticationManager> authenticatorSet)
{
AssertUtil.assertIsNotEmpty(authenticatorSet);
this.authenticatorSet = authenticatorSet;
}
//~--- methods --------------------------------------------------------------
@@ -82,41 +95,37 @@ public class XmlAuthenticator implements Authenticator
* @return
*/
@Override
public User authenticate(HttpServletRequest request,
HttpServletResponse response, String username,
String password)
public AuthenticationResult authenticate(HttpServletRequest request,
HttpServletResponse response, String username, String password)
{
User user = userManager.get(username);
AuthenticationResult result = null;
if (user != null)
for (AuthenticationManager authenticator : authenticatorSet)
{
String encryptedPassword = encryptionHandler.encrypt(password);
if (!encryptedPassword.equalsIgnoreCase(user.getPassword()))
try
{
user = null;
result = authenticator.authenticate(request, response, username,
password);
if (logger.isDebugEnabled())
{
logger.debug("password for user {} is wrong", username);
logger.debug("authenticator {} ends with result, {}",
authenticator.getClass().getName(), result);
}
}
else
{
if (logger.isDebugEnabled())
if (((result != null) && result.getState().isSuccessfully())
|| (result.getState() == AuthenticationState.FAILED))
{
logger.debug("user {} logged in successfully", username);
break;
}
user.setPassword(null);
}
catch (Exception ex)
{
logger.error(ex.getMessage(), ex);
}
}
else if (logger.isDebugEnabled())
{
logger.debug("could not find user {}", username);
}
return user;
return result;
}
/**
@@ -128,30 +137,29 @@ public class XmlAuthenticator implements Authenticator
@Override
public void close() throws IOException
{
// do nothing
for (AuthenticationManager authenticator : authenticatorSet)
{
IOUtil.close(authenticator);
}
}
/**
* Method description
*
*
* @param provider
* @param context
*/
@Override
public void init(SCMContextProvider provider)
public void init(SCMContextProvider context)
{
// do nothing
for (AuthenticationManager authenticator : authenticatorSet)
{
authenticator.init(context);
}
}
//~--- fields ---------------------------------------------------------------
/** Field description */
@Inject
private EncryptionHandler encryptionHandler;
/** Field description */
@Inject
private UserManager userManager;
private Set<AuthenticationManager> authenticatorSet;
}

View File

@@ -0,0 +1,214 @@
/**
* Copyright (c) 2010, Sebastian Sdorra
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of SCM-Manager; nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* http://bitbucket.org/sdorra/scm-manager
*
*/
package sonia.scm.web.security;
//~--- non-JDK imports --------------------------------------------------------
import com.google.inject.Inject;
import com.google.inject.Singleton;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sonia.scm.SCMContextProvider;
import sonia.scm.security.EncryptionHandler;
import sonia.scm.user.User;
import sonia.scm.user.UserManager;
//~--- JDK imports ------------------------------------------------------------
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* @author Sebastian Sdorra
*/
@Singleton
public class XmlAuthenticationManager implements AuthenticationManager
{
/** Field description */
public static final String NAME_DIRECTORY = "users";
/** Field description */
public static final String TYPE = "xml";
/** the logger for XmlAuthenticationManager */
private static final Logger logger =
LoggerFactory.getLogger(XmlAuthenticationManager.class);
//~--- constructors ---------------------------------------------------------
/**
* Constructs ...
*
*
* @param userManager
* @param encryptionHandler
*/
@Inject
public XmlAuthenticationManager(UserManager userManager,
EncryptionHandler encryptionHandler)
{
this.userManager = userManager;
this.encryptionHandler = encryptionHandler;
}
//~--- methods --------------------------------------------------------------
/**
* Method description
*
*
* @param request
* @param response
* @param username
* @param password
*
* @return
*/
@Override
public AuthenticationResult authenticate(HttpServletRequest request,
HttpServletResponse response, String username, String password)
{
AuthenticationResult result = null;
User user = userManager.get(username);
if (user != null)
{
if (TYPE.equals(user.getType()))
{
result = authenticate(user, username, password);
}
else
{
if (logger.isDebugEnabled())
{
logger.debug("{} is not an xml user", username);
}
result = AuthenticationResult.NEXT;
}
}
else
{
if (logger.isDebugEnabled())
{
logger.debug("could not find user {}", username);
}
result = AuthenticationResult.NEXT;
}
return result;
}
/**
* Method description
*
*
* @throws IOException
*/
@Override
public void close() throws IOException
{
// do nothing
}
/**
* Method description
*
*
* @param provider
*/
@Override
public void init(SCMContextProvider provider)
{
// do nothing
}
/**
* Method description
*
*
* @param user
* @param username
* @param password
*
* @return
*/
private AuthenticationResult authenticate(User user, String username,
String password)
{
AuthenticationResult result = null;
String encryptedPassword = encryptionHandler.encrypt(password);
if (!encryptedPassword.equalsIgnoreCase(user.getPassword()))
{
user = null;
if (logger.isDebugEnabled())
{
logger.debug("password for user {} is wrong", username);
}
result = AuthenticationResult.FAILED;
}
else
{
if (logger.isDebugEnabled())
{
logger.debug("user {} logged in successfully", username);
}
user.setPassword(null);
result = new AuthenticationResult(user, AuthenticationState.SUCCESS);
}
return result;
}
//~--- fields ---------------------------------------------------------------
/** Field description */
private EncryptionHandler encryptionHandler;
/** Field description */
private UserManager userManager;
}

View File

@@ -46,7 +46,8 @@ import sonia.scm.plugin.ext.Extension;
import sonia.scm.plugin.ext.ExtensionProcessor;
import sonia.scm.repository.RepositoryHandler;
import sonia.scm.security.EncryptionHandler;
import sonia.scm.web.security.Authenticator;
import sonia.scm.web.security.AuthenticationManager;
import sonia.scm.web.security.XmlAuthenticationManager;
//~--- JDK imports ------------------------------------------------------------
@@ -90,6 +91,10 @@ public class BindingExtensionProcessor implements ExtensionProcessor
{
Multibinder<RepositoryHandler> repositoryHandlers =
Multibinder.newSetBinder(binder, RepositoryHandler.class);
Multibinder<AuthenticationManager> authenticators =
Multibinder.newSetBinder(binder, AuthenticationManager.class);
authenticators.addBinding().to(XmlAuthenticationManager.class);
for (Class extensionClass : extensions)
{
@@ -103,17 +108,21 @@ public class BindingExtensionProcessor implements ExtensionProcessor
}
binder.bind(extensionClass);
repositoryHandlers.addBinding().to(extensionClass);
}
else if (EncryptionHandler.class.isAssignableFrom(extensionClass))
{
bind(binder, EncryptionHandler.class, extensionClass);
}
else if (Authenticator.class.isAssignableFrom(extensionClass))
else if (AuthenticationManager.class.isAssignableFrom(extensionClass))
{
bind(binder, Authenticator.class, extensionClass);
if (logger.isInfoEnabled())
{
logger.info("bind Authenticator {}", extensionClass.getName());
}
binder.bind(extensionClass);
authenticators.addBinding().to(extensionClass);
}
else
{

View File

@@ -44,13 +44,16 @@ import sonia.scm.plugin.DefaultPluginManager;
import sonia.scm.plugin.PluginManager;
import sonia.scm.repository.RepositoryManager;
import sonia.scm.user.UserManager;
import sonia.scm.web.security.Authenticator;
import sonia.scm.util.IOUtil;
import sonia.scm.web.security.AuthenticationManager;
//~--- JDK imports ------------------------------------------------------------
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletContextEvent;
/**
*
* @author Sebastian Sdorra
@@ -58,6 +61,33 @@ import java.util.List;
public class ContextListener extends GuiceServletContextListener
{
/**
* Method description
*
*
* @param servletContextEvent
*/
@Override
public void contextDestroyed(ServletContextEvent servletContextEvent)
{
if (injector != null)
{
// close RepositoryManager
IOUtil.close(injector.getInstance(RepositoryManager.class));
// close Authenticator
IOUtil.close(injector.getInstance(AuthenticationManager.class));
// close UserManager
IOUtil.close(injector.getInstance(UserManager.class));
}
super.contextDestroyed(servletContextEvent);
}
//~--- get methods ----------------------------------------------------------
/**
* Method description
*
@@ -78,8 +108,7 @@ public class ContextListener extends GuiceServletContextListener
new ArrayList<Module>(bindExtProcessor.getModuleSet());
moduleList.add(0, main);
Injector injector = Guice.createInjector(moduleList);
injector = Guice.createInjector(moduleList);
// init RepositoryManager
injector.getInstance(RepositoryManager.class).init(SCMContext.getContext());
@@ -88,8 +117,14 @@ public class ContextListener extends GuiceServletContextListener
injector.getInstance(UserManager.class).init(SCMContext.getContext());
// init Authenticator
injector.getInstance(Authenticator.class).init(SCMContext.getContext());
injector.getInstance(AuthenticationManager.class).init(
SCMContext.getContext());
return injector;
}
//~--- fields ---------------------------------------------------------------
/** Field description */
private Injector injector;
}

View File

@@ -56,10 +56,10 @@ import sonia.scm.security.SecurityContext;
import sonia.scm.user.UserManager;
import sonia.scm.user.xml.XmlUserManager;
import sonia.scm.util.DebugServlet;
import sonia.scm.web.security.Authenticator;
import sonia.scm.web.security.AuthenticationManager;
import sonia.scm.web.security.BasicSecurityContext;
import sonia.scm.web.security.ChainAuthenticatonManager;
import sonia.scm.web.security.WebSecurityContext;
import sonia.scm.web.security.XmlAuthenticator;
//~--- JDK imports ------------------------------------------------------------
@@ -155,10 +155,14 @@ public class ScmServletModule extends ServletModule
bind(ScmConfiguration.class).toInstance(config);
bind(PluginManager.class).toInstance(pluginManager);
bind(EncryptionHandler.class).to(MessageDigestEncryptionHandler.class);
bind(Authenticator.class).to(XmlAuthenticator.class);
bindExtProcessor.bindExtensions(binder());
// bind security stuff
bind(AuthenticationManager.class).to(ChainAuthenticatonManager.class);
bind(SecurityContext.class).to(BasicSecurityContext.class);
bind(WebSecurityContext.class).to(BasicSecurityContext.class);
bindExtProcessor.bindExtensions(binder());
// bind security cache
bind(CacheManager.class).to(EhCacheManager.class);
// bind(RepositoryManager.class).annotatedWith(Undecorated.class).to(