Search in sources :

Example 21 with JwsJwtCompactConsumer

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

the class ValidateJWTTransformationTest method testSAMLToJWTTransformation.

@org.junit.Test
public void testSAMLToJWTTransformation() throws Exception {
    TokenValidateOperation validateOperation = new TokenValidateOperation();
    // Add Token Validator
    List<TokenValidator> validatorList = new ArrayList<>();
    validatorList.add(new SAMLTokenValidator());
    validateOperation.setTokenValidators(validatorList);
    // Add Token Provider
    List<TokenProvider> providerList = new ArrayList<>();
    providerList.add(new JWTTokenProvider());
    validateOperation.setTokenProviders(providerList);
    // Add STSProperties object
    STSPropertiesMBean stsProperties = new StaticSTSProperties();
    Crypto crypto = CryptoFactory.getInstance(getEncryptionProperties());
    stsProperties.setEncryptionCrypto(crypto);
    stsProperties.setSignatureCrypto(crypto);
    stsProperties.setEncryptionUsername("myservicekey");
    stsProperties.setSignatureUsername("mystskey");
    stsProperties.setCallbackHandler(new PasswordCallbackHandler());
    stsProperties.setIssuer("STS");
    validateOperation.setStsProperties(stsProperties);
    // Mock up a request
    RequestSecurityTokenType request = new RequestSecurityTokenType();
    JAXBElement<String> tokenType = new JAXBElement<String>(QNameConstants.TOKEN_TYPE, String.class, JWTTokenProvider.JWT_TOKEN_TYPE);
    request.getAny().add(tokenType);
    // Create a SAML Token
    Element samlToken = createSAMLAssertion(WSS4JConstants.WSS_SAML2_TOKEN_TYPE, crypto, "mystskey", new PasswordCallbackHandler());
    Document doc = samlToken.getOwnerDocument();
    samlToken = (Element) doc.appendChild(samlToken);
    ValidateTargetType validateTarget = new ValidateTargetType();
    validateTarget.setAny(samlToken);
    JAXBElement<ValidateTargetType> validateTargetType = new JAXBElement<ValidateTargetType>(QNameConstants.VALIDATE_TARGET, ValidateTargetType.class, validateTarget);
    request.getAny().add(validateTargetType);
    // Mock up message context
    MessageImpl msg = new MessageImpl();
    WrappedMessageContext msgCtx = new WrappedMessageContext(msg);
    Principal principal = new CustomTokenPrincipal("alice");
    msgCtx.put(SecurityContext.class.getName(), createSecurityContext(principal));
    // Validate a token
    RequestSecurityTokenResponseType response = validateOperation.validate(request, principal, msgCtx);
    assertTrue(validateResponse(response));
    // Test the generated token.
    Element token = null;
    for (Object tokenObject : response.getAny()) {
        if (tokenObject instanceof JAXBElement<?> && REQUESTED_SECURITY_TOKEN.equals(((JAXBElement<?>) tokenObject).getName())) {
            RequestedSecurityTokenType rstType = (RequestedSecurityTokenType) ((JAXBElement<?>) tokenObject).getValue();
            token = (Element) rstType.getAny();
            break;
        }
    }
    assertNotNull(token);
    JwsJwtCompactConsumer jwtConsumer = new JwsJwtCompactConsumer(token.getTextContent());
    JwtToken jwt = jwtConsumer.getJwtToken();
    Assert.assertEquals("alice", jwt.getClaim(JwtConstants.CLAIM_SUBJECT));
}
Also used : RequestSecurityTokenType(org.apache.cxf.ws.security.sts.provider.model.RequestSecurityTokenType) JAXBElement(javax.xml.bind.JAXBElement) Element(org.w3c.dom.Element) ArrayList(java.util.ArrayList) RequestSecurityTokenResponseType(org.apache.cxf.ws.security.sts.provider.model.RequestSecurityTokenResponseType) StaticSTSProperties(org.apache.cxf.sts.StaticSTSProperties) RequestedSecurityTokenType(org.apache.cxf.ws.security.sts.provider.model.RequestedSecurityTokenType) Document(org.w3c.dom.Document) CustomTokenPrincipal(org.apache.wss4j.common.principal.CustomTokenPrincipal) TokenProvider(org.apache.cxf.sts.token.provider.TokenProvider) JWTTokenProvider(org.apache.cxf.sts.token.provider.jwt.JWTTokenProvider) SAMLTokenProvider(org.apache.cxf.sts.token.provider.SAMLTokenProvider) JWTTokenValidator(org.apache.cxf.sts.token.validator.jwt.JWTTokenValidator) TokenValidator(org.apache.cxf.sts.token.validator.TokenValidator) SAMLTokenValidator(org.apache.cxf.sts.token.validator.SAMLTokenValidator) PasswordCallbackHandler(org.apache.cxf.sts.common.PasswordCallbackHandler) JwsJwtCompactConsumer(org.apache.cxf.rs.security.jose.jws.JwsJwtCompactConsumer) JWTTokenProvider(org.apache.cxf.sts.token.provider.jwt.JWTTokenProvider) JAXBElement(javax.xml.bind.JAXBElement) JwtToken(org.apache.cxf.rs.security.jose.jwt.JwtToken) Crypto(org.apache.wss4j.common.crypto.Crypto) STSPropertiesMBean(org.apache.cxf.sts.STSPropertiesMBean) WrappedMessageContext(org.apache.cxf.jaxws.context.WrappedMessageContext) SecurityContext(org.apache.cxf.security.SecurityContext) SAMLTokenValidator(org.apache.cxf.sts.token.validator.SAMLTokenValidator) ValidateTargetType(org.apache.cxf.ws.security.sts.provider.model.ValidateTargetType) MessageImpl(org.apache.cxf.message.MessageImpl) CustomTokenPrincipal(org.apache.wss4j.common.principal.CustomTokenPrincipal) Principal(java.security.Principal)

Example 22 with JwsJwtCompactConsumer

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

the class OAuth2JwtFiltersTest method doTestServiceWithJwtTokenAndScope.

private void doTestServiceWithJwtTokenAndScope(String oauthService, String rsAddress) throws Exception {
    URL busFile = OAuth2JwtFiltersTest.class.getResource("client.xml");
    // Get Authorization Code
    WebClient oauthClient = WebClient.create(oauthService, OAuth2TestUtils.setupProviders(), "alice", "security", busFile.toString());
    // Save the Cookie for the second request...
    WebClient.getConfig(oauthClient).getRequestContext().put(org.apache.cxf.message.Message.MAINTAIN_SESSION, Boolean.TRUE);
    String code = OAuth2TestUtils.getAuthorizationCode(oauthClient, "create_book");
    assertNotNull(code);
    // Now get the access token
    oauthClient = WebClient.create(oauthService, OAuth2TestUtils.setupProviders(), "consumer-id", "this-is-a-secret", busFile.toString());
    // Save the Cookie for the second request...
    WebClient.getConfig(oauthClient).getRequestContext().put(org.apache.cxf.message.Message.MAINTAIN_SESSION, Boolean.TRUE);
    ClientAccessToken accessToken = OAuth2TestUtils.getAccessTokenWithAuthorizationCode(oauthClient, code);
    assertNotNull(accessToken.getTokenKey());
    JwsJwtCompactConsumer jwtConsumer = new JwsJwtCompactConsumer(accessToken.getTokenKey());
    JwsSignatureVerifier verifier = JwsUtils.loadSignatureVerifier("org/apache/cxf/systest/jaxrs/security/alice.rs.properties", null);
    assertTrue(jwtConsumer.verifySignatureWith(verifier));
    JwtClaims claims = jwtConsumer.getJwtClaims();
    assertEquals("consumer-id", claims.getStringProperty(OAuthConstants.CLIENT_ID));
    assertEquals("alice", claims.getStringProperty("username"));
    // Now invoke on the service with the access token
    WebClient client = WebClient.create(rsAddress, OAuth2TestUtils.setupProviders(), busFile.toString());
    client.header("Authorization", "Bearer " + accessToken.getTokenKey());
    Response response = client.type("application/xml").post(new Book("book", 123L));
    assertEquals(200, response.getStatus());
    Book returnedBook = response.readEntity(Book.class);
    assertEquals(returnedBook.getName(), "book");
    assertEquals(returnedBook.getId(), 123L);
}
Also used : JwsSignatureVerifier(org.apache.cxf.rs.security.jose.jws.JwsSignatureVerifier) Response(javax.ws.rs.core.Response) JwtClaims(org.apache.cxf.rs.security.jose.jwt.JwtClaims) Book(org.apache.cxf.systest.jaxrs.security.Book) ClientAccessToken(org.apache.cxf.rs.security.oauth2.common.ClientAccessToken) JwsJwtCompactConsumer(org.apache.cxf.rs.security.jose.jws.JwsJwtCompactConsumer) WebClient(org.apache.cxf.jaxrs.client.WebClient) URL(java.net.URL)

Example 23 with JwsJwtCompactConsumer

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

the class OIDCFlowTest method testImplicitFlow.

@org.junit.Test
public void testImplicitFlow() throws Exception {
    URL busFile = OIDCFlowTest.class.getResource("client.xml");
    String address = "https://localhost:" + PORT + "/services/";
    WebClient client = WebClient.create(address, OAuth2TestUtils.setupProviders(), "alice", "security", busFile.toString());
    // Save the Cookie for the second request...
    WebClient.getConfig(client).getRequestContext().put(org.apache.cxf.message.Message.MAINTAIN_SESSION, Boolean.TRUE);
    // Get Access Token
    client.type("application/json").accept("application/json");
    client.query("client_id", "consumer-id");
    client.query("redirect_uri", "http://www.blah.apache.org");
    client.query("scope", "openid");
    client.query("response_type", "id_token token");
    client.query("nonce", "123456789");
    client.path("authorize-implicit/");
    Response response = client.get();
    OAuthAuthorizationData authzData = response.readEntity(OAuthAuthorizationData.class);
    // Now call "decision" to get the access token
    client.path("decision");
    client.type("application/x-www-form-urlencoded");
    Form form = new Form();
    form.param("session_authenticity_token", authzData.getAuthenticityToken());
    form.param("client_id", authzData.getClientId());
    form.param("redirect_uri", authzData.getRedirectUri());
    form.param("scope", authzData.getProposedScope());
    if (authzData.getResponseType() != null) {
        form.param("response_type", authzData.getResponseType());
    }
    if (authzData.getNonce() != null) {
        form.param("nonce", authzData.getNonce());
    }
    form.param("oauthDecision", "allow");
    response = client.post(form);
    String location = response.getHeaderString("Location");
    // Check Access Token
    String accessToken = OAuth2TestUtils.getSubstring(location, "access_token");
    assertNotNull(accessToken);
    // Check IdToken
    String idToken = OAuth2TestUtils.getSubstring(location, "id_token");
    assertNotNull(idToken);
    validateIdToken(idToken, null);
    JwsJwtCompactConsumer jwtConsumer = new JwsJwtCompactConsumer(idToken);
    JwtToken jwt = jwtConsumer.getJwtToken();
    Assert.assertNotNull(jwt.getClaims().getClaim(IdToken.ACCESS_TOKEN_HASH_CLAIM));
    Assert.assertNotNull(jwt.getClaims().getClaim(IdToken.NONCE_CLAIM));
    OidcUtils.validateAccessTokenHash(accessToken, jwt, true);
}
Also used : Response(javax.ws.rs.core.Response) JwtToken(org.apache.cxf.rs.security.jose.jwt.JwtToken) Form(javax.ws.rs.core.Form) JwsJwtCompactConsumer(org.apache.cxf.rs.security.jose.jws.JwsJwtCompactConsumer) WebClient(org.apache.cxf.jaxrs.client.WebClient) OAuthAuthorizationData(org.apache.cxf.rs.security.oauth2.common.OAuthAuthorizationData) URL(java.net.URL)

Example 24 with JwsJwtCompactConsumer

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

the class OIDCFlowTest method testImplicitFlowNoAccessToken.

@org.junit.Test
public void testImplicitFlowNoAccessToken() throws Exception {
    URL busFile = OIDCFlowTest.class.getResource("client.xml");
    String address = "https://localhost:" + PORT + "/services/";
    WebClient client = WebClient.create(address, OAuth2TestUtils.setupProviders(), "alice", "security", busFile.toString());
    // Save the Cookie for the second request...
    WebClient.getConfig(client).getRequestContext().put(org.apache.cxf.message.Message.MAINTAIN_SESSION, Boolean.TRUE);
    // Get Access Token
    client.type("application/json").accept("application/json");
    client.query("client_id", "consumer-id");
    client.query("redirect_uri", "http://www.blah.apache.org");
    client.query("scope", "openid");
    client.query("response_type", "id_token");
    client.query("nonce", "123456789");
    client.path("authorize-implicit/");
    Response response = client.get();
    OAuthAuthorizationData authzData = response.readEntity(OAuthAuthorizationData.class);
    // Now call "decision" to get the access token
    client.path("decision");
    client.type("application/x-www-form-urlencoded");
    Form form = new Form();
    form.param("session_authenticity_token", authzData.getAuthenticityToken());
    form.param("client_id", authzData.getClientId());
    form.param("redirect_uri", authzData.getRedirectUri());
    form.param("scope", authzData.getProposedScope());
    if (authzData.getResponseType() != null) {
        form.param("response_type", authzData.getResponseType());
    }
    if (authzData.getNonce() != null) {
        form.param("nonce", authzData.getNonce());
    }
    form.param("oauthDecision", "allow");
    response = client.post(form);
    String location = response.getHeaderString("Location");
    // Check Access Token - it should not be present
    String accessToken = OAuth2TestUtils.getSubstring(location, "access_token");
    assertNull(accessToken);
    // Check IdToken
    String idToken = OAuth2TestUtils.getSubstring(location, "id_token");
    assertNotNull(idToken);
    validateIdToken(idToken, null);
    JwsJwtCompactConsumer jwtConsumer = new JwsJwtCompactConsumer(idToken);
    JwtToken jwt = jwtConsumer.getJwtToken();
    Assert.assertNull(jwt.getClaims().getClaim(IdToken.ACCESS_TOKEN_HASH_CLAIM));
    Assert.assertNotNull(jwt.getClaims().getClaim(IdToken.NONCE_CLAIM));
}
Also used : Response(javax.ws.rs.core.Response) JwtToken(org.apache.cxf.rs.security.jose.jwt.JwtToken) Form(javax.ws.rs.core.Form) JwsJwtCompactConsumer(org.apache.cxf.rs.security.jose.jws.JwsJwtCompactConsumer) WebClient(org.apache.cxf.jaxrs.client.WebClient) OAuthAuthorizationData(org.apache.cxf.rs.security.oauth2.common.OAuthAuthorizationData) URL(java.net.URL)

Example 25 with JwsJwtCompactConsumer

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

the class OIDCFlowTest method testHybridCodeIdTokenToken.

@org.junit.Test
public void testHybridCodeIdTokenToken() throws Exception {
    URL busFile = OIDCFlowTest.class.getResource("client.xml");
    String address = "https://localhost:" + PORT + "/services/";
    WebClient client = WebClient.create(address, OAuth2TestUtils.setupProviders(), "alice", "security", busFile.toString());
    // Save the Cookie for the second request...
    WebClient.getConfig(client).getRequestContext().put(org.apache.cxf.message.Message.MAINTAIN_SESSION, Boolean.TRUE);
    // Get location
    AuthorizationCodeParameters parameters = new AuthorizationCodeParameters();
    parameters.setConsumerId("consumer-id");
    parameters.setScope("openid");
    parameters.setNonce("123456789");
    parameters.setResponseType("code id_token token");
    parameters.setPath("authorize-hybrid/");
    String location = OAuth2TestUtils.getLocation(client, parameters);
    assertNotNull(location);
    // Check code
    String code = OAuth2TestUtils.getSubstring(location, "code");
    assertNotNull(code);
    // Check id_token
    String idToken = OAuth2TestUtils.getSubstring(location, "id_token");
    assertNotNull(idToken);
    validateIdToken(idToken, "123456789");
    // check the code hash is returned from the implicit authorization endpoint
    JwsJwtCompactConsumer jwtConsumer = new JwsJwtCompactConsumer(idToken);
    JwtToken jwt = jwtConsumer.getJwtToken();
    Assert.assertNotNull(jwt.getClaims().getClaim(IdToken.AUTH_CODE_HASH_CLAIM));
    // Check Access Token
    String accessToken = OAuth2TestUtils.getSubstring(location, "access_token");
    assertNotNull(accessToken);
    jwtConsumer = new JwsJwtCompactConsumer(idToken);
    jwt = jwtConsumer.getJwtToken();
    Assert.assertNotNull(jwt.getClaims().getClaim(IdToken.ACCESS_TOKEN_HASH_CLAIM));
    OidcUtils.validateAccessTokenHash(accessToken, jwt, true);
    Assert.assertNotNull(jwt.getClaims().getClaim(IdToken.AUTH_CODE_HASH_CLAIM));
}
Also used : JwtToken(org.apache.cxf.rs.security.jose.jwt.JwtToken) AuthorizationCodeParameters(org.apache.cxf.systest.jaxrs.security.oauth2.common.OAuth2TestUtils.AuthorizationCodeParameters) JwsJwtCompactConsumer(org.apache.cxf.rs.security.jose.jws.JwsJwtCompactConsumer) WebClient(org.apache.cxf.jaxrs.client.WebClient) URL(java.net.URL)

Aggregations

JwsJwtCompactConsumer (org.apache.cxf.rs.security.jose.jws.JwsJwtCompactConsumer)76 JwtToken (org.apache.cxf.rs.security.jose.jwt.JwtToken)61 JWTTokenProvider (org.apache.cxf.sts.token.provider.jwt.JWTTokenProvider)33 Response (javax.ws.rs.core.Response)20 WebClient (org.apache.cxf.jaxrs.client.WebClient)18 URL (java.net.URL)17 Element (org.w3c.dom.Element)15 JAXBElement (javax.xml.bind.JAXBElement)13 Crypto (org.apache.wss4j.common.crypto.Crypto)13 KeyStore (java.security.KeyStore)12 X509Certificate (java.security.cert.X509Certificate)12 ArrayList (java.util.ArrayList)10 Date (java.util.Date)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 TokenProvider (org.apache.cxf.sts.token.provider.TokenProvider)9 Document (org.w3c.dom.Document)9 Certificate (java.security.cert.Certificate)8