use of org.apache.cxf.rs.security.jose.jws.JwsJwtCompactConsumer in project testcases by coheigea.
the class JWTTestIT method testAuthenticatedRequest.
@org.junit.Test
public void testAuthenticatedRequest() throws Exception {
SpringBusFactory bf = new SpringBusFactory();
URL busFile = JWTTestIT.class.getResource("cxf-client.xml");
Bus bus = bf.createBus(busFile.toString());
SpringBusFactory.setDefaultBus(bus);
SpringBusFactory.setThreadDefaultBus(bus);
// 1. Get a JWT Token from the STS via the REST interface for "alice"
String address = "https://localhost:" + STS_PORT + "/SecurityTokenService/token";
WebClient client = WebClient.create(address, "alice", "security", busFile.toString());
client.accept("text/plain");
client.path("jwt");
// sclient.query("appliesTo", "bob/service.ws.apache.org@service.ws.apache.org");
Response response = client.get();
String jwtToken = response.readEntity(String.class);
assertNotNull(jwtToken);
JwsJwtCompactConsumer jwtConsumer = new JwsJwtCompactConsumer(jwtToken);
JwtToken jwt = jwtConsumer.getJwtToken();
assertEquals("alice", jwt.getClaim(JwtConstants.CLAIM_SUBJECT));
// 2. Now use the JWT Token to authenticate to Syncope.
String syncopePort = System.getProperty("syncope.port");
SyncopeClientFactoryBean clientFactory = new SyncopeClientFactoryBean().setAddress("http://localhost:" + syncopePort + "/syncope/rest/");
SyncopeClient syncopeClient = clientFactory.create(jwtToken);
syncopeClient.self();
}
use of org.apache.cxf.rs.security.jose.jws.JwsJwtCompactConsumer in project testcases by coheigea.
the class JWTJAXRSAuthenticationTest method testJWTKerberosAccessTokenFailingAuthz.
@org.junit.Test
public void testJWTKerberosAccessTokenFailingAuthz() throws Exception {
URL busFile = JWTJAXRSAuthenticationTest.class.getResource("cxf-client-dave.xml");
// 1. Get a JWT Token from the STS via the REST interface for "alice"
String jwtToken = getJWTTokenFromSTS(busFile);
JwsJwtCompactConsumer jwtConsumer = new JwsJwtCompactConsumer(jwtToken);
JwtToken jwt = jwtConsumer.getJwtToken();
assertEquals("dave", jwt.getClaim(JwtConstants.CLAIM_SUBJECT));
assertTrue((jwt.getClaim(ROLE)).equals("employee"));
// 2. Now call on the service using a custom HttpAuthSupplier
String address = "https://localhost:" + PORT + "/doubleit/services";
WebClient client = WebClient.create(address, busFile.toString()).type("application/xml");
Map<String, Object> requestContext = WebClient.getConfig(client).getRequestContext();
requestContext.put("auth.spnego.useKerberosOid", "true");
KerbyHttpAuthSupplier authSupplier = new KerbyHttpAuthSupplier();
authSupplier.setServicePrincipalName("bob/service.ws.apache.org@service.ws.apache.org");
authSupplier.setServiceNameType(GSSName.NT_HOSTBASED_SERVICE);
authSupplier.setJwtToken(jwtToken);
WebClient.getConfig(client).getHttpConduit().setAuthSupplier(authSupplier);
Number numberToDouble = new Number();
numberToDouble.setDescription("This is the number to double");
numberToDouble.setNumber(25);
Response response = client.post(numberToDouble);
assertEquals(response.getStatus(), 500);
}
use of org.apache.cxf.rs.security.jose.jws.JwsJwtCompactConsumer in project security by opensearch-project.
the class JwtVerifier method getVerifiedJwtToken.
public JwtToken getVerifiedJwtToken(String encodedJwt) throws BadCredentialsException {
try {
JwsJwtCompactConsumer jwtConsumer = new JwsJwtCompactConsumer(encodedJwt);
JwtToken jwt = jwtConsumer.getJwtToken();
String escapedKid = jwt.getJwsHeaders().getKeyId();
String kid = escapedKid;
if (!Strings.isNullOrEmpty(kid)) {
kid = StringEscapeUtils.unescapeJava(escapedKid);
}
JsonWebKey key = keyProvider.getKey(kid);
// Algorithm is not mandatory for the key material, so we set it to the same as the JWT
if (key.getAlgorithm() == null && key.getPublicKeyUse() == PublicKeyUse.SIGN && key.getKeyType() == KeyType.RSA) {
key.setAlgorithm(jwt.getJwsHeaders().getAlgorithm());
}
JwsSignatureVerifier signatureVerifier = getInitializedSignatureVerifier(key, jwt);
boolean signatureValid = jwtConsumer.verifySignatureWith(signatureVerifier);
if (!signatureValid && Strings.isNullOrEmpty(kid)) {
key = keyProvider.getKeyAfterRefresh(null);
signatureVerifier = getInitializedSignatureVerifier(key, jwt);
signatureValid = jwtConsumer.verifySignatureWith(signatureVerifier);
}
if (!signatureValid) {
throw new BadCredentialsException("Invalid JWT signature");
}
validateClaims(jwt);
return jwt;
} catch (JwtException e) {
throw new BadCredentialsException(e.getMessage(), e);
}
}
use of org.apache.cxf.rs.security.jose.jws.JwsJwtCompactConsumer in project security by opensearch-project.
the class HTTPSamlAuthenticatorTest method shouldUnescapeSamlEntitiesTest.
@Test
public void shouldUnescapeSamlEntitiesTest() throws Exception {
mockSamlIdpServer.setAuthenticateUser("ABC\\User1");
mockSamlIdpServer.setEndpointQueryString(null);
mockSamlIdpServer.setSpSignatureCertificate(spSigningCertificate);
mockSamlIdpServer.setEncryptAssertion(true);
mockSamlIdpServer.setAuthenticateUserRoles(Arrays.asList("ABC\\Admin"));
Settings settings = Settings.builder().put(IDP_METADATA_URL, mockSamlIdpServer.getMetadataUri()).put("kibana_url", "http://wherever").put("idp.entity_id", mockSamlIdpServer.getIdpEntityId()).put("sp.signature_private_key", "-BEGIN PRIVATE KEY-\n" + Base64.getEncoder().encodeToString(spSigningPrivateKey.getEncoded()) + "-END PRIVATE KEY-").put("exchange_key", "abc").put("roles_key", "roles").put("path.home", ".").build();
HTTPSamlAuthenticator samlAuthenticator = new HTTPSamlAuthenticator(settings, null);
AuthenticateHeaders authenticateHeaders = getAutenticateHeaders(samlAuthenticator);
String encodedSamlResponse = mockSamlIdpServer.handleSsoGetRequestURI(authenticateHeaders.location);
RestRequest tokenRestRequest = buildTokenExchangeRestRequest(encodedSamlResponse, authenticateHeaders);
TestRestChannel tokenRestChannel = new TestRestChannel(tokenRestRequest);
samlAuthenticator.reRequestAuthentication(tokenRestChannel, null);
String responseJson = new String(BytesReference.toBytes(tokenRestChannel.response.content()));
HashMap<String, Object> response = DefaultObjectMapper.objectMapper.readValue(responseJson, new TypeReference<HashMap<String, Object>>() {
});
String authorization = (String) response.get("authorization");
Assert.assertNotNull("Expected authorization attribute in JSON: " + responseJson, authorization);
JwsJwtCompactConsumer jwtConsumer = new JwsJwtCompactConsumer(authorization.replaceAll("\\s*bearer\\s*", ""));
JwtToken jwt = jwtConsumer.getJwtToken();
Assert.assertEquals("ABC\\User1", jwt.getClaim("sub"));
Assert.assertEquals("ABC\\User1", samlAuthenticator.httpJwtAuthenticator.extractSubject(jwt.getClaims()));
Assert.assertEquals("[ABC\\Admin]", String.valueOf(jwt.getClaim("roles")));
Assert.assertEquals("ABC\\Admin", samlAuthenticator.httpJwtAuthenticator.extractRoles(jwt.getClaims())[0]);
}
use of org.apache.cxf.rs.security.jose.jws.JwsJwtCompactConsumer in project security by opensearch-project.
the class HTTPSamlAuthenticatorTest method testMetadataBody.
@Test
public void testMetadataBody() throws Exception {
mockSamlIdpServer.setSignResponses(true);
mockSamlIdpServer.loadSigningKeys("saml/kirk-keystore.jks", "kirk");
mockSamlIdpServer.setAuthenticateUser("horst");
mockSamlIdpServer.setEndpointQueryString(null);
// Note: We need to replace endpoint with mockSamlIdpServer endpoint
final String metadataBody = FileHelper.loadFile("saml/metadata.xml").replaceAll("http://localhost:33667/", mockSamlIdpServer.getMetadataUri());
Settings settings = Settings.builder().put(IDP_METADATA_CONTENT, metadataBody).put("kibana_url", "http://wherever").put("idp.entity_id", mockSamlIdpServer.getIdpEntityId()).put("exchange_key", "abc").put("roles_key", "roles").put("path.home", ".").build();
HTTPSamlAuthenticator samlAuthenticator = new HTTPSamlAuthenticator(settings, null);
AuthenticateHeaders authenticateHeaders = getAutenticateHeaders(samlAuthenticator);
String encodedSamlResponse = mockSamlIdpServer.handleSsoGetRequestURI(authenticateHeaders.location);
RestRequest tokenRestRequest = buildTokenExchangeRestRequest(encodedSamlResponse, authenticateHeaders);
TestRestChannel tokenRestChannel = new TestRestChannel(tokenRestRequest);
samlAuthenticator.reRequestAuthentication(tokenRestChannel, null);
String responseJson = new String(BytesReference.toBytes(tokenRestChannel.response.content()));
HashMap<String, Object> response = DefaultObjectMapper.objectMapper.readValue(responseJson, new TypeReference<HashMap<String, Object>>() {
});
String authorization = (String) response.get("authorization");
Assert.assertNotNull("Expected authorization attribute in JSON: " + responseJson, authorization);
JwsJwtCompactConsumer jwtConsumer = new JwsJwtCompactConsumer(authorization.replaceAll("\\s*bearer\\s*", ""));
JwtToken jwt = jwtConsumer.getJwtToken();
Assert.assertEquals("horst", jwt.getClaim("sub"));
}
Aggregations