use of org.apache.knox.gateway.services.security.token.UnknownTokenException in project knox by apache.
the class AbstractJWTFilter method validateToken.
protected boolean validateToken(final HttpServletRequest request, final HttpServletResponse response, final FilterChain chain, final JWT token) throws IOException, ServletException {
final String tokenId = TokenUtils.getTokenId(token);
final String displayableTokenId = Tokens.getTokenIDDisplayText(tokenId);
final String displayableToken = Tokens.getTokenDisplayText(token.toString());
// confirm that issuer matches the intended target
if (expectedIssuer.equals(token.getIssuer())) {
// the designated expiration time
try {
if (tokenIsStillValid(token)) {
boolean audValid = validateAudiences(token);
if (audValid) {
Date nbf = token.getNotBeforeDate();
if (nbf == null || new Date().after(nbf)) {
if (isTokenEnabled(tokenId)) {
if (verifyTokenSignature(token)) {
return true;
} else {
log.failedToVerifyTokenSignature(displayableToken, displayableTokenId);
handleValidationError(request, response, HttpServletResponse.SC_UNAUTHORIZED, null);
}
} else {
log.disabledToken(displayableTokenId);
handleValidationError(request, response, HttpServletResponse.SC_UNAUTHORIZED, "Token " + displayableTokenId + " is disabled");
}
} else {
log.notBeforeCheckFailed();
handleValidationError(request, response, HttpServletResponse.SC_BAD_REQUEST, "Bad request: the NotBefore check failed");
}
} else {
log.failedToValidateAudience(displayableToken, displayableTokenId);
handleValidationError(request, response, HttpServletResponse.SC_BAD_REQUEST, "Bad request: missing required token audience");
}
} else {
log.tokenHasExpired(displayableToken, displayableTokenId);
// Explicitly evict the record of this token's signature verification (if present).
// There is no value in keeping this record for expired tokens, and explicitly removing them may prevent
// records for other valid tokens from being prematurely evicted from the cache.
removeSignatureVerificationRecord(token.toString());
handleValidationError(request, response, HttpServletResponse.SC_UNAUTHORIZED, "Token has expired");
}
} catch (UnknownTokenException e) {
log.unableToVerifyExpiration(e);
handleValidationError(request, response, HttpServletResponse.SC_UNAUTHORIZED, e.getMessage());
}
} else {
handleValidationError(request, response, HttpServletResponse.SC_UNAUTHORIZED, null);
}
return false;
}
use of org.apache.knox.gateway.services.security.token.UnknownTokenException in project knox by apache.
the class JWTFederationFilter method doFilter.
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
/* check for unauthenticated paths to bypass */
if (AuthFilterUtils.doesRequestContainUnauthPath(unAuthenticatedPaths, request)) {
continueWithAnonymousSubject(request, response, chain);
return;
}
final Pair<TokenType, String> wireToken = getWireToken(request);
if (wireToken != null && wireToken.getLeft() != null && wireToken.getRight() != null) {
TokenType tokenType = wireToken.getLeft();
String tokenValue = wireToken.getRight();
if (TokenType.JWT.equals(tokenType)) {
try {
JWT token = new JWTToken(tokenValue);
if (validateToken((HttpServletRequest) request, (HttpServletResponse) response, chain, token)) {
Subject subject = createSubjectFromToken(token);
continueWithEstablishedSecurityContext(subject, (HttpServletRequest) request, (HttpServletResponse) response, chain);
}
} catch (ParseException | UnknownTokenException ex) {
((HttpServletResponse) response).sendError(HttpServletResponse.SC_UNAUTHORIZED);
}
} else if (TokenType.Passcode.equals(tokenType)) {
// Validate the token based on the server-managed metadata
// The received token value must be a Base64 encoded value of Base64(tokenId)::Base64(rawPasscode)
String tokenId = null;
String passcode = null;
try {
final String[] base64DecodedTokenIdAndPasscode = decodeBase64(tokenValue).split("::");
tokenId = decodeBase64(base64DecodedTokenIdAndPasscode[0]);
passcode = decodeBase64(base64DecodedTokenIdAndPasscode[1]);
} catch (Exception e) {
log.failedToParsePasscodeToken(e);
handleValidationError((HttpServletRequest) request, (HttpServletResponse) response, HttpServletResponse.SC_UNAUTHORIZED, "Error while parsing the received passcode token");
}
if (validateToken((HttpServletRequest) request, (HttpServletResponse) response, chain, tokenId, passcode)) {
try {
Subject subject = createSubjectFromTokenIdentifier(tokenId);
continueWithEstablishedSecurityContext(subject, (HttpServletRequest) request, (HttpServletResponse) response, chain);
} catch (UnknownTokenException e) {
((HttpServletResponse) response).sendError(HttpServletResponse.SC_UNAUTHORIZED);
}
}
}
} else {
// no token provided in header
log.missingTokenFromHeader(wireToken);
((HttpServletResponse) response).sendError(HttpServletResponse.SC_UNAUTHORIZED);
}
}
use of org.apache.knox.gateway.services.security.token.UnknownTokenException in project knox by apache.
the class AccessTokenFederationFilter method doFilter.
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
String header = ((HttpServletRequest) request).getHeader("Authorization");
if (header != null && header.startsWith(BEARER)) {
// what follows the bearer designator should be the JWT token being used to request or as an access token
String wireToken = header.substring(BEARER.length());
JWTToken token;
try {
token = JWTToken.parseToken(wireToken);
} catch (ParseException e) {
throw new ServletException("ParseException encountered while processing the JWT token: ", e);
}
boolean verified = false;
try {
verified = authority.verifyToken(token);
} catch (TokenServiceException e) {
log.unableToVerifyToken(e);
}
final String tokenId = TokenUtils.getTokenId(token);
final String displayableTokenId = Tokens.getTokenIDDisplayText(tokenId);
final String displayableToken = Tokens.getTokenDisplayText(token.toString());
if (verified) {
try {
if (!isExpired(token)) {
if (((HttpServletRequest) request).getRequestURL().indexOf(token.getAudience().toLowerCase(Locale.ROOT)) != -1) {
Subject subject = createSubjectFromToken(token);
continueWithEstablishedSecurityContext(subject, (HttpServletRequest) request, (HttpServletResponse) response, chain);
} else {
log.failedToValidateAudience(displayableToken, displayableTokenId);
sendUnauthorized(response);
}
} else {
log.tokenHasExpired(displayableToken, displayableTokenId);
sendUnauthorized(response);
}
} catch (UnknownTokenException e) {
log.unableToVerifyExpiration(e);
sendUnauthorized(response);
}
} else {
log.failedToVerifyTokenSignature(displayableToken, displayableTokenId);
sendUnauthorized(response);
}
} else {
log.missingBearerToken();
sendUnauthorized(response);
}
}
use of org.apache.knox.gateway.services.security.token.UnknownTokenException in project knox by apache.
the class SSOCookieFederationFilter method doFilter.
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse res = (HttpServletResponse) response;
List<Cookie> ssoCookies = CookieUtils.getCookiesForName(req, cookieName);
if (ssoCookies.isEmpty()) {
/* check for unauthenticated paths to bypass */
if (AuthFilterUtils.doesRequestContainUnauthPath(unAuthenticatedPaths, request)) {
/* This path is configured as an unauthenticated path let the request through */
final Subject sub = new Subject();
sub.getPrincipals().add(new PrimaryPrincipal("anonymous"));
LOGGER.unauthenticatedPathBypass(req.getRequestURI(), unAuthenticatedPaths.toString());
continueWithEstablishedSecurityContext(sub, req, res, chain);
}
if ("OPTIONS".equals(req.getMethod())) {
// CORS preflight requests to determine allowed origins and related config
// must be able to continue without being redirected
Subject sub = new Subject();
sub.getPrincipals().add(new PrimaryPrincipal("anonymous"));
continueWithEstablishedSecurityContext(sub, req, res, chain);
} else {
sendRedirectToLoginURL(req, res);
}
} else {
for (Cookie ssoCookie : ssoCookies) {
String wireToken = ssoCookie.getValue();
try {
JWT token = new JWTToken(wireToken);
if (validateToken(req, res, chain, token)) {
Subject subject = createSubjectFromToken(token);
continueWithEstablishedSecurityContext(subject, req, res, chain);
// we found a valid cookie we don't need to keep checking anymore
return;
}
} catch (ParseException | UnknownTokenException ignore) {
// Ignore the error since cookie was invalid
// Fall through to keep checking if there are more cookies
}
}
// There were no valid cookies found so redirect to login url
if (res != null && !res.isCommitted()) {
sendRedirectToLoginURL(req, res);
}
}
}
use of org.apache.knox.gateway.services.security.token.UnknownTokenException in project knox by apache.
the class CommonJWTFilterTest method testIsStillValidUnknownToken.
@Test(expected = UnknownTokenException.class)
public void testIsStillValidUnknownToken() throws Exception {
TokenStateService tss = EasyMock.createNiceMock(TokenStateService.class);
final String tokenId = UUID.randomUUID().toString();
EasyMock.expect(tss.getTokenExpiration(anyObject(JWT.class))).andThrow(new UnknownTokenException(tokenId)).anyTimes();
EasyMock.expect(tss.getTokenExpiration(anyObject(String.class))).andThrow(new UnknownTokenException(tokenId)).anyTimes();
EasyMock.replay(tss);
doTestIsStillValid(tss);
}
Aggregations