Search in sources :

Example 11 with UnknownTokenException

use of org.apache.knox.gateway.services.security.token.UnknownTokenException in project knox by apache.

the class HadoopAuthPostFilter method doFilter.

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    Subject subject = null;
    if (shouldUseJwtFilter(jwtFilter, (HttpServletRequest) request)) {
        try {
            Pair<JWTFederationFilter.TokenType, String> wireToken = jwtFilter.getWireToken(request);
            JWTFederationFilter.TokenType tokenType = wireToken.getLeft();
            String token = wireToken.getRight();
            if (JWTFederationFilter.TokenType.JWT.equals(tokenType)) {
                subject = jwtFilter.createSubjectFromToken(token);
            } else if (JWTFederationFilter.TokenType.Passcode.equals(tokenType)) {
                subject = jwtFilter.createSubjectFromTokenIdentifier(token);
            }
        } catch (ParseException | UnknownTokenException e) {
        // NOP: subject remains null -> SC_FORBIDDEN will be returned
        }
    } else {
        final String principal = ((HttpServletRequest) request).getRemoteUser();
        if (principal != null) {
            subject = new Subject();
            subject.getPrincipals().add(new PrimaryPrincipal(principal));
            AuditContext context = auditService.getContext();
            context.setUsername(principal);
            auditService.attachContext(context);
        }
    }
    if (subject != null) {
        log.hadoopAuthAssertedPrincipal(getPrincipalsAsString(subject));
        String sourceUri = (String) request.getAttribute(AbstractGatewayFilter.SOURCE_REQUEST_CONTEXT_URL_ATTRIBUTE_NAME);
        auditor.audit(Action.AUTHENTICATION, sourceUri, ResourceType.URI, ActionOutcome.SUCCESS);
        doAs(request, response, chain, subject);
    } else {
        ((HttpServletResponse) response).sendError(HttpServletResponse.SC_FORBIDDEN, "User not authenticated");
    }
}
Also used : HttpServletResponse(javax.servlet.http.HttpServletResponse) Subject(javax.security.auth.Subject) AuditContext(org.apache.knox.gateway.audit.api.AuditContext) JWTFederationFilter(org.apache.knox.gateway.provider.federation.jwt.filter.JWTFederationFilter) HttpServletRequest(javax.servlet.http.HttpServletRequest) PrimaryPrincipal(org.apache.knox.gateway.security.PrimaryPrincipal) UnknownTokenException(org.apache.knox.gateway.services.security.token.UnknownTokenException) ParseException(java.text.ParseException)

Example 12 with UnknownTokenException

use of org.apache.knox.gateway.services.security.token.UnknownTokenException in project knox by apache.

the class DefaultTokenStateService method getTokens.

@Override
public Collection<KnoxToken> getTokens(String userName) {
    final Collection<KnoxToken> tokens = new TreeSet<>();
    metadataMap.entrySet().stream().filter(entry -> entry.getValue().getUserName().equals(userName)).forEach(metadata -> {
        String tokenId = metadata.getKey();
        try {
            tokens.add(new KnoxToken(tokenId, getTokenIssueTime(tokenId), getTokenExpiration(tokenId), getMaxLifetime(tokenId), metadata.getValue()));
        } catch (UnknownTokenException e) {
        // NOP: since this is coming from memory the only reason an UTE is thrown that the token got removed/revoked.
        // In that case we would not want to return it anyway
        }
    });
    return tokens;
}
Also used : KnoxToken(org.apache.knox.gateway.services.security.token.KnoxToken) MessagesFactory(org.apache.knox.gateway.i18n.messages.MessagesFactory) GatewayConfig(org.apache.knox.gateway.config.GatewayConfig) JWT(org.apache.knox.gateway.services.security.token.impl.JWT) TokenMetadata(org.apache.knox.gateway.services.security.token.TokenMetadata) TreeSet(java.util.TreeSet) HashSet(java.util.HashSet) JWTToken(org.apache.knox.gateway.services.security.token.impl.JWTToken) InstanceAlreadyExistsException(javax.management.InstanceAlreadyExistsException) Tokens(org.apache.knox.gateway.util.Tokens) UnknownTokenException(org.apache.knox.gateway.services.security.token.UnknownTokenException) Map(java.util.Map) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) MBeanRegistrationException(javax.management.MBeanRegistrationException) ManagementFactory(java.lang.management.ManagementFactory) TokenStateServiceStatistics(org.apache.knox.gateway.services.token.TokenStateServiceStatistics) NotCompliantMBeanException(javax.management.NotCompliantMBeanException) Collection(java.util.Collection) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Set(java.util.Set) ObjectName(javax.management.ObjectName) Instant(java.time.Instant) TokenUtils(org.apache.knox.gateway.services.security.token.TokenUtils) Collectors(java.util.stream.Collectors) Executors(java.util.concurrent.Executors) TokenStateService(org.apache.knox.gateway.services.security.token.TokenStateService) TimeUnit(java.util.concurrent.TimeUnit) MalformedObjectNameException(javax.management.MalformedObjectNameException) List(java.util.List) ServiceLifecycleException(org.apache.knox.gateway.services.ServiceLifecycleException) Collections(java.util.Collections) TreeSet(java.util.TreeSet) KnoxToken(org.apache.knox.gateway.services.security.token.KnoxToken) UnknownTokenException(org.apache.knox.gateway.services.security.token.UnknownTokenException)

Example 13 with UnknownTokenException

use of org.apache.knox.gateway.services.security.token.UnknownTokenException in project knox by apache.

the class JournalBasedTokenStateService method getTokenIssueTime.

@Override
public long getTokenIssueTime(String tokenId) throws UnknownTokenException {
    try {
        // Check the in-memory collection first, to avoid file access when possible
        return super.getTokenIssueTime(tokenId);
    } catch (UnknownTokenException e) {
    // It's not in memory
    }
    validateToken(tokenId);
    // If there is no associated state in the in-memory cache, proceed to check the journal
    long issueTime = 0;
    try {
        JournalEntry entry = journal.get(tokenId);
        if (entry == null) {
            throw new UnknownTokenException(tokenId);
        }
        issueTime = Long.parseLong(entry.getIssueTime());
    } catch (IOException e) {
        log.failedToLoadJournalEntry(e);
    }
    return issueTime;
}
Also used : UnknownTokenException(org.apache.knox.gateway.services.security.token.UnknownTokenException) IOException(java.io.IOException) JournalEntry(org.apache.knox.gateway.services.token.state.JournalEntry)

Example 14 with UnknownTokenException

use of org.apache.knox.gateway.services.security.token.UnknownTokenException in project knox by apache.

the class DefaultTokenStateServiceTest method testTokenEviction.

@Test
public void testTokenEviction() throws Exception {
    final JWTToken token = createMockToken(System.currentTimeMillis() - TimeUnit.SECONDS.toMillis(60));
    final TokenStateService tss = createTokenStateService();
    final long evictionInterval = TimeUnit.SECONDS.toMillis(3);
    final long maxTokenLifetime = evictionInterval * 3;
    try {
        tss.start();
        // Add the expired token
        addToken(tss, token.getClaim(JWTToken.KNOX_ID_CLAIM), System.currentTimeMillis(), token.getExpiresDate().getTime(), maxTokenLifetime);
        assertTrue("Expected the token to have expired.", tss.isExpired(token));
        // Sleep to allow the eviction evaluation to be performed
        Thread.sleep(evictionInterval + (evictionInterval / 2));
        // Expect the renew call to fail since the token should have been evicted
        final UnknownTokenException e = assertThrows(UnknownTokenException.class, () -> tss.renewToken(token));
        assertEquals("Unknown token: " + Tokens.getTokenIDDisplayText(TokenUtils.getTokenId(token)), e.getMessage());
    } finally {
        tss.stop();
    }
}
Also used : UnknownTokenException(org.apache.knox.gateway.services.security.token.UnknownTokenException) TokenStateService(org.apache.knox.gateway.services.security.token.TokenStateService) JWTToken(org.apache.knox.gateway.services.security.token.impl.JWTToken) Test(org.junit.Test)

Example 15 with UnknownTokenException

use of org.apache.knox.gateway.services.security.token.UnknownTokenException in project knox by apache.

the class TokenResource method revoke.

@DELETE
@Path(REVOKE_PATH)
@Produces({ APPLICATION_JSON })
public Response revoke(String token) {
    Response resp;
    String error = "";
    ErrorCode errorCode = ErrorCode.UNKNOWN;
    Response.Status errorStatus = Response.Status.BAD_REQUEST;
    if (tokenStateService == null) {
        error = "Token revocation support is not configured";
        errorCode = ErrorCode.CONFIGURATION_ERROR;
    } else {
        try {
            final String revoker = SubjectUtils.getCurrentEffectivePrincipalName();
            final String tokenId = getTokenId(token);
            if (triesToRevokeOwnToken(tokenId, revoker) || allowedRenewers.contains(revoker)) {
                tokenStateService.revokeToken(tokenId);
                log.revokedToken(getTopologyName(), Tokens.getTokenDisplayText(token), Tokens.getTokenIDDisplayText(tokenId), revoker);
            } else {
                errorStatus = Response.Status.FORBIDDEN;
                error = "Caller (" + revoker + ") not authorized to revoke tokens.";
                errorCode = ErrorCode.UNAUTHORIZED;
            }
        } catch (ParseException e) {
            log.invalidToken(getTopologyName(), Tokens.getTokenDisplayText(token), e);
            error = safeGetMessage(e);
            errorCode = ErrorCode.INVALID_TOKEN;
        } catch (UnknownTokenException e) {
            error = safeGetMessage(e);
            errorCode = ErrorCode.UNKNOWN_TOKEN;
        }
    }
    if (error.isEmpty()) {
        resp = Response.status(Response.Status.OK).entity("{\n  \"revoked\": \"true\"\n}\n").build();
    } else {
        log.badRevocationRequest(getTopologyName(), Tokens.getTokenDisplayText(token), error);
        resp = Response.status(errorStatus).entity("{\n  \"revoked\": \"false\",\n  \"error\": \"" + error + "\",\n  \"code\": " + errorCode.toInt() + "\n}\n").build();
    }
    return resp;
}
Also used : Response(javax.ws.rs.core.Response) UnknownTokenException(org.apache.knox.gateway.services.security.token.UnknownTokenException) ParseException(java.text.ParseException) DateTimeParseException(java.time.format.DateTimeParseException) Path(javax.ws.rs.Path) DELETE(javax.ws.rs.DELETE) Produces(javax.ws.rs.Produces)

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