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);
}
}
}
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);
}
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());
}
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();
}
Aggregations