mirror of
https://github.com/scm-manager/scm-manager.git
synced 2025-11-02 19:45:51 +01:00
introduce api for handling token validation failed exception
This commit is contained in:
committed by
René Pfeuffer
parent
5887c5c268
commit
f2a53644b6
@@ -0,0 +1,51 @@
|
|||||||
|
/*
|
||||||
|
* 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;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Thrown by the {@link AccessTokenResolver} when an {@link AccessTokenValidator} fails to validate an access token.
|
||||||
|
* @since 2.6.2
|
||||||
|
*/
|
||||||
|
@SuppressWarnings("squid:MaximumInheritanceDepth") // exceptions have a deep inheritance depth themselves; therefore we accept this here
|
||||||
|
public class TokenValidationFailedException extends AuthenticationException {
|
||||||
|
private final AccessTokenValidator validator;
|
||||||
|
private final AccessToken accessToken;
|
||||||
|
|
||||||
|
public TokenValidationFailedException(AccessTokenValidator validator, AccessToken accessToken) {
|
||||||
|
super(String.format("Token validator %s failed for access token %s", validator.getClass(), accessToken.getId()));
|
||||||
|
this.validator = validator;
|
||||||
|
this.accessToken = accessToken;
|
||||||
|
}
|
||||||
|
|
||||||
|
public AccessTokenValidator getValidator() {
|
||||||
|
return validator;
|
||||||
|
}
|
||||||
|
|
||||||
|
public AccessToken getAccessToken() {
|
||||||
|
return accessToken;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -39,6 +39,7 @@ import sonia.scm.config.ScmConfiguration;
|
|||||||
import sonia.scm.security.AnonymousMode;
|
import sonia.scm.security.AnonymousMode;
|
||||||
import sonia.scm.security.AnonymousToken;
|
import sonia.scm.security.AnonymousToken;
|
||||||
import sonia.scm.security.TokenExpiredException;
|
import sonia.scm.security.TokenExpiredException;
|
||||||
|
import sonia.scm.security.TokenValidationFailedException;
|
||||||
import sonia.scm.util.HttpUtil;
|
import sonia.scm.util.HttpUtil;
|
||||||
import sonia.scm.util.Util;
|
import sonia.scm.util.Util;
|
||||||
import sonia.scm.web.WebTokenGenerator;
|
import sonia.scm.web.WebTokenGenerator;
|
||||||
@@ -168,9 +169,15 @@ public class AuthenticationFilter extends HttpFilter {
|
|||||||
|
|
||||||
protected void handleTokenExpiredException(HttpServletRequest request, HttpServletResponse response,
|
protected void handleTokenExpiredException(HttpServletRequest request, HttpServletResponse response,
|
||||||
FilterChain chain, TokenExpiredException tokenExpiredException) throws IOException, ServletException {
|
FilterChain chain, TokenExpiredException tokenExpiredException) throws IOException, ServletException {
|
||||||
|
logger.trace("rethrow token expired exception");
|
||||||
throw tokenExpiredException;
|
throw tokenExpiredException;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
protected void handleTokenValidationFailedException(HttpServletRequest request, HttpServletResponse response, FilterChain chain, TokenValidationFailedException tokenValidationFailedException) throws IOException, ServletException {
|
||||||
|
logger.trace("send unauthorized, because of a failed token validation");
|
||||||
|
handleUnauthorized(request, response, chain);
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Iterates all {@link WebTokenGenerator} and creates an
|
* Iterates all {@link WebTokenGenerator} and creates an
|
||||||
* {@link AuthenticationToken} from the given request.
|
* {@link AuthenticationToken} from the given request.
|
||||||
@@ -216,7 +223,11 @@ public class AuthenticationFilter extends HttpFilter {
|
|||||||
processChain(request, response, chain, subject);
|
processChain(request, response, chain, subject);
|
||||||
} catch (TokenExpiredException ex) {
|
} catch (TokenExpiredException ex) {
|
||||||
// Rethrow to be caught by TokenExpiredFilter
|
// Rethrow to be caught by TokenExpiredFilter
|
||||||
|
logger.trace("handle token expired exception");
|
||||||
handleTokenExpiredException(request, response, chain, ex);
|
handleTokenExpiredException(request, response, chain, ex);
|
||||||
|
} catch (TokenValidationFailedException ex) {
|
||||||
|
logger.trace("handle token validation failed exception");
|
||||||
|
handleTokenValidationFailedException(request, response, chain, ex);
|
||||||
} catch (AuthenticationException ex) {
|
} catch (AuthenticationException ex) {
|
||||||
logger.warn("authentication failed", ex);
|
logger.warn("authentication failed", ex);
|
||||||
handleUnauthorized(request, response, chain);
|
handleUnauthorized(request, response, chain);
|
||||||
@@ -259,7 +270,7 @@ public class AuthenticationFilter extends HttpFilter {
|
|||||||
*
|
*
|
||||||
* @return {@code true} if anonymous access is enabled
|
* @return {@code true} if anonymous access is enabled
|
||||||
*/
|
*/
|
||||||
private boolean isAnonymousAccessEnabled() {
|
protected boolean isAnonymousAccessEnabled() {
|
||||||
return (configuration != null) && configuration.getAnonymousMode() != AnonymousMode.OFF;
|
return (configuration != null) && configuration.getAnonymousMode() != AnonymousMode.OFF;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -89,7 +89,7 @@ public final class JwtAccessTokenResolver implements AccessTokenResolver {
|
|||||||
if (!validator.validate(accessToken)) {
|
if (!validator.validate(accessToken)) {
|
||||||
String msg = createValidationFailedMessage(validator, accessToken);
|
String msg = createValidationFailedMessage(validator, accessToken);
|
||||||
LOG.debug(msg);
|
LOG.debug(msg);
|
||||||
throw new AuthenticationException(msg);
|
throw new TokenValidationFailedException(validator, accessToken);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -55,16 +55,16 @@ public class ScmAtLeastOneSuccessfulStrategy extends AbstractAuthenticationStrat
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public AuthenticationInfo afterAllAttempts(AuthenticationToken token, AuthenticationInfo aggregate) throws AuthenticationException {
|
public AuthenticationInfo afterAllAttempts(AuthenticationToken token, AuthenticationInfo aggregate) {
|
||||||
final List<Throwable> throwables = threadLocal.get();
|
final List<Throwable> throwables = threadLocal.get();
|
||||||
threadLocal.remove();
|
threadLocal.remove();
|
||||||
if (isAuthenticationSuccessful(aggregate)) {
|
if (isAuthenticationSuccessful(aggregate)) {
|
||||||
return aggregate;
|
return aggregate;
|
||||||
}
|
}
|
||||||
Optional<TokenExpiredException> tokenExpiredException = findTokenExpiredException(throwables);
|
Optional<? extends AuthenticationException> specializedException = findSpecializedException(throwables);
|
||||||
|
|
||||||
if (tokenExpiredException.isPresent()) {
|
if (specializedException.isPresent()) {
|
||||||
throw tokenExpiredException.get();
|
throw specializedException.get();
|
||||||
} else {
|
} else {
|
||||||
throw createAuthenticationException(token);
|
throw createAuthenticationException(token);
|
||||||
}
|
}
|
||||||
@@ -82,6 +82,18 @@ public class ScmAtLeastOneSuccessfulStrategy extends AbstractAuthenticationStrat
|
|||||||
return throwables.stream().filter(t -> t instanceof TokenExpiredException).findFirst().map(t -> (TokenExpiredException) t);
|
return throwables.stream().filter(t -> t instanceof TokenExpiredException).findFirst().map(t -> (TokenExpiredException) t);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static Optional<AuthenticationException> findTokenValidationFailedException(List<Throwable> throwables) {
|
||||||
|
return throwables.stream().filter(t -> t instanceof TokenValidationFailedException).findFirst().map(t -> (TokenValidationFailedException) t);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Optional<? extends AuthenticationException> findSpecializedException(List<Throwable> throwables) {
|
||||||
|
Optional<TokenExpiredException> tokenExpiredException = findTokenExpiredException(throwables);
|
||||||
|
if (tokenExpiredException.isPresent()) {
|
||||||
|
return tokenExpiredException;
|
||||||
|
}
|
||||||
|
return findTokenValidationFailedException(throwables);
|
||||||
|
}
|
||||||
|
|
||||||
private static AuthenticationException createAuthenticationException(AuthenticationToken token) {
|
private static AuthenticationException createAuthenticationException(AuthenticationToken token) {
|
||||||
return new AuthenticationException("Authentication token of type [" + token.getClass() + "] " +
|
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 " +
|
"could not be authenticated by any configured realms. Please ensure that at least one realm can " +
|
||||||
|
|||||||
@@ -110,7 +110,7 @@ public class JwtAccessTokenResolverTest {
|
|||||||
when(validator.validate(Mockito.any(AccessToken.class))).thenReturn(false);
|
when(validator.validate(Mockito.any(AccessToken.class))).thenReturn(false);
|
||||||
|
|
||||||
// expect exception
|
// expect exception
|
||||||
expectedException.expect(AuthenticationException.class);
|
expectedException.expect(TokenValidationFailedException.class);
|
||||||
expectedException.expectMessage(Matchers.containsString("token"));
|
expectedException.expectMessage(Matchers.containsString("token"));
|
||||||
|
|
||||||
BearerToken bearer = BearerToken.valueOf(compact);
|
BearerToken bearer = BearerToken.valueOf(compact);
|
||||||
|
|||||||
@@ -36,6 +36,7 @@ import org.mockito.Mock;
|
|||||||
import org.mockito.junit.MockitoJUnitRunner;
|
import org.mockito.junit.MockitoJUnitRunner;
|
||||||
|
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
|
import java.util.Arrays;
|
||||||
|
|
||||||
import static java.util.Collections.singletonList;
|
import static java.util.Collections.singletonList;
|
||||||
import static org.assertj.core.api.Assertions.assertThat;
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
@@ -59,6 +60,9 @@ public class ScmAtLeastOneSuccessfulStrategyTest {
|
|||||||
@Mock
|
@Mock
|
||||||
TokenExpiredException tokenExpiredException;
|
TokenExpiredException tokenExpiredException;
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
TokenValidationFailedException tokenValidationFailedException;
|
||||||
|
|
||||||
@Mock
|
@Mock
|
||||||
AuthenticationException authenticationException;
|
AuthenticationException authenticationException;
|
||||||
|
|
||||||
@@ -77,13 +81,29 @@ public class ScmAtLeastOneSuccessfulStrategyTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test(expected = TokenExpiredException.class)
|
@Test(expected = TokenExpiredException.class)
|
||||||
public void shouldRethrowException() {
|
public void shouldRethrowTokenExpiredException() {
|
||||||
final ScmAtLeastOneSuccessfulStrategy strategy = new ScmAtLeastOneSuccessfulStrategy();
|
final ScmAtLeastOneSuccessfulStrategy strategy = new ScmAtLeastOneSuccessfulStrategy();
|
||||||
strategy.threadLocal.set(singletonList(tokenExpiredException));
|
strategy.threadLocal.set(singletonList(tokenExpiredException));
|
||||||
|
|
||||||
strategy.afterAllAttempts(token, aggregateInfo);
|
strategy.afterAllAttempts(token, aggregateInfo);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test(expected = TokenValidationFailedException.class)
|
||||||
|
public void shouldRethrowTokenValidationFailedException() {
|
||||||
|
final ScmAtLeastOneSuccessfulStrategy strategy = new ScmAtLeastOneSuccessfulStrategy();
|
||||||
|
strategy.threadLocal.set(singletonList(tokenValidationFailedException));
|
||||||
|
|
||||||
|
strategy.afterAllAttempts(token, aggregateInfo);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test(expected = TokenExpiredException.class)
|
||||||
|
public void shouldPrioritizeRethrowingTokenExpiredExceptionOverTokenValidationFailedException() {
|
||||||
|
final ScmAtLeastOneSuccessfulStrategy strategy = new ScmAtLeastOneSuccessfulStrategy();
|
||||||
|
strategy.threadLocal.set(Arrays.asList(tokenValidationFailedException, tokenExpiredException));
|
||||||
|
|
||||||
|
strategy.afterAllAttempts(token, aggregateInfo);
|
||||||
|
}
|
||||||
|
|
||||||
@Test(expected = AuthenticationException.class)
|
@Test(expected = AuthenticationException.class)
|
||||||
public void shouldThrowGenericErrorIfNonTokenExpiredExceptionWasCaught() {
|
public void shouldThrowGenericErrorIfNonTokenExpiredExceptionWasCaught() {
|
||||||
final ScmAtLeastOneSuccessfulStrategy strategy = new ScmAtLeastOneSuccessfulStrategy();
|
final ScmAtLeastOneSuccessfulStrategy strategy = new ScmAtLeastOneSuccessfulStrategy();
|
||||||
|
|||||||
Reference in New Issue
Block a user