Reverted mess of eclipse formatting.

This commit is contained in:
Clemens Rabe
2013-10-15 20:57:38 +02:00
parent 13bd150c6f
commit 814b940998
2 changed files with 459 additions and 403 deletions

View File

@@ -29,6 +29,8 @@
* *
*/ */
package sonia.scm.web.filter; package sonia.scm.web.filter;
//~--- non-JDK imports -------------------------------------------------------- //~--- non-JDK imports --------------------------------------------------------
@@ -41,6 +43,7 @@ import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException; import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken; import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject; import org.apache.shiro.subject.Subject;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@@ -65,195 +68,218 @@ import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
/** /**
* *
* @author Sebastian Sdorra * @author Sebastian Sdorra
*/ */
@Singleton @Singleton
public class BasicAuthenticationFilter extends AutoLoginFilter { public class BasicAuthenticationFilter extends AutoLoginFilter
{
/** Field description */ /** Field description */
public static final String AUTHORIZATION_BASIC_PREFIX = "BASIC"; public static final String AUTHORIZATION_BASIC_PREFIX = "BASIC";
/** Field description */ /** Field description */
public static final String CREDENTIAL_SEPARATOR = ":"; public static final String CREDENTIAL_SEPARATOR = ":";
/** Field description */ /** Field description */
public static final String HEADER_AUTHORIZATION = "Authorization"; public static final String HEADER_AUTHORIZATION = "Authorization";
/** the logger for BasicAuthenticationFilter */ /** the logger for BasicAuthenticationFilter */
private static final Logger logger = LoggerFactory private static final Logger logger =
.getLogger(BasicAuthenticationFilter.class); LoggerFactory.getLogger(BasicAuthenticationFilter.class);
// ~--- constructors //~--- constructors ---------------------------------------------------------
// ---------------------------------------------------------
/** /**
* Constructs ... * Constructs ...
* *
* *
* @param securityContextProvider * @param securityContextProvider
* @deprecated use the constructor with out arguments instead. * @deprecated use the constructor with out arguments instead.
*/ */
@Deprecated @Deprecated
public BasicAuthenticationFilter( public BasicAuthenticationFilter(
Provider<WebSecurityContext> securityContextProvider) { Provider<WebSecurityContext> securityContextProvider) {}
}
/** /**
* Constructs a new basic authenticaton filter * Constructs a new basic authenticaton filter
* *
* @param configuration * @param configuration scm-manager global configuration
* scm-manager global configuration *
* * @since 1.21
* @since 1.21 */
*/ @Inject
@Inject public BasicAuthenticationFilter(ScmConfiguration configuration,
public BasicAuthenticationFilter(ScmConfiguration configuration, Set<AutoLoginModule> autoLoginModules)
Set<AutoLoginModule> autoLoginModules) { {
super(autoLoginModules); super(autoLoginModules);
this.configuration = configuration; this.configuration = configuration;
} }
// ~--- methods //~--- methods --------------------------------------------------------------
// --------------------------------------------------------------
/** /**
* Method description * Method description
* *
* *
* @param request * @param request
* @param response * @param response
* @param chain * @param chain
* *
* @throws IOException * @throws IOException
* @throws ServletException * @throws ServletException
*/ */
@Override @Override
protected void doFilter(HttpServletRequest request, protected void doFilter(HttpServletRequest request,
HttpServletResponse response, FilterChain chain) HttpServletResponse response, FilterChain chain)
throws IOException, ServletException { throws IOException, ServletException
Subject subject = SecurityUtils.getSubject(); {
User user = getAuthenticatedUser(request, response); Subject subject = SecurityUtils.getSubject();
User user = getAuthenticatedUser(request, response);
// Fallback to basic authentication scheme // Fallback to basic authentication scheme
if (user == null) { if (user == null)
String authentication = request.getHeader(HEADER_AUTHORIZATION); {
String authentication = request.getHeader(HEADER_AUTHORIZATION);
if (Util.startWithIgnoreCase(authentication, if (Util.startWithIgnoreCase(authentication, AUTHORIZATION_BASIC_PREFIX))
AUTHORIZATION_BASIC_PREFIX)) { {
if (logger.isTraceEnabled()) { if (logger.isTraceEnabled())
logger.trace("found basic authorization header, start authentication"); {
} logger.trace("found basic authorization header, start authentication");
}
user = authenticate(request, response, subject, authentication); user = authenticate(request, response, subject, authentication);
if (logger.isTraceEnabled()) { if (logger.isTraceEnabled())
if (user != null) { {
logger.trace("user {} successfully authenticated", if (user != null)
user.getName()); {
} else { logger.trace("user {} successfully authenticated", user.getName());
logger.trace("authentcation failed, user object is null"); }
} else
} {
} else if ((configuration != null) logger.trace("authentcation failed, user object is null");
&& configuration.isAnonymousAccessEnabled()) { }
if (logger.isTraceEnabled()) { }
logger.trace("anonymous access granted"); }
} else if ((configuration != null)
&& configuration.isAnonymousAccessEnabled())
{
if (logger.isTraceEnabled())
{
logger.trace("anonymous access granted");
}
user = SCMContext.ANONYMOUS; user = SCMContext.ANONYMOUS;
} }
} }
if (user == null) { if (user == null)
if (logger.isTraceEnabled()) { {
logger.trace("could not find user send unauthorized"); if (logger.isTraceEnabled())
} {
logger.trace("could not find user send unauthorized");
}
handleUnauthorized(request, response, chain); handleUnauthorized(request, response, chain);
} else { }
chain.doFilter( else
new SecurityHttpServletRequestWrapper(request, user), {
response); chain.doFilter(new SecurityHttpServletRequestWrapper(request, user),
} response);
} }
}
/** /**
* Method description * Method description
* *
* *
* @param request * @param request
* @param response * @param response
* @param chain * @param chain
* *
* @throws IOException * @throws IOException
* @throws ServletException * @throws ServletException
* *
* @since 1.8 * @since 1.8
*/ */
protected void handleUnauthorized(HttpServletRequest request, protected void handleUnauthorized(HttpServletRequest request,
HttpServletResponse response, FilterChain chain) HttpServletResponse response, FilterChain chain)
throws IOException, ServletException { throws IOException, ServletException
HttpUtil.sendUnauthorized(request, response); {
} HttpUtil.sendUnauthorized(request, response);
}
/** /**
* Method description * Method description
* *
* *
* @param request * @param request
* @param response * @param response
* @param securityContext * @param securityContext
* @param subject * @param subject
* @param authentication * @param authentication
* *
* @return * @return
*/ */
private User authenticate(HttpServletRequest request, private User authenticate(HttpServletRequest request,
HttpServletResponse response, Subject subject, String authentication) { HttpServletResponse response, Subject subject, String authentication)
String token = authentication.substring(6); {
String token = authentication.substring(6);
token = new String(Base64.decode(token.getBytes())); token = new String(Base64.decode(token.getBytes()));
int index = token.indexOf(CREDENTIAL_SEPARATOR); int index = token.indexOf(CREDENTIAL_SEPARATOR);
User user = null; User user = null;
if ((index > 0) && (index < token.length())) { if ((index > 0) && (index < token.length()))
String username = token.substring(0, index); {
String password = token.substring(index + 1); String username = token.substring(0, index);
String password = token.substring(index + 1);
if (Util.isNotEmpty(username) && Util.isNotEmpty(password)) { if (Util.isNotEmpty(username) && Util.isNotEmpty(password))
if (logger.isTraceEnabled()) { {
logger.trace("try to authenticate user {}", username); if (logger.isTraceEnabled())
} {
logger.trace("try to authenticate user {}", username);
}
try { try
{
subject.login(new UsernamePasswordToken(username, password, subject.login(new UsernamePasswordToken(username, password,
request.getRemoteAddr())); request.getRemoteAddr()));
user = subject.getPrincipals().oneByType(User.class); user = subject.getPrincipals().oneByType(User.class);
} catch (AuthenticationException ex) { }
if (logger.isTraceEnabled()) { catch (AuthenticationException ex)
logger.trace("authentication failed for user " {
.concat(username), ex); if (logger.isTraceEnabled())
} else if (logger.isWarnEnabled()) { {
logger.warn("authentication failed for user {}", logger.trace("authentication failed for user ".concat(username),
username); ex);
} }
} else if (logger.isWarnEnabled())
} else if (logger.isWarnEnabled()) { {
logger.warn("username or password is null/empty"); logger.warn("authentication failed for user {}", username);
} }
} else if (logger.isWarnEnabled()) { }
logger.warn("failed to read basic auth credentials"); }
} else if (logger.isWarnEnabled())
{
logger.warn("username or password is null/empty");
}
}
else if (logger.isWarnEnabled())
{
logger.warn("failed to read basic auth credentials");
}
return user; return user;
} }
// ~--- fields //~--- fields ---------------------------------------------------------------
// ---------------------------------------------------------------
/** Field description */ /** Field description */
private ScmConfiguration configuration; private ScmConfiguration configuration;
} }

View File

@@ -29,6 +29,8 @@
* *
*/ */
package sonia.scm.web.security; package sonia.scm.web.security;
//~--- non-JDK imports -------------------------------------------------------- //~--- non-JDK imports --------------------------------------------------------
@@ -64,296 +66,324 @@ import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
/** /**
* *
* @author Sebastian Sdorra * @author Sebastian Sdorra
*/ */
@Singleton @Singleton
public class ChainAuthenticatonManager extends AbstractAuthenticationManager { public class ChainAuthenticatonManager extends AbstractAuthenticationManager
{
/** Field description */ /** Field description */
public static final String CACHE_NAME = "sonia.cache.auth"; public static final String CACHE_NAME = "sonia.cache.auth";
/** the logger for ChainAuthenticatonManager */ /** the logger for ChainAuthenticatonManager */
private static final Logger logger = LoggerFactory private static final Logger logger =
.getLogger(ChainAuthenticatonManager.class); LoggerFactory.getLogger(ChainAuthenticatonManager.class);
// ~--- constructors //~--- constructors ---------------------------------------------------------
// ---------------------------------------------------------
/** /**
* Constructs ... * Constructs ...
* *
* *
* *
* @param userManager * @param userManager
* @param authenticationHandlerSet * @param authenticationHandlerSet
* @param encryptionHandler * @param encryptionHandler
* @param cacheManager * @param cacheManager
* @param authenticationListenerProvider * @param authenticationListenerProvider
* @param authenticationListeners * @param authenticationListeners
*/ */
@Inject @Inject
public ChainAuthenticatonManager(UserManager userManager, public ChainAuthenticatonManager(UserManager userManager,
Set<AuthenticationHandler> authenticationHandlerSet, Set<AuthenticationHandler> authenticationHandlerSet,
EncryptionHandler encryptionHandler, CacheManager cacheManager, EncryptionHandler encryptionHandler, CacheManager cacheManager,
Set<AuthenticationListener> authenticationListeners) { Set<AuthenticationListener> authenticationListeners)
AssertUtil.assertIsNotEmpty(authenticationHandlerSet); {
AssertUtil.assertIsNotNull(cacheManager); AssertUtil.assertIsNotEmpty(authenticationHandlerSet);
this.authenticationHandlers = sort(userManager, AssertUtil.assertIsNotNull(cacheManager);
authenticationHandlerSet); this.authenticationHandlers = sort(userManager, authenticationHandlerSet);
this.encryptionHandler = encryptionHandler; this.encryptionHandler = encryptionHandler;
this.cache = cacheManager.getCache(String.class, this.cache = cacheManager.getCache(String.class,
AuthenticationCacheValue.class, CACHE_NAME); AuthenticationCacheValue.class, CACHE_NAME);
if (Util.isNotEmpty(authenticationListeners)) { if (Util.isNotEmpty(authenticationListeners))
addListeners(authenticationListeners); {
} addListeners(authenticationListeners);
} }
}
// ~--- methods //~--- methods --------------------------------------------------------------
// --------------------------------------------------------------
/** /**
* Method description * Method description
* *
* *
* @param request * @param request
* @param response * @param response
* @param username * @param username
* @param password * @param password
* *
* @return * @return
*/ */
@Override @Override
public AuthenticationResult authenticate(HttpServletRequest request, public AuthenticationResult authenticate(HttpServletRequest request,
HttpServletResponse response, String username, String password) { HttpServletResponse response, String username, String password)
AssertUtil.assertIsNotEmpty(username); {
AssertUtil.assertIsNotEmpty(password); AssertUtil.assertIsNotEmpty(username);
AssertUtil.assertIsNotEmpty(password);
String encryptedPassword = encryptionHandler.encrypt(password); String encryptedPassword = encryptionHandler.encrypt(password);
AuthenticationResult ar = getCached(username, encryptedPassword); AuthenticationResult ar = getCached(username, encryptedPassword);
if (ar == null) { if (ar == null)
if (logger.isTraceEnabled()) { {
logger.trace( if (logger.isTraceEnabled())
"no authentication result for user {} found in cache", {
username); logger.trace("no authentication result for user {} found in cache",
} username);
}
ar = doAuthentication(request, response, username, password); ar = doAuthentication(request, response, username, password);
if ((ar != null) && ar.isCacheable()) { if ((ar != null) && ar.isCacheable())
cache.put(username, new AuthenticationCacheValue(ar, {
encryptedPassword)); cache.put(username,
} new AuthenticationCacheValue(ar, encryptedPassword));
} else if (logger.isDebugEnabled()) { }
logger.debug("authenticate {} via cache", username); }
} else if (logger.isDebugEnabled())
{
logger.debug("authenticate {} via cache", username);
}
return ar; return ar;
} }
/** /**
* Method description * Method description
* *
* *
* @throws IOException * @throws IOException
*/ */
@Override @Override
public void close() throws IOException { public void close() throws IOException
for (AuthenticationHandler authenticator : authenticationHandlers) { {
if (logger.isTraceEnabled()) { for (AuthenticationHandler authenticator : authenticationHandlers)
logger.trace("close authenticator {}", authenticator.getClass()); {
} if (logger.isTraceEnabled())
{
logger.trace("close authenticator {}", authenticator.getClass());
}
IOUtil.close(authenticator); IOUtil.close(authenticator);
} }
} }
/** /**
* Method description * Method description
* *
* *
* @param context * @param context
*/ */
@Override @Override
public void init(SCMContextProvider context) { public void init(SCMContextProvider context)
for (AuthenticationHandler authenticator : authenticationHandlers) { {
if (logger.isTraceEnabled()) { for (AuthenticationHandler authenticator : authenticationHandlers)
logger.trace("initialize authenticator {}", {
authenticator.getClass()); if (logger.isTraceEnabled())
} {
logger.trace("initialize authenticator {}", authenticator.getClass());
}
authenticator.init(context); authenticator.init(context);
} }
} }
/** /**
* Method description * Method description
* *
* *
* @param request * @param request
* @param response * @param response
* @param username * @param username
* @param password * @param password
* *
* @return * @return
*/ */
private AuthenticationResult doAuthentication(HttpServletRequest request, private AuthenticationResult doAuthentication(HttpServletRequest request,
HttpServletResponse response, String username, String password) { HttpServletResponse response, String username, String password)
AuthenticationResult ar = null; {
AuthenticationResult ar = null;
if (logger.isTraceEnabled()) { if (logger.isTraceEnabled())
logger.trace("start authentication chain for user {}", username); {
} logger.trace("start authentication chain for user {}", username);
}
for (AuthenticationHandler authenticator : authenticationHandlers) { for (AuthenticationHandler authenticator : authenticationHandlers)
if (logger.isTraceEnabled()) { {
logger.trace("check authenticator {} for user {}", if (logger.isTraceEnabled())
authenticator.getClass(), username); {
} logger.trace("check authenticator {} for user {}",
authenticator.getClass(), username);
}
try { try
AuthenticationResult result = authenticator.authenticate( {
request, response, username, password); AuthenticationResult result = authenticator.authenticate(request,
response, username, password);
if (logger.isDebugEnabled()) { if (logger.isDebugEnabled())
logger.debug("authenticator {} ends with result, {}", {
authenticator.getClass().getName(), result); logger.debug("authenticator {} ends with result, {}",
} authenticator.getClass().getName(), result);
}
// CR: Removed check on state=failed to allow next module to // CR: Removed check on state=failed to allow next module to
// continue // continue
if ((result != null) && (result.getState() != null) if ((result != null) && (result.getState() != null)
&& result.getState().isSuccessfully()) { && result.getState().isSuccessfully())
if (result.getUser() != null) { {
User user = result.getUser(); if (result.getUser() != null)
{
User user = result.getUser();
user.setType(authenticator.getType()); user.setType(authenticator.getType());
ar = result; ar = result;
// notify authentication listeners // notify authentication listeners
fireAuthenticationEvent(request, response, user); fireAuthenticationEvent(request, response, user);
} }
break; break;
} }
} catch (Exception ex) { }
logger.error("error durring authentication process of " catch (Exception ex)
.concat(authenticator.getClass().getName()), ex); {
} logger.error(
} "error durring authentication process of ".concat(
authenticator.getClass().getName()), ex);
}
}
return ar; return ar;
} }
/** /**
* Method description * Method description
* *
* *
* @param userManager * @param userManager
* @param authenticationHandlerSet * @param authenticationHandlerSet
* *
* @return * @return
*/ */
@VisibleForTesting @VisibleForTesting
private List<AuthenticationHandler> sort(UserManager userManager, private List<AuthenticationHandler> sort(UserManager userManager,
Set<AuthenticationHandler> authenticationHandlerSet) { Set<AuthenticationHandler> authenticationHandlerSet)
List<AuthenticationHandler> handlers = Lists {
.newArrayListWithCapacity(authenticationHandlerSet.size()); List<AuthenticationHandler> handlers =
Lists.newArrayListWithCapacity(authenticationHandlerSet.size());
String first = Strings.nullToEmpty(userManager.getDefaultType()); String first = Strings.nullToEmpty(userManager.getDefaultType());
for (AuthenticationHandler handler : authenticationHandlerSet) { for (AuthenticationHandler handler : authenticationHandlerSet)
if (first.equals(handler.getType())) { {
handlers.add(0, handler); if (first.equals(handler.getType()))
} else { {
handlers.add(handler); handlers.add(0, handler);
} }
} else
{
handlers.add(handler);
}
}
return handlers; return handlers;
} }
// ~--- get methods //~--- get methods ----------------------------------------------------------
// ----------------------------------------------------------
/** /**
* Method description * Method description
* *
* *
* @param username * @param username
* @param encryptedPassword * @param encryptedPassword
* *
* @return * @return
*/ */
private AuthenticationResult getCached(String username, private AuthenticationResult getCached(String username,
String encryptedPassword) { String encryptedPassword)
AuthenticationResult result = null; {
AuthenticationCacheValue value = cache.get(username); AuthenticationResult result = null;
AuthenticationCacheValue value = cache.get(username);
if (value != null) { if (value != null)
String cachedPassword = value.password; {
String cachedPassword = value.password;
if (cachedPassword.equals(encryptedPassword)) { if (cachedPassword.equals(encryptedPassword))
result = value.authenticationResult; {
} result = value.authenticationResult;
} }
}
return result; return result;
} }
// ~--- inner classes //~--- inner classes --------------------------------------------------------
// --------------------------------------------------------
/** /**
* Class description * Class description
* *
* *
* @version Enter version here..., 2011-01-15 * @version Enter version here..., 2011-01-15
* @author Sebastian Sdorra * @author Sebastian Sdorra
*/ */
private static class AuthenticationCacheValue implements Serializable { private static class AuthenticationCacheValue implements Serializable
{
/** Field description */ /** Field description */
private static final long serialVersionUID = 2201116145941277549L; private static final long serialVersionUID = 2201116145941277549L;
// ~--- constructors //~--- constructors -------------------------------------------------------
// -------------------------------------------------------
/** /**
* Constructs ... * Constructs ...
* *
* *
* *
* @param ar * @param ar
* @param password * @param password
*/ */
public AuthenticationCacheValue(AuthenticationResult ar, String password) { public AuthenticationCacheValue(AuthenticationResult ar, String password)
this.authenticationResult = new AuthenticationResult(ar.getUser() {
.clone(), ar.getGroups(), ar.getState()); this.authenticationResult =
this.password = password; new AuthenticationResult(ar.getUser().clone(), ar.getGroups(),
} ar.getState());
this.password = password;
}
// ~--- fields //~--- fields -------------------------------------------------------------
// -------------------------------------------------------------
/** Field description */ /** Field description */
private AuthenticationResult authenticationResult; private AuthenticationResult authenticationResult;
/** Field description */ /** Field description */
private String password; private String password;
} }
// ~--- fields
// ---------------------------------------------------------------
/** Field description */ //~--- fields ---------------------------------------------------------------
private List<AuthenticationHandler> authenticationHandlers;
/** Field description */ /** Field description */
private Cache<String, AuthenticationCacheValue> cache; private List<AuthenticationHandler> authenticationHandlers;
/** Field description */ /** Field description */
private EncryptionHandler encryptionHandler; private Cache<String, AuthenticationCacheValue> cache;
/** Field description */
private EncryptionHandler encryptionHandler;
} }