Search in sources :

Example 81 with JwsJwtCompactConsumer

use of org.apache.cxf.rs.security.jose.jws.JwsJwtCompactConsumer in project security by opensearch-project.

the class HTTPSamlAuthenticatorTest method shouldNotEscapeSamlEntities.

@Test
public void shouldNotEscapeSamlEntities() 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]);
}
Also used : JwtToken(org.apache.cxf.rs.security.jose.jwt.JwtToken) FakeRestRequest(org.opensearch.security.util.FakeRestRequest) RestRequest(org.opensearch.rest.RestRequest) HashMap(java.util.HashMap) JwsJwtCompactConsumer(org.apache.cxf.rs.security.jose.jws.JwsJwtCompactConsumer) Settings(org.opensearch.common.settings.Settings) Test(org.junit.Test)

Example 82 with JwsJwtCompactConsumer

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"));
}
Also used : JwtToken(org.apache.cxf.rs.security.jose.jwt.JwtToken) FakeRestRequest(org.opensearch.security.util.FakeRestRequest) RestRequest(org.opensearch.rest.RestRequest) HashMap(java.util.HashMap) JwsJwtCompactConsumer(org.apache.cxf.rs.security.jose.jws.JwsJwtCompactConsumer) Settings(org.opensearch.common.settings.Settings) Test(org.junit.Test)

Example 83 with JwsJwtCompactConsumer

use of org.apache.cxf.rs.security.jose.jws.JwsJwtCompactConsumer in project security by opensearch-project.

the class HTTPSamlAuthenticatorTest method rolesTest.

@SuppressWarnings("unchecked")
@Test
public void rolesTest() throws Exception {
    mockSamlIdpServer.setSignResponses(true);
    mockSamlIdpServer.loadSigningKeys("saml/kirk-keystore.jks", "kirk");
    mockSamlIdpServer.setAuthenticateUser("horst");
    mockSamlIdpServer.setAuthenticateUserRoles(Arrays.asList("a ,c", "b   ,d,   e", "f", "g,,h, ,i"));
    mockSamlIdpServer.setEndpointQueryString(null);
    Settings settings = Settings.builder().put(IDP_METADATA_URL, mockSamlIdpServer.getMetadataUri()).put("kibana_url", "http://wherever").put("idp.entity_id", mockSamlIdpServer.getIdpEntityId()).put("exchange_key", "abc").put("roles_key", "roles").put("path.home", ".").put("roles_seperator", ",").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"));
    Assert.assertArrayEquals(new String[] { "a ", "c", "b   ", "d", "   e", "f", "g", "h", " ", "i" }, ((List<String>) jwt.getClaim("roles")).toArray(new String[0]));
}
Also used : JwtToken(org.apache.cxf.rs.security.jose.jwt.JwtToken) FakeRestRequest(org.opensearch.security.util.FakeRestRequest) RestRequest(org.opensearch.rest.RestRequest) HashMap(java.util.HashMap) JwsJwtCompactConsumer(org.apache.cxf.rs.security.jose.jws.JwsJwtCompactConsumer) Settings(org.opensearch.common.settings.Settings) Test(org.junit.Test)

Example 84 with JwsJwtCompactConsumer

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);
    }
}
Also used : JwtToken(org.apache.cxf.rs.security.jose.jwt.JwtToken) JwsSignatureVerifier(org.apache.cxf.rs.security.jose.jws.JwsSignatureVerifier) JsonWebKey(org.apache.cxf.rs.security.jose.jwk.JsonWebKey) JwsJwtCompactConsumer(org.apache.cxf.rs.security.jose.jws.JwsJwtCompactConsumer) JwtException(org.apache.cxf.rs.security.jose.jwt.JwtException)

Aggregations

JwsJwtCompactConsumer (org.apache.cxf.rs.security.jose.jws.JwsJwtCompactConsumer)84 JwtToken (org.apache.cxf.rs.security.jose.jwt.JwtToken)71 JWTTokenProvider (org.apache.cxf.sts.token.provider.jwt.JWTTokenProvider)33 WebClient (org.apache.cxf.jaxrs.client.WebClient)19 HashMap (java.util.HashMap)16 Response (javax.ws.rs.core.Response)15 Element (org.w3c.dom.Element)15 X509Certificate (java.security.cert.X509Certificate)14 KeyStore (java.security.KeyStore)13 JAXBElement (javax.xml.bind.JAXBElement)13 Crypto (org.apache.wss4j.common.crypto.Crypto)13 Settings (org.opensearch.common.settings.Settings)11 RestRequest (org.opensearch.rest.RestRequest)11 FakeRestRequest (org.opensearch.security.util.FakeRestRequest)11 URL (java.net.URL)10 ClaimsHandler (org.apache.cxf.sts.claims.ClaimsHandler)10 ClaimsManager (org.apache.cxf.sts.claims.ClaimsManager)10 CustomClaimsHandler (org.apache.cxf.sts.common.CustomClaimsHandler)10 CustomTokenPrincipal (org.apache.wss4j.common.principal.CustomTokenPrincipal)10 Test (org.junit.Test)10