use of org.apache.knox.gateway.services.security.token.JWTokenAttributes in project knox by apache.
the class JWTAccessTokenAssertionFilter method getAccessToken.
private String getAccessToken(final String principalName, String serviceName, long expires) {
String accessToken = null;
Principal p = new Principal() {
@Override
public String getName() {
return principalName;
}
};
JWT token;
try {
final JWTokenAttributes jwtAttributes = new JWTokenAttributesBuilder().setPrincipal(p).setAudiences(serviceName).setAlgorithm(signatureAlgorithm).setExpires(expires).build();
token = authority.issueToken(jwtAttributes);
// Coverity CID 1327961
if (token != null) {
accessToken = token.toString();
}
} catch (TokenServiceException e) {
log.unableToIssueToken(e);
}
return accessToken;
}
use of org.apache.knox.gateway.services.security.token.JWTokenAttributes in project knox by apache.
the class DefaultTokenAuthorityServiceTest method testTokenCreationCustomSigningKey.
@Test
public void testTokenCreationCustomSigningKey() throws Exception {
/*
Generated testSigningKeyName.jks with the following commands:
cd gateway-server/src/test/resources/keystores/
keytool -genkey -alias testSigningKeyAlias -keyalg RSA -keystore testSigningKeyName.jks \
-storepass testSigningKeyPassphrase -keypass testSigningKeyPassphrase -keysize 2048 \
-dname 'CN=testSigningKey,OU=example,O=Apache,L=US,ST=CA,C=US' -noprompt
*/
String customSigningKeyName = "testSigningKeyName";
String customSigningKeyAlias = "testSigningKeyAlias";
String customSigningKeyPassphrase = "testSigningKeyPassphrase";
Principal principal = EasyMock.createNiceMock(Principal.class);
EasyMock.expect(principal.getName()).andReturn("john.doe@example.com");
GatewayConfig config = EasyMock.createNiceMock(GatewayConfig.class);
String basedir = System.getProperty("basedir");
if (basedir == null) {
basedir = new File(".").getCanonicalPath();
}
EasyMock.expect(config.getGatewaySecurityDir()).andReturn(basedir + "/target/test-classes").anyTimes();
EasyMock.expect(config.getGatewayKeystoreDir()).andReturn(basedir + "/target/test-classes/keystores").anyTimes();
EasyMock.expect(config.getSigningKeystoreName()).andReturn("server-keystore.jks").anyTimes();
EasyMock.expect(config.getSigningKeystorePath()).andReturn(basedir + "/target/test-classes/keystores/server-keystore.jks").anyTimes();
EasyMock.expect(config.getSigningKeystorePasswordAlias()).andReturn(GatewayConfig.DEFAULT_SIGNING_KEYSTORE_PASSWORD_ALIAS).anyTimes();
EasyMock.expect(config.getSigningKeyPassphraseAlias()).andReturn(GatewayConfig.DEFAULT_SIGNING_KEY_PASSPHRASE_ALIAS).anyTimes();
EasyMock.expect(config.getSigningKeystoreType()).andReturn("jks").anyTimes();
EasyMock.expect(config.getSigningKeyAlias()).andReturn("server").anyTimes();
EasyMock.expect(config.getCredentialStoreType()).andReturn(GatewayConfig.DEFAULT_CREDENTIAL_STORE_TYPE).anyTimes();
EasyMock.expect(config.getCredentialStoreAlgorithm()).andReturn(GatewayConfig.DEFAULT_CREDENTIAL_STORE_ALG).anyTimes();
MasterService ms = EasyMock.createNiceMock(MasterService.class);
AliasService as = EasyMock.createNiceMock(AliasService.class);
EasyMock.expect(as.getSigningKeyPassphrase()).andReturn("horton".toCharArray()).anyTimes();
EasyMock.replay(principal, config, ms, as);
DefaultKeystoreService ks = new DefaultKeystoreService();
ks.setMasterService(ms);
ks.init(config, new HashMap<>());
DefaultTokenAuthorityService ta = new DefaultTokenAuthorityService();
ta.setAliasService(as);
ta.setKeystoreService(ks);
ta.init(config, new HashMap<>());
ta.start();
final JWTokenAttributes jwtAttributes = new JWTokenAttributesBuilder().setPrincipal(principal).setAudiences(Collections.emptyList()).setAlgorithm("RS256").setExpires(-1).setSigningKeystoreName(customSigningKeyName).setSigningKeystoreAlias(customSigningKeyAlias).setSigningKeystorePassphrase(customSigningKeyPassphrase.toCharArray()).build();
JWT token = ta.issueToken(jwtAttributes);
assertEquals("KNOXSSO", token.getIssuer());
assertEquals("john.doe@example.com", token.getSubject());
RSAPublicKey customPublicKey = (RSAPublicKey) ks.getSigningKeystore(customSigningKeyName).getCertificate(customSigningKeyAlias).getPublicKey();
assertFalse(ta.verifyToken(token));
assertTrue(ta.verifyToken(token, customPublicKey));
}
use of org.apache.knox.gateway.services.security.token.JWTokenAttributes 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();
}
use of org.apache.knox.gateway.services.security.token.JWTokenAttributes in project knox by apache.
the class WebSSOResource method getAuthenticationToken.
private Response getAuthenticationToken(int statusCode) {
GatewayServices services = (GatewayServices) request.getServletContext().getAttribute(GatewayServices.GATEWAY_SERVICES_ATTRIBUTE);
boolean removeOriginalUrlCookie = true;
List<Cookie> originalUrlCookies = CookieUtils.getCookiesForName(request, ORIGINAL_URL_COOKIE_NAME);
String original;
if (originalUrlCookies.isEmpty()) {
// in the case where there are no SAML redirects done before here
// we need to get it from the request parameters
removeOriginalUrlCookie = false;
original = getOriginalUrlFromQueryParams();
if (original.isEmpty()) {
LOGGER.originalURLNotFound();
throw new WebApplicationException("Original URL not found in the request.", Response.Status.BAD_REQUEST);
}
boolean validRedirect = true;
// If there is no whitelist, then everything is valid.
if (whitelist != null) {
String decodedOriginal = null;
try {
decodedOriginal = URLDecoder.decode(original, StandardCharsets.UTF_8.name());
} catch (UnsupportedEncodingException e) {
//
}
validRedirect = RegExUtils.checkWhitelist(whitelist, (decodedOriginal != null ? decodedOriginal : original));
}
if (!validRedirect) {
LOGGER.whiteListMatchFail(Log4jAuditor.maskTokenFromURL(original), whitelist);
throw new WebApplicationException("Original URL not valid according to the configured whitelist.", Response.Status.BAD_REQUEST);
}
} else {
// There should only be one original url cookie for the given path
original = originalUrlCookies.get(0).getValue();
}
AliasService as = services.getService(ServiceType.ALIAS_SERVICE);
JWTokenAuthority tokenAuthority = services.getService(ServiceType.TOKEN_SERVICE);
Principal p = request.getUserPrincipal();
try {
String signingKeystoreName = context.getInitParameter(SSO_SIGNINGKEY_KEYSTORE_NAME);
String signingKeystoreAlias = context.getInitParameter(SSO_SIGNINGKEY_KEYSTORE_ALIAS);
String signingKeystorePassphraseAlias = context.getInitParameter(SSO_SIGNINGKEY_KEYSTORE_PASSPHRASE_ALIAS);
char[] signingKeystorePassphrase = null;
if (signingKeystorePassphraseAlias != null) {
signingKeystorePassphrase = as.getPasswordFromAliasForCluster(clusterName, signingKeystorePassphraseAlias);
}
final JWTokenAttributes jwtAttributes = new JWTokenAttributesBuilder().setPrincipal(p).setAudiences(targetAudiences).setAlgorithm(signatureAlgorithm).setExpires(getExpiry()).setSigningKeystoreName(signingKeystoreName).setSigningKeystoreAlias(signingKeystoreAlias).setSigningKeystorePassphrase(signingKeystorePassphrase).build();
JWT token = tokenAuthority.issueToken(jwtAttributes);
// Coverity CID 1327959
if (token != null) {
addJWTHadoopCookie(original, token);
}
if (removeOriginalUrlCookie) {
removeOriginalUrlCookie(response);
}
LOGGER.aboutToRedirectToOriginal(Log4jAuditor.maskTokenFromURL(original));
response.setStatus(statusCode);
response.setHeader("Location", original);
try {
response.getOutputStream().close();
} catch (IOException e) {
LOGGER.unableToCloseOutputStream(e.getMessage(), Arrays.toString(e.getStackTrace()));
}
} catch (TokenServiceException | AliasServiceException e) {
LOGGER.unableToIssueToken(e);
}
URI location = null;
try {
location = new URI(original);
} catch (URISyntaxException urise) {
// todo log return error response
}
if (!enableSession) {
// invalidate the session to avoid autologin
// Coverity CID 1352857
HttpSession session = request.getSession(false);
if (session != null) {
session.invalidate();
}
}
return Response.seeOther(location).entity("{ \"redirectTo\" : " + original + " }").build();
}
Aggregations