Search in sources :

Example 1 with UnknownTokenException

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;
}
Also used : UnknownTokenException(org.apache.knox.gateway.services.security.token.UnknownTokenException) Date(java.util.Date)

Example 2 with UnknownTokenException

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);
    }
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) JWT(org.apache.knox.gateway.services.security.token.impl.JWT) UnknownTokenException(org.apache.knox.gateway.services.security.token.UnknownTokenException) HttpServletResponse(javax.servlet.http.HttpServletResponse) ParseException(java.text.ParseException) JWTToken(org.apache.knox.gateway.services.security.token.impl.JWTToken) Subject(javax.security.auth.Subject) ServletException(javax.servlet.ServletException) UnknownTokenException(org.apache.knox.gateway.services.security.token.UnknownTokenException) ParseException(java.text.ParseException) IOException(java.io.IOException)

Example 3 with UnknownTokenException

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);
    }
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletException(javax.servlet.ServletException) UnknownTokenException(org.apache.knox.gateway.services.security.token.UnknownTokenException) ParseException(java.text.ParseException) JWTToken(org.apache.knox.gateway.services.security.token.impl.JWTToken) TokenServiceException(org.apache.knox.gateway.services.security.token.TokenServiceException) Subject(javax.security.auth.Subject)

Example 4 with UnknownTokenException

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);
        }
    }
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) Cookie(javax.servlet.http.Cookie) PrimaryPrincipal(org.apache.knox.gateway.security.PrimaryPrincipal) JWT(org.apache.knox.gateway.services.security.token.impl.JWT) UnknownTokenException(org.apache.knox.gateway.services.security.token.UnknownTokenException) HttpServletResponse(javax.servlet.http.HttpServletResponse) ParseException(java.text.ParseException) JWTToken(org.apache.knox.gateway.services.security.token.impl.JWTToken) Subject(javax.security.auth.Subject)

Example 5 with UnknownTokenException

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);
}
Also used : UnknownTokenException(org.apache.knox.gateway.services.security.token.UnknownTokenException) TokenStateService(org.apache.knox.gateway.services.security.token.TokenStateService) Test(org.junit.Test)

Aggregations

UnknownTokenException (org.apache.knox.gateway.services.security.token.UnknownTokenException)15 ParseException (java.text.ParseException)5 JWTToken (org.apache.knox.gateway.services.security.token.impl.JWTToken)5 IOException (java.io.IOException)4 Subject (javax.security.auth.Subject)4 HttpServletRequest (javax.servlet.http.HttpServletRequest)4 TokenMetadata (org.apache.knox.gateway.services.security.token.TokenMetadata)4 TokenStateService (org.apache.knox.gateway.services.security.token.TokenStateService)4 HttpServletResponse (javax.servlet.http.HttpServletResponse)3 JWT (org.apache.knox.gateway.services.security.token.impl.JWT)3 ServletException (javax.servlet.ServletException)2 PrimaryPrincipal (org.apache.knox.gateway.security.PrimaryPrincipal)2 ServiceLifecycleException (org.apache.knox.gateway.services.ServiceLifecycleException)2 JournalEntry (org.apache.knox.gateway.services.token.state.JournalEntry)2 Test (org.junit.Test)2 ManagementFactory (java.lang.management.ManagementFactory)1 SQLException (java.sql.SQLException)1 Instant (java.time.Instant)1 DateTimeParseException (java.time.format.DateTimeParseException)1 Collection (java.util.Collection)1