initial implementation

This commit is contained in:
Konstantin Schaper
2020-08-20 17:44:36 +02:00
parent 330f7c500e
commit 44edb48771
6 changed files with 205 additions and 14 deletions

View File

@@ -67,6 +67,7 @@ public class AuthenticationFilter extends HttpFilter {
*/ */
private static final String ATTRIBUTE_FAILED_AUTH = "sonia.scm.auth.failed"; private static final String ATTRIBUTE_FAILED_AUTH = "sonia.scm.auth.failed";
private final Set<WebTokenGenerator> tokenGenerators; private final Set<WebTokenGenerator> tokenGenerators;
protected ScmConfiguration configuration; protected ScmConfiguration configuration;
@@ -117,7 +118,7 @@ public class AuthenticationFilter extends HttpFilter {
} }
/** /**
* Sends status code 403 back to client, if the authentication has failed. * Sends status code 401 back to client, if the authentication has failed.
* In all other cases the method will send status code 403 back to client. * In all other cases the method will send status code 403 back to client.
* *
* @param request servlet request * @param request servlet request
@@ -209,12 +210,8 @@ public class AuthenticationFilter extends HttpFilter {
subject.login(token); subject.login(token);
processChain(request, response, chain, subject); processChain(request, response, chain, subject);
} catch (TokenExpiredException ex) { } catch (TokenExpiredException ex) {
if (logger.isTraceEnabled()) { // Rethrow to be caught by TokenExpiredFilter
logger.trace("{} expired", token.getClass(), ex); throw ex;
} else {
logger.debug("{} expired", token.getClass());
}
handleUnauthorized(request, response, chain);
} catch (AuthenticationException ex) { } catch (AuthenticationException ex) {
logger.warn("authentication failed", ex); logger.warn("authentication failed", ex);
handleUnauthorized(request, response, chain); handleUnauthorized(request, response, chain);

View File

@@ -120,7 +120,12 @@ function handleFailure(response: Response) {
if (!response.ok) { if (!response.ok) {
if (isBackendError(response)) { if (isBackendError(response)) {
return response.json().then((content: BackendErrorContent) => { return response.json().then((content: BackendErrorContent) => {
if (content.errorCode === "DDS8D8unr1") {
window.location.replace(`${contextPath}/login`);
throw new UnauthorizedError("Unauthorized", 401);
} else {
throw createBackendError(content, response.status); throw createBackendError(content, response.status);
}
}); });
} else { } else {
if (response.status === 401) { if (response.status === 401) {

View File

@@ -28,8 +28,11 @@ package sonia.scm.lifecycle.modules;
import com.google.inject.name.Names; import com.google.inject.name.Names;
import org.apache.shiro.authc.Authenticator;
import org.apache.shiro.authc.credential.DefaultPasswordService; import org.apache.shiro.authc.credential.DefaultPasswordService;
import org.apache.shiro.authc.credential.PasswordService; import org.apache.shiro.authc.credential.PasswordService;
import org.apache.shiro.authc.pam.AuthenticationStrategy;
import org.apache.shiro.authc.pam.ModularRealmAuthenticator;
import org.apache.shiro.crypto.hash.DefaultHashService; import org.apache.shiro.crypto.hash.DefaultHashService;
import org.apache.shiro.guice.web.ShiroWebModule; import org.apache.shiro.guice.web.ShiroWebModule;
import org.apache.shiro.realm.Realm; import org.apache.shiro.realm.Realm;
@@ -44,6 +47,7 @@ import sonia.scm.plugin.ExtensionProcessor;
import javax.servlet.ServletContext; import javax.servlet.ServletContext;
import org.apache.shiro.mgt.RememberMeManager; import org.apache.shiro.mgt.RememberMeManager;
import sonia.scm.security.DisabledRememberMeManager; import sonia.scm.security.DisabledRememberMeManager;
import sonia.scm.security.ScmAtLeastOneSuccessfulStrategy;
/** /**
* *
@@ -94,6 +98,11 @@ public class ScmSecurityModule extends ShiroWebModule
// disable remember me cookie generation // disable remember me cookie generation
bind(RememberMeManager.class).to(DisabledRememberMeManager.class); bind(RememberMeManager.class).to(DisabledRememberMeManager.class);
// bind authentication strategy
bind(ModularRealmAuthenticator.class);
bind(Authenticator.class).to(ModularRealmAuthenticator.class);
bind(AuthenticationStrategy.class).to(ScmAtLeastOneSuccessfulStrategy.class);
// bind realm // bind realm
for (Class<? extends Realm> realm : extensionProcessor.byExtensionPoint(Realm.class)) for (Class<? extends Realm> realm : extensionProcessor.byExtensionPoint(Realm.class))
{ {

View File

@@ -52,6 +52,10 @@ public final class DefaultAccessTokenCookieIssuer implements AccessTokenCookieIs
*/ */
private static final Logger LOG = LoggerFactory.getLogger(DefaultAccessTokenCookieIssuer.class); private static final Logger LOG = LoggerFactory.getLogger(DefaultAccessTokenCookieIssuer.class);
private static final int DEFAULT_COOKIE_EXPIRATION_AMOUNT = 24;
private static final TimeUnit DEFAULT_COOKIE_EXPIRATION_UNIT = TimeUnit.HOURS;
private static final int DEFAULT_COOKIE_EXPIRATION = (int) TimeUnit.SECONDS.convert(DEFAULT_COOKIE_EXPIRATION_AMOUNT, DEFAULT_COOKIE_EXPIRATION_UNIT);
private final ScmConfiguration configuration; private final ScmConfiguration configuration;
/** /**
@@ -75,7 +79,7 @@ public final class DefaultAccessTokenCookieIssuer implements AccessTokenCookieIs
LOG.trace("create and attach cookie for access token {}", accessToken.getId()); LOG.trace("create and attach cookie for access token {}", accessToken.getId());
Cookie c = new Cookie(HttpUtil.COOKIE_BEARER_AUTHENTICATION, accessToken.compact()); Cookie c = new Cookie(HttpUtil.COOKIE_BEARER_AUTHENTICATION, accessToken.compact());
c.setPath(contextPath(request)); c.setPath(contextPath(request));
c.setMaxAge(getMaxAge(accessToken)); c.setMaxAge(DEFAULT_COOKIE_EXPIRATION);
c.setHttpOnly(isHttpOnly()); c.setHttpOnly(isHttpOnly());
c.setSecure(isSecure(request)); c.setSecure(isSecure(request));
@@ -111,11 +115,6 @@ public final class DefaultAccessTokenCookieIssuer implements AccessTokenCookieIs
return contextPath; return contextPath;
} }
private int getMaxAge(AccessToken accessToken){
long maxAgeMs = accessToken.getExpiration().getTime() - new Date().getTime();
return (int) TimeUnit.MILLISECONDS.toSeconds(maxAgeMs);
}
private boolean isSecure(HttpServletRequest request){ private boolean isSecure(HttpServletRequest request){
boolean secure = request.isSecure(); boolean secure = request.isSecure();
if (!secure) { if (!secure) {

View File

@@ -0,0 +1,91 @@
/*
* MIT License
*
* Copyright (c) 2020-present Cloudogu GmbH and Contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package sonia.scm.security;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.pam.AbstractAuthenticationStrategy;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.subject.PrincipalCollection;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
public class ScmAtLeastOneSuccessfulStrategy extends AbstractAuthenticationStrategy {
private final ThreadLocal<List<Throwable>> threadLocal = new ThreadLocal<>();
@Override
public AuthenticationInfo beforeAllAttempts(Collection<? extends Realm> realms, AuthenticationToken token) throws AuthenticationException {
this.threadLocal.set(new ArrayList<>());
return super.beforeAllAttempts(realms, token);
}
@Override
public AuthenticationInfo afterAttempt(Realm realm, AuthenticationToken token, AuthenticationInfo singleRealmInfo, AuthenticationInfo aggregateInfo, Throwable t) throws AuthenticationException {
if (t != null) {
this.threadLocal.get().add(t);
}
return super.afterAttempt(realm, token, singleRealmInfo, aggregateInfo, t);
}
@Override
public AuthenticationInfo afterAllAttempts(AuthenticationToken token, AuthenticationInfo aggregate) throws AuthenticationException {
final List<Throwable> throwables = threadLocal.get();
threadLocal.remove();
if (isAuthenticationSuccessful(aggregate)) {
return aggregate;
}
Optional<TokenExpiredException> tokenExpiredException = findTokenExpiredException(throwables);
if (tokenExpiredException.isPresent()) {
throw tokenExpiredException.get();
} else {
throw createAuthenticationException(token);
}
}
private static boolean isAuthenticationSuccessful(AuthenticationInfo aggregate) {
return aggregate != null && isNotEmpty(aggregate.getPrincipals());
}
private static boolean isNotEmpty(PrincipalCollection pc) {
return pc != null && !pc.isEmpty();
}
private static Optional<TokenExpiredException> findTokenExpiredException(List<Throwable> throwables) {
return throwables.stream().filter(t -> t instanceof TokenExpiredException).findFirst().map(t -> (TokenExpiredException) t);
}
private static AuthenticationException createAuthenticationException(AuthenticationToken token) {
return new AuthenticationException("Authentication token of type [" + token.getClass() + "] " +
"could not be authenticated by any configured realms. Please ensure that at least one realm can " +
"authenticate these tokens.");
}
}

View File

@@ -0,0 +1,90 @@
/*
* MIT License
*
* Copyright (c) 2020-present Cloudogu GmbH and Contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package sonia.scm.security;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import sonia.scm.Priority;
import sonia.scm.api.v2.resources.ErrorDto;
import sonia.scm.filter.Filters;
import sonia.scm.filter.WebElement;
import sonia.scm.web.VndMediaType;
import sonia.scm.web.filter.HttpFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebElement("/*")
@Priority(Filters.PRIORITY_PRE_AUTHENTICATION)
@Singleton
public class TokenExpiredFilter extends HttpFilter {
private static final String TOKEN_EXPIRED_ERROR_CODE = "DDS8D8unr1";
private static final Logger LOG = LoggerFactory.getLogger(TokenExpiredFilter.class);
private final AccessTokenCookieIssuer accessTokenCookieIssuer;
private final ObjectMapper objectMapper;
@Inject
public TokenExpiredFilter(AccessTokenCookieIssuer accessTokenCookieIssuer, ObjectMapper objectMapper) {
this.accessTokenCookieIssuer = accessTokenCookieIssuer;
this.objectMapper = objectMapper;
}
@Override
protected void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
try {
chain.doFilter(request, response);
} catch (TokenExpiredException ex) {
if (LOG.isTraceEnabled()) {
LOG.trace("Token expired", ex);
} else {
LOG.debug("Token expired");
}
handleTokenExpired(request, response);
}
}
protected void handleTokenExpired(HttpServletRequest request,
HttpServletResponse response) throws IOException {
accessTokenCookieIssuer.invalidate(request, response);
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
response.setContentType(VndMediaType.ERROR_TYPE);
final ErrorDto errorDto = new ErrorDto();
errorDto.setMessage("Token Expired");
errorDto.setErrorCode(TOKEN_EXPIRED_ERROR_CODE);
errorDto.setTransactionId(MDC.get("transaction_id"));
try (ServletOutputStream stream = response.getOutputStream()) {
objectMapper.writeValue(stream, errorDto);
}
}
}