Search in sources :

Example 11 with TokenMetadata

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

the class TokenStateDatabase method getTokenMetadata.

TokenMetadata getTokenMetadata(String tokenId) throws SQLException {
    try (Connection connection = dataSource.getConnection();
        PreparedStatement getMaxLifetimeStatement = connection.prepareStatement(GET_METADATA_SQL)) {
        getMaxLifetimeStatement.setString(1, tokenId);
        try (ResultSet rs = getMaxLifetimeStatement.executeQuery()) {
            final Map<String, String> metadataMap = new HashMap<>();
            while (rs.next()) {
                String metadataName = rs.getString(1);
                metadataMap.put(metadataName, decodeMetadata(metadataName, rs.getString(2)));
            }
            return metadataMap.isEmpty() ? null : new TokenMetadata(metadataMap);
        }
    }
}
Also used : HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Connection(java.sql.Connection) ResultSet(java.sql.ResultSet) PreparedStatement(java.sql.PreparedStatement) TokenMetadata(org.apache.knox.gateway.services.security.token.TokenMetadata)

Example 12 with TokenMetadata

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

the class AliasBasedTokenStateServiceTest method getMetadataMapField.

private static Map<String, Map<String, TokenMetadata>> getMetadataMapField(TokenStateService tss, boolean fromGrandParent) throws Exception {
    final Class<TokenStateService> clazz = (Class<TokenStateService>) (fromGrandParent ? tss.getClass().getSuperclass().getSuperclass() : tss.getClass().getSuperclass());
    Field metadataMapField = clazz.getDeclaredField("metadataMap");
    metadataMapField.setAccessible(true);
    return (Map<String, Map<String, TokenMetadata>>) metadataMapField.get(tss);
}
Also used : Field(java.lang.reflect.Field) EasyMock.anyString(org.easymock.EasyMock.anyString) TokenStateService(org.apache.knox.gateway.services.security.token.TokenStateService) TokenMetadata(org.apache.knox.gateway.services.security.token.TokenMetadata) HashMap(java.util.HashMap) Map(java.util.Map)

Example 13 with TokenMetadata

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

the class ZookeeperTokenStateServiceTest method testRetry.

@Test
public void testRetry() throws Exception {
    final ZookeeperTokenStateService zktokenStateServiceNode1 = setupZkTokenStateService(LONG_TOKEN_STATE_ALIAS_PERSISTENCE_INTERVAL);
    final ZookeeperTokenStateService zktokenStateServiceNode2 = setupZkTokenStateService(LONG_TOKEN_STATE_ALIAS_PERSISTENCE_INTERVAL);
    final String tokenId = UUID.randomUUID().toString();
    zktokenStateServiceNode1.addToken(tokenId, 10L, 2000L);
    final long expiration = zktokenStateServiceNode2.getTokenExpiration(tokenId);
    Thread.sleep(LONG_TOKEN_STATE_ALIAS_PERSISTENCE_INTERVAL * 1000);
    assertEquals(2000L, expiration);
    final String userName = "testUser";
    final String comment = "This is my test comment";
    zktokenStateServiceNode1.addMetadata(tokenId, new TokenMetadata(userName, comment, true));
    Thread.sleep(LONG_TOKEN_STATE_ALIAS_PERSISTENCE_INTERVAL * 1000);
    assertEquals(userName, zktokenStateServiceNode2.getTokenMetadata(tokenId).getUserName());
    assertEquals(comment, zktokenStateServiceNode2.getTokenMetadata(tokenId).getComment());
    assertTrue(zktokenStateServiceNode2.getTokenMetadata(tokenId).isEnabled());
}
Also used : TokenMetadata(org.apache.knox.gateway.services.security.token.TokenMetadata) Test(org.junit.Test)

Example 14 with TokenMetadata

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

the class TokenResource method getAuthenticationToken.

private Response getAuthenticationToken() {
    if (clientCertRequired) {
        X509Certificate cert = extractCertificate(request);
        if (cert != null) {
            if (!allowedDNs.contains(cert.getSubjectDN().getName().replaceAll("\\s+", ""))) {
                return Response.status(Response.Status.FORBIDDEN).entity("{ \"Unable to get token - untrusted client cert.\" }").build();
            }
        } else {
            return Response.status(Response.Status.FORBIDDEN).entity("{ \"Unable to get token - client cert required.\" }").build();
        }
    }
    GatewayServices services = (GatewayServices) request.getServletContext().getAttribute(GatewayServices.GATEWAY_SERVICES_ATTRIBUTE);
    JWTokenAuthority ts = services.getService(ServiceType.TOKEN_SERVICE);
    Principal p = request.getUserPrincipal();
    long expires = getExpiry();
    if (endpointPublicCert == null) {
        // acquire PEM for gateway identity of this gateway instance
        KeystoreService ks = services.getService(ServiceType.KEYSTORE_SERVICE);
        if (ks != null) {
            try {
                Certificate cert = ks.getCertificateForGateway();
                byte[] bytes = cert.getEncoded();
                endpointPublicCert = Base64.encodeBase64String(bytes);
            } catch (KeyStoreException | KeystoreServiceException | CertificateEncodingException e) {
                // assuming that certs will be properly provisioned across all clients
                log.unableToAcquireCertForEndpointClients(e);
            }
        }
    }
    String jku = null;
    /* remove .../token and replace it with ..../jwks.json */
    final int idx = request.getRequestURL().lastIndexOf("/");
    if (idx > 1) {
        jku = request.getRequestURL().substring(0, idx) + JWKSResource.JWKS_PATH;
    }
    if (tokenStateService != null) {
        if (tokenLimitPerUser != -1) {
            // if -1 => unlimited tokens for all users
            if (tokenStateService.getTokens(p.getName()).size() >= tokenLimitPerUser) {
                log.tokenLimitExceeded(p.getName());
                return Response.status(Response.Status.FORBIDDEN).entity("{ \"Unable to get token - token limit exceeded.\" }").build();
            }
        }
    }
    try {
        final boolean managedToken = tokenStateService != null;
        JWT token;
        JWTokenAttributes jwtAttributes;
        final JWTokenAttributesBuilder jwtAttributesBuilder = new JWTokenAttributesBuilder();
        jwtAttributesBuilder.setPrincipal(p).setAlgorithm(signatureAlgorithm).setExpires(expires).setManaged(managedToken).setJku(jku).setType(tokenType);
        if (!targetAudiences.isEmpty()) {
            jwtAttributesBuilder.setAudiences(targetAudiences);
        }
        jwtAttributes = jwtAttributesBuilder.build();
        token = ts.issueToken(jwtAttributes);
        if (token != null) {
            String accessToken = token.toString();
            String tokenId = TokenUtils.getTokenId(token);
            log.issuedToken(getTopologyName(), Tokens.getTokenDisplayText(accessToken), Tokens.getTokenIDDisplayText(tokenId));
            final HashMap<String, Object> map = new HashMap<>();
            map.put(ACCESS_TOKEN, accessToken);
            map.put(TOKEN_ID, tokenId);
            map.put(MANAGED_TOKEN, String.valueOf(managedToken));
            map.put(TOKEN_TYPE, BEARER);
            map.put(EXPIRES_IN, expires);
            if (tokenTargetUrl != null) {
                map.put(TARGET_URL, tokenTargetUrl);
            }
            if (tokenClientDataMap != null) {
                map.putAll(tokenClientDataMap);
            }
            if (endpointPublicCert != null) {
                map.put(ENDPOINT_PUBLIC_CERT, endpointPublicCert);
            }
            final String passcode = UUID.randomUUID().toString();
            map.put(PASSCODE, generatePasscodeField(tokenId, passcode));
            String jsonResponse = JsonUtils.renderAsJsonString(map);
            // Optional token store service persistence
            if (tokenStateService != null) {
                final long issueTime = System.currentTimeMillis();
                tokenStateService.addToken(tokenId, issueTime, expires, maxTokenLifetime.orElse(tokenStateService.getDefaultMaxLifetimeDuration()));
                final String comment = request.getParameter(COMMENT);
                final TokenMetadata tokenMetadata = new TokenMetadata(p.getName(), StringUtils.isBlank(comment) ? null : comment);
                tokenMetadata.setPasscode(tokenMAC.hash(tokenId, issueTime, p.getName(), passcode));
                tokenStateService.addMetadata(tokenId, tokenMetadata);
                log.storedToken(getTopologyName(), Tokens.getTokenDisplayText(accessToken), Tokens.getTokenIDDisplayText(tokenId));
            }
            return Response.ok().entity(jsonResponse).build();
        } else {
            return Response.serverError().build();
        }
    } catch (TokenServiceException e) {
        log.unableToIssueToken(e);
    }
    return Response.ok().entity("{ \"Unable to acquire token.\" }").build();
}
Also used : GatewayServices(org.apache.knox.gateway.services.GatewayServices) HashMap(java.util.HashMap) JWT(org.apache.knox.gateway.services.security.token.impl.JWT) CertificateEncodingException(java.security.cert.CertificateEncodingException) KeyStoreException(java.security.KeyStoreException) KeystoreServiceException(org.apache.knox.gateway.services.security.KeystoreServiceException) TokenMetadata(org.apache.knox.gateway.services.security.token.TokenMetadata) X509Certificate(java.security.cert.X509Certificate) JWTokenAuthority(org.apache.knox.gateway.services.security.token.JWTokenAuthority) JWTokenAttributes(org.apache.knox.gateway.services.security.token.JWTokenAttributes) KeystoreService(org.apache.knox.gateway.services.security.KeystoreService) Principal(java.security.Principal) TokenServiceException(org.apache.knox.gateway.services.security.token.TokenServiceException) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate) JWTokenAttributesBuilder(org.apache.knox.gateway.services.security.token.JWTokenAttributesBuilder)

Aggregations

TokenMetadata (org.apache.knox.gateway.services.security.token.TokenMetadata)14 Test (org.junit.Test)5 HashMap (java.util.HashMap)4 UnknownTokenException (org.apache.knox.gateway.services.security.token.UnknownTokenException)3 JWTToken (org.apache.knox.gateway.services.security.token.impl.JWTToken)3 EasyMock.anyString (org.easymock.EasyMock.anyString)3 HashSet (java.util.HashSet)2 Map (java.util.Map)2 AbstractAliasService (org.apache.knox.gateway.services.security.AbstractAliasService)2 AliasService (org.apache.knox.gateway.services.security.AliasService)2 TokenStateService (org.apache.knox.gateway.services.security.token.TokenStateService)2 JWT (org.apache.knox.gateway.services.security.token.impl.JWT)2 Field (java.lang.reflect.Field)1 KeyStoreException (java.security.KeyStoreException)1 Principal (java.security.Principal)1 Certificate (java.security.cert.Certificate)1 CertificateEncodingException (java.security.cert.CertificateEncodingException)1 X509Certificate (java.security.cert.X509Certificate)1 Connection (java.sql.Connection)1 PreparedStatement (java.sql.PreparedStatement)1