Search in sources :

Example 76 with JwsJwtCompactConsumer

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();
}
Also used : Response(javax.ws.rs.core.Response) JwtToken(org.apache.cxf.rs.security.jose.jwt.JwtToken) Bus(org.apache.cxf.Bus) SpringBusFactory(org.apache.cxf.bus.spring.SpringBusFactory) SyncopeClientFactoryBean(org.apache.syncope.client.lib.SyncopeClientFactoryBean) JwsJwtCompactConsumer(org.apache.cxf.rs.security.jose.jws.JwsJwtCompactConsumer) WebClient(org.apache.cxf.jaxrs.client.WebClient) URL(java.net.URL) SyncopeClient(org.apache.syncope.client.lib.SyncopeClient)

Example 77 with JwsJwtCompactConsumer

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);
}
Also used : JwtToken(org.apache.cxf.rs.security.jose.jwt.JwtToken) Response(javax.ws.rs.core.Response) JwsJwtCompactConsumer(org.apache.cxf.rs.security.jose.jws.JwsJwtCompactConsumer) WebClient(org.apache.cxf.jaxrs.client.WebClient) URL(java.net.URL)

Example 78 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)

Example 79 with JwsJwtCompactConsumer

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]);
}
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 80 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)

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