org.apache.cxf.rs.security.jose.jws.JwsJwtCompactConsumer Java Examples

The following examples show how to use org.apache.cxf.rs.security.jose.jws.JwsJwtCompactConsumer. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: JWTTokenProviderTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@org.junit.Test
public void testCachedSignedJWT() throws Exception {
    TokenProvider jwtTokenProvider = new JWTTokenProvider();
    ((JWTTokenProvider)jwtTokenProvider).setSignToken(true);

    TokenProviderParameters providerParameters = createProviderParameters();

    assertTrue(jwtTokenProvider.canHandleToken(JWTTokenProvider.JWT_TOKEN_TYPE));
    TokenProviderResponse providerResponse = jwtTokenProvider.createToken(providerParameters);
    assertNotNull(providerResponse);
    assertTrue(providerResponse.getToken() != null && providerResponse.getTokenId() != null);

    String token = (String)providerResponse.getToken();
    assertNotNull(token);
    assertTrue(token.split("\\.").length == 3);

    // Validate the token
    JwsJwtCompactConsumer jwtConsumer = new JwsJwtCompactConsumer(token);
    JwtToken jwt = jwtConsumer.getJwtToken();
    Assert.assertEquals("alice", jwt.getClaim(JwtConstants.CLAIM_SUBJECT));
    Assert.assertEquals(providerResponse.getTokenId(), jwt.getClaim(JwtConstants.CLAIM_JWT_ID));
    Assert.assertEquals(providerResponse.getCreated().getEpochSecond(),
                        jwt.getClaim(JwtConstants.CLAIM_ISSUED_AT));
    Assert.assertEquals(providerResponse.getExpires().getEpochSecond(),
                        jwt.getClaim(JwtConstants.CLAIM_EXPIRY));
}
 
Example #2
Source File: OIDCFlowTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
private void validateAccessToken(String accessToken)
    throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException {
    JwsJwtCompactConsumer jwtConsumer = new JwsJwtCompactConsumer(accessToken);
    JwtToken jwt = jwtConsumer.getJwtToken();

    // Validate claims
    assertNotNull(jwt.getClaim(JwtConstants.CLAIM_SUBJECT));
    assertNotNull(jwt.getClaim(JwtConstants.CLAIM_EXPIRY));
    assertNotNull(jwt.getClaim(JwtConstants.CLAIM_ISSUED_AT));

    KeyStore keystore = KeyStore.getInstance("JKS");
    keystore.load(ClassLoaderUtils.getResourceAsStream("keys/alice.jks", this.getClass()),
                  "password".toCharArray());
    Certificate cert = keystore.getCertificate("alice");
    assertNotNull(cert);

    assertTrue(jwtConsumer.verifySignatureWith((X509Certificate)cert,
                                                      SignatureAlgorithm.RS256));
}
 
Example #3
Source File: AbstractOIDCTest.java    From cxf-fediz with Apache License 2.0 6 votes vote down vote up
private void validateIdToken(String idToken, String audience, String role) throws IOException {
    JwsJwtCompactConsumer jwtConsumer = new JwsJwtCompactConsumer(idToken);
    JwtToken jwt = jwtConsumer.getJwtToken();
    JwtClaims jwtClaims = jwt.getClaims();

    // Validate claims
    assertEquals("alice", jwtClaims.getClaim("preferred_username"));
    assertEquals("accounts.fediz.com", jwtClaims.getIssuer());
    assertEquals(audience, jwtClaims.getAudience());
    assertNotNull(jwtClaims.getIssuedAt());
    assertNotNull(jwtClaims.getExpiryTime());

    // Check role
    if (role != null) {
        List<String> roles = jwtClaims.getListStringProperty("roles");
        assertNotNull(roles);
        assertTrue(roles.contains(role));
    }

    JwsHeaders jwsHeaders = jwt.getJwsHeaders();
    assertTrue(jwtConsumer.verifySignatureWith(
        jsonWebKeys().getKey(jwsHeaders.getKeyId()), SignatureAlgorithm.valueOf(jwsHeaders.getAlgorithm())));
}
 
Example #4
Source File: OIDCFlowTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
private void validateIdToken(String idToken, String nonce)
    throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException {
    JwsJwtCompactConsumer jwtConsumer = new JwsJwtCompactConsumer(idToken);
    JwtToken jwt = jwtConsumer.getJwtToken();

    // Validate claims
    assertEquals("alice", jwt.getClaim(JwtConstants.CLAIM_SUBJECT));
    assertEquals("OIDC IdP", jwt.getClaim(JwtConstants.CLAIM_ISSUER));
    assertEquals("consumer-id", jwt.getClaim(JwtConstants.CLAIM_AUDIENCE));
    assertNotNull(jwt.getClaim(JwtConstants.CLAIM_EXPIRY));
    assertNotNull(jwt.getClaim(JwtConstants.CLAIM_ISSUED_AT));
    if (nonce != null) {
        assertEquals(nonce, jwt.getClaim(IdToken.NONCE_CLAIM));
    }

    KeyStore keystore = KeyStore.getInstance("JKS");
    keystore.load(ClassLoaderUtils.getResourceAsStream("keys/alice.jks", this.getClass()),
                  "password".toCharArray());
    Certificate cert = keystore.getCertificate("alice");
    assertNotNull(cert);

    assertTrue(jwtConsumer.verifySignatureWith((X509Certificate)cert,
                                                      SignatureAlgorithm.RS256));
}
 
Example #5
Source File: UserInfoTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
private void validateIdToken(String idToken, String nonce)
    throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException {
    JwsJwtCompactConsumer jwtConsumer = new JwsJwtCompactConsumer(idToken);
    JwtToken jwt = jwtConsumer.getJwtToken();

    // Validate claims
    assertEquals("alice", jwt.getClaim(JwtConstants.CLAIM_SUBJECT));
    assertEquals("OIDC IdP", jwt.getClaim(JwtConstants.CLAIM_ISSUER));
    assertEquals("consumer-id", jwt.getClaim(JwtConstants.CLAIM_AUDIENCE));
    assertNotNull(jwt.getClaim(JwtConstants.CLAIM_EXPIRY));
    assertNotNull(jwt.getClaim(JwtConstants.CLAIM_ISSUED_AT));
    if (nonce != null) {
        assertEquals(nonce, jwt.getClaim(IdToken.NONCE_CLAIM));
    }

    KeyStore keystore = KeyStore.getInstance("JKS");
    keystore.load(ClassLoaderUtils.getResourceAsStream("keys/alice.jks", this.getClass()),
                  "password".toCharArray());
    Certificate cert = keystore.getCertificate("alice");
    assertNotNull(cert);

    assertTrue(jwtConsumer.verifySignatureWith((X509Certificate)cert,
                                                      SignatureAlgorithm.RS256));
}
 
Example #6
Source File: JWTTokenValidator.java    From cxf with Apache License 2.0 6 votes vote down vote up
/**
 * Return true if this TokenValidator implementation is capable of validating the
 * ReceivedToken argument. The realm is ignored in this Validator.
 */
public boolean canHandleToken(ReceivedToken validateTarget, String realm) {
    Object token = validateTarget.getToken();
    if (token instanceof Element) {
        Element tokenEl = (Element)token;
        if (tokenEl.getFirstChild().getNodeType() == org.w3c.dom.Node.TEXT_NODE) {
            try {
                JwsJwtCompactConsumer jwtConsumer = new JwsJwtCompactConsumer(tokenEl.getTextContent());
                if (jwtConsumer.getJwtToken() != null) {
                    return true;
                }
            } catch (RuntimeException ex) {
                return false;
            }
        }
    }
    return false;
}
 
Example #7
Source File: STSRESTTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
private static JwtToken validateJWTToken(String token)
    throws Exception {
    assertNotNull(token);
    JwsJwtCompactConsumer jwtConsumer = new JwsJwtCompactConsumer(token);
    JwtToken jwt = jwtConsumer.getJwtToken();

    // Validate claims
    assertEquals("DoubleItSTSIssuer", jwt.getClaims().getIssuer());
    assertNotNull(jwt.getClaims().getExpiryTime());
    assertNotNull(jwt.getClaims().getIssuedAt());

    CryptoType alias = new CryptoType(CryptoType.TYPE.ALIAS);
    alias.setAlias("mystskey");
    X509Certificate stsCertificate = serviceCrypto.getX509Certificates(alias)[0];
    assertTrue(jwtConsumer.verifySignatureWith(stsCertificate, SignatureAlgorithm.RS256));

    return jwt;
}
 
Example #8
Source File: JWTTokenProviderTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@org.junit.Test
public void testCreateUnsignedJWT() throws Exception {
    TokenProvider jwtTokenProvider = new JWTTokenProvider();
    ((JWTTokenProvider)jwtTokenProvider).setSignToken(false);

    TokenProviderParameters providerParameters = createProviderParameters();

    assertTrue(jwtTokenProvider.canHandleToken(JWTTokenProvider.JWT_TOKEN_TYPE));
    TokenProviderResponse providerResponse = jwtTokenProvider.createToken(providerParameters);
    assertNotNull(providerResponse);
    assertTrue(providerResponse.getToken() != null && providerResponse.getTokenId() != null);

    String token = (String)providerResponse.getToken();
    assertNotNull(token);
    assertTrue(token.split("\\.").length == 2);

    // Validate the token
    JwsJwtCompactConsumer jwtConsumer = new JwsJwtCompactConsumer(token);
    JwtToken jwt = jwtConsumer.getJwtToken();
    Assert.assertEquals("alice", jwt.getClaim(JwtConstants.CLAIM_SUBJECT));
    Assert.assertEquals(providerResponse.getTokenId(), jwt.getClaim(JwtConstants.CLAIM_JWT_ID));
    Assert.assertEquals(providerResponse.getCreated().getEpochSecond(),
                        jwt.getClaim(JwtConstants.CLAIM_ISSUED_AT));
    Assert.assertEquals(providerResponse.getExpires().getEpochSecond(),
                        jwt.getClaim(JwtConstants.CLAIM_EXPIRY));
}
 
Example #9
Source File: AuthorizationGrantTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
private static void validateAccessToken(String accessToken)
    throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException {
    JwsJwtCompactConsumer jwtConsumer = new JwsJwtCompactConsumer(accessToken);
    JwtClaims jwtClaims = jwtConsumer.getJwtToken().getClaims();

    // Validate claims
    if (!OAuthConstants.CLIENT_CREDENTIALS_GRANT.equals(jwtClaims.getStringProperty(OAuthConstants.GRANT_TYPE))) {
        // We don't have a Subject for the client credential grant
        assertNotNull(jwtClaims.getSubject());
    }
    assertNotNull(jwtClaims.getIssuedAt());
    assertNotNull(jwtClaims.getExpiryTime());
    assertEquals(ISSUER, jwtClaims.getIssuer());

    KeyStore keystore = KeyStore.getInstance("JKS");
    keystore.load(ClassLoaderUtils.getResourceAsStream("keys/alice.jks", AuthorizationGrantTest.class),
                  "password".toCharArray());
    Certificate cert = keystore.getCertificate("alice");
    assertNotNull(cert);

    assertTrue(jwtConsumer.verifySignatureWith((X509Certificate)cert,
                                                      SignatureAlgorithm.RS256));
}
 
Example #10
Source File: JWTProviderLifetimeTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
/**
 * Issue JWT token with no Expires element. This will be rejected, but will default to the
 * configured TTL and so the request will pass.
 */
@org.junit.Test
public void testJWTNoExpires() throws Exception {

    JWTTokenProvider tokenProvider = new JWTTokenProvider();
    DefaultJWTClaimsProvider claimsProvider = new DefaultJWTClaimsProvider();
    claimsProvider.setAcceptClientLifetime(true);
    tokenProvider.setJwtClaimsProvider(claimsProvider);

    TokenProviderParameters providerParameters =
        createProviderParameters(JWTTokenProvider.JWT_TOKEN_TYPE);

    // Set expected lifetime to 1 minute
    Instant creationTime = Instant.now().plusSeconds(120L);

    Lifetime lifetime = new Lifetime();
    lifetime.setCreated(creationTime.atZone(ZoneOffset.UTC).format(DateUtil.getDateTimeFormatter(true)));

    providerParameters.getTokenRequirements().setLifetime(lifetime);

    TokenProviderResponse providerResponse = tokenProvider.createToken(providerParameters);
    assertNotNull(providerResponse);
    assertTrue(providerResponse.getToken() != null && providerResponse.getTokenId() != null);
    long duration = Duration.between(providerResponse.getCreated(), providerResponse.getExpires()).getSeconds();
    assertEquals(claimsProvider.getLifetime(), duration);

    String token = (String)providerResponse.getToken();
    assertNotNull(token);

    JwsJwtCompactConsumer jwtConsumer = new JwsJwtCompactConsumer(token);
    JwtToken jwt = jwtConsumer.getJwtToken();
    assertEquals(jwt.getClaim(JwtConstants.CLAIM_ISSUED_AT), providerResponse.getCreated().getEpochSecond());
}
 
Example #11
Source File: JWTProviderActAsTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
/**
 * Create a JWT Token with ActAs from a UsernameToken
 */
@org.junit.Test
public void testJWTActAsUsernameToken() throws Exception {
    TokenProvider tokenProvider = new JWTTokenProvider();

    UsernameTokenType usernameToken = new UsernameTokenType();
    AttributedString username = new AttributedString();
    username.setValue("bob");
    usernameToken.setUsername(username);
    JAXBElement<UsernameTokenType> usernameTokenType =
        new JAXBElement<UsernameTokenType>(
            QNameConstants.USERNAME_TOKEN, UsernameTokenType.class, usernameToken
        );

    TokenProviderParameters providerParameters =
        createProviderParameters(
            JWTTokenProvider.JWT_TOKEN_TYPE, usernameTokenType
        );
    //Principal must be set in ReceivedToken/ActAs
    providerParameters.getTokenRequirements().getActAs().setPrincipal(
            new CustomTokenPrincipal(username.getValue()));

    assertTrue(tokenProvider.canHandleToken(JWTTokenProvider.JWT_TOKEN_TYPE));
    TokenProviderResponse providerResponse = tokenProvider.createToken(providerParameters);
    assertNotNull(providerResponse);
    assertTrue(providerResponse.getToken() != null && providerResponse.getTokenId() != null);

    String token = (String)providerResponse.getToken();
    assertNotNull(token);

    // Validate the token
    JwsJwtCompactConsumer jwtConsumer = new JwsJwtCompactConsumer(token);
    JwtToken jwt = jwtConsumer.getJwtToken();
    Assert.assertEquals("technical-user", jwt.getClaim(JwtConstants.CLAIM_SUBJECT));
    Assert.assertEquals("bob", jwt.getClaim("ActAs"));
}
 
Example #12
Source File: JWTTokenProviderTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void testCreateSignedJWT() throws Exception {
    TokenProvider jwtTokenProvider = new JWTTokenProvider();
    ((JWTTokenProvider)jwtTokenProvider).setSignToken(true);

    TokenProviderParameters providerParameters = createProviderParameters();

    assertTrue(jwtTokenProvider.canHandleToken(JWTTokenProvider.JWT_TOKEN_TYPE));
    TokenProviderResponse providerResponse = jwtTokenProvider.createToken(providerParameters);
    assertNotNull(providerResponse);
    assertTrue(providerResponse.getToken() != null && providerResponse.getTokenId() != null);

    String token = (String)providerResponse.getToken();
    assertNotNull(token);
    assertTrue(token.split("\\.").length == 3);

    // Validate the token
    JwsJwtCompactConsumer jwtConsumer = new JwsJwtCompactConsumer(token);
    JwtToken jwt = jwtConsumer.getJwtToken();
    Assert.assertEquals("alice", jwt.getClaim(JwtConstants.CLAIM_SUBJECT));
    Assert.assertEquals(providerResponse.getTokenId(), jwt.getClaim(JwtConstants.CLAIM_JWT_ID));
    Assert.assertEquals(providerResponse.getCreated().getEpochSecond(),
                        jwt.getClaim(JwtConstants.CLAIM_ISSUED_AT));
    Assert.assertEquals(providerResponse.getExpires().getEpochSecond(),
                        jwt.getClaim(JwtConstants.CLAIM_EXPIRY));

    // Verify Signature
    Crypto crypto = providerParameters.getStsProperties().getSignatureCrypto();
    CryptoType cryptoType = new CryptoType(CryptoType.TYPE.ALIAS);
    cryptoType.setAlias(providerParameters.getStsProperties().getSignatureUsername());
    X509Certificate[] certs = crypto.getX509Certificates(cryptoType);
    assertNotNull(certs);

    assertTrue(jwtConsumer.verifySignatureWith(certs[0], SignatureAlgorithm.RS256));
}
 
Example #13
Source File: JAXRSOAuth2TlsTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
private void doTestTwoWayTLSClientIdBoundJwt(String clientId) throws Exception {
    String atServiceAddress = "https://localhost:" + PORT + "/oauth2Jwt/token";
    WebClient wc = createOAuth2WebClient(atServiceAddress);

    ClientAccessToken at = OAuthClientUtils.getAccessToken(wc, new Consumer(clientId),
                                                           new CustomGrant());
    assertNotNull(at.getTokenKey());
    JwsJwtCompactConsumer c = new JwsJwtCompactConsumer(at.getTokenKey());
    JwtClaims claims = JwtUtils.jsonToClaims(c.getDecodedJwsPayload());

    Map<String, Object> cnfs = claims.getMapProperty(JwtConstants.CLAIM_CONFIRMATION);
    assertNotNull(cnfs);
    assertNotNull(cnfs.get(JoseConstants.HEADER_X509_THUMBPRINT_SHA256));

    String protectedRsAddress = "https://localhost:" + PORT + "/rsJwt/bookstore/books/123";
    WebClient wcRs = createRsWebClient(protectedRsAddress, at, "client.xml");
    Book book = wcRs.get(Book.class);
    assertEquals(123L, book.getId());

    String protectedRsAddress2 = "https://localhost:" + PORT + "/rsJwt2/bookstore/books/123";
    WebClient wcRs2 = createRsWebClient(protectedRsAddress2, at, "client.xml");
    book = wcRs2.get(Book.class);
    assertEquals(123L, book.getId());

    String unprotectedRsAddress = "https://localhost:" + PORT + "/rsUnprotected/bookstore/books/123";
    WebClient wcRsDiffClientCert = createRsWebClient(unprotectedRsAddress, at, "client2.xml");
    // Unprotected resource
    book = wcRsDiffClientCert.get(Book.class);
    assertEquals(123L, book.getId());

    // Protected resource, access token was created with Morpit.jks key, RS is accessed with
    // Bethal.jks key, thus 401 is expected
    wcRsDiffClientCert = createRsWebClient(protectedRsAddress, at, "client2.xml");
    assertEquals(401, wcRsDiffClientCert.get().getStatus());
    wcRsDiffClientCert = createRsWebClient(protectedRsAddress2, at, "client2.xml");
    assertEquals(401, wcRsDiffClientCert.get().getStatus());
}
 
Example #14
Source File: JWTClaimsTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void testJWTRoleUsingURI() throws Exception {
    TokenProvider tokenProvider = new JWTTokenProvider();
    TokenProviderParameters providerParameters =
        createProviderParameters(JWTTokenProvider.JWT_TOKEN_TYPE, null);

    ClaimsManager claimsManager = new ClaimsManager();
    ClaimsHandler claimsHandler = new CustomClaimsHandler();
    claimsManager.setClaimHandlers(Collections.singletonList(claimsHandler));
    providerParameters.setClaimsManager(claimsManager);

    ClaimCollection claims = new ClaimCollection();

    URI role = URI.create("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/role");

    Claim claim = new Claim();
    claim.setClaimType(role);
    claims.add(claim);

    providerParameters.setRequestedPrimaryClaims(claims);

    assertTrue(tokenProvider.canHandleToken(JWTTokenProvider.JWT_TOKEN_TYPE));
    TokenProviderResponse providerResponse = tokenProvider.createToken(providerParameters);
    assertNotNull(providerResponse);
    assertTrue(providerResponse.getToken() != null && providerResponse.getTokenId() != null);

    String token = (String)providerResponse.getToken();
    assertNotNull(token);

    JwsJwtCompactConsumer jwtConsumer = new JwsJwtCompactConsumer(token);
    JwtToken jwt = jwtConsumer.getJwtToken();
    assertEquals(jwt.getClaim(role.toString()), "DUMMY");
}
 
Example #15
Source File: JWTClaimsTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void testJWTRoleUsingCustomReturnType() throws Exception {
    TokenProvider tokenProvider = new JWTTokenProvider();
    TokenProviderParameters providerParameters =
        createProviderParameters(JWTTokenProvider.JWT_TOKEN_TYPE, null);

    ClaimsManager claimsManager = new ClaimsManager();
    ClaimsHandler claimsHandler = new CustomClaimsHandler();
    claimsManager.setClaimHandlers(Collections.singletonList(claimsHandler));
    providerParameters.setClaimsManager(claimsManager);

    ClaimCollection claims = new ClaimCollection();

    URI role = URI.create("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/role");

    Claim claim = new Claim();
    claim.setClaimType(role);
    claims.add(claim);

    providerParameters.setRequestedPrimaryClaims(claims);

    Map<String, String> claimTypeMap = new HashMap<>();
    claimTypeMap.put(role.toString(), "roles");
    DefaultJWTClaimsProvider claimsProvider = new DefaultJWTClaimsProvider();
    claimsProvider.setClaimTypeMap(claimTypeMap);
    ((JWTTokenProvider)tokenProvider).setJwtClaimsProvider(claimsProvider);

    assertTrue(tokenProvider.canHandleToken(JWTTokenProvider.JWT_TOKEN_TYPE));
    TokenProviderResponse providerResponse = tokenProvider.createToken(providerParameters);
    assertNotNull(providerResponse);
    assertTrue(providerResponse.getToken() != null && providerResponse.getTokenId() != null);

    String token = (String)providerResponse.getToken();
    assertNotNull(token);

    JwsJwtCompactConsumer jwtConsumer = new JwsJwtCompactConsumer(token);
    JwtToken jwt = jwtConsumer.getJwtToken();
    assertEquals(jwt.getClaim("roles"), "DUMMY");
}
 
Example #16
Source File: IssueJWTRealmUnitTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
private void validateToken(String token, String issuer, String sigUsername, Crypto sigCrypto) throws Exception {
    JwsJwtCompactConsumer jwtConsumer = new JwsJwtCompactConsumer(token);
    JwtToken jwt = jwtConsumer.getJwtToken();
    Assert.assertEquals(issuer, jwt.getClaim(JwtConstants.CLAIM_ISSUER));

    CryptoType cryptoType = new CryptoType(CryptoType.TYPE.ALIAS);
    cryptoType.setAlias(sigUsername);
    X509Certificate[] certs = sigCrypto.getX509Certificates(cryptoType);
    assertNotNull(certs);

    assertTrue(jwtConsumer.verifySignatureWith(certs[0], SignatureAlgorithm.RS256));
}
 
Example #17
Source File: JWTClaimsTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
/**
 * Test the creation of a JWTToken with various claims set by a ClaimsHandler.
 */
@org.junit.Test
public void testJWTClaims() throws Exception {
    TokenProvider tokenProvider = new JWTTokenProvider();
    TokenProviderParameters providerParameters =
        createProviderParameters(JWTTokenProvider.JWT_TOKEN_TYPE, null);

    ClaimsManager claimsManager = new ClaimsManager();
    ClaimsHandler claimsHandler = new CustomClaimsHandler();
    claimsManager.setClaimHandlers(Collections.singletonList(claimsHandler));
    providerParameters.setClaimsManager(claimsManager);

    ClaimCollection claims = createClaims();
    providerParameters.setRequestedPrimaryClaims(claims);

    assertTrue(tokenProvider.canHandleToken(JWTTokenProvider.JWT_TOKEN_TYPE));
    TokenProviderResponse providerResponse = tokenProvider.createToken(providerParameters);
    assertNotNull(providerResponse);
    assertTrue(providerResponse.getToken() != null && providerResponse.getTokenId() != null);

    String token = (String)providerResponse.getToken();
    assertNotNull(token);

    JwsJwtCompactConsumer jwtConsumer = new JwsJwtCompactConsumer(token);
    JwtToken jwt = jwtConsumer.getJwtToken();
    assertEquals(jwt.getClaim(ClaimTypes.EMAILADDRESS.toString()), "[email protected]");
    assertEquals(jwt.getClaim(ClaimTypes.FIRSTNAME.toString()), "alice");
    assertEquals(jwt.getClaim(ClaimTypes.LASTNAME.toString()), "doe");
}
 
Example #18
Source File: JWTClaimsTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
/**
 * Test the creation of a JWTToken with various claims set by a ClaimsHandler.
 * We have both a primary claim (sent in wst:RequestSecurityToken) and a secondary claim
 * (send in wst:RequestSecurityToken/wst:SecondaryParameters).
 */
@org.junit.Test
public void testJWTMultipleClaims() throws Exception {
    TokenProvider tokenProvider = new JWTTokenProvider();
    TokenProviderParameters providerParameters =
        createProviderParameters(JWTTokenProvider.JWT_TOKEN_TYPE, null);

    ClaimsManager claimsManager = new ClaimsManager();
    ClaimsHandler claimsHandler = new CustomClaimsHandler();
    claimsManager.setClaimHandlers(Collections.singletonList(claimsHandler));
    providerParameters.setClaimsManager(claimsManager);

    ClaimCollection primaryClaims = createClaims();
    providerParameters.setRequestedPrimaryClaims(primaryClaims);

    ClaimCollection secondaryClaims = new ClaimCollection();
    Claim claim = new Claim();
    claim.setClaimType(ClaimTypes.STREETADDRESS);
    secondaryClaims.add(claim);
    providerParameters.setRequestedSecondaryClaims(secondaryClaims);

    TokenProviderResponse providerResponse = tokenProvider.createToken(providerParameters);
    assertNotNull(providerResponse);
    assertTrue(providerResponse.getToken() != null && providerResponse.getTokenId() != null);

    String token = (String)providerResponse.getToken();
    assertNotNull(token);

    JwsJwtCompactConsumer jwtConsumer = new JwsJwtCompactConsumer(token);
    JwtToken jwt = jwtConsumer.getJwtToken();
    assertEquals(jwt.getClaim(ClaimTypes.EMAILADDRESS.toString()), "[email protected]");
    assertEquals(jwt.getClaim(ClaimTypes.FIRSTNAME.toString()), "alice");
    assertEquals(jwt.getClaim(ClaimTypes.LASTNAME.toString()), "doe");
    assertEquals(jwt.getClaim(ClaimTypes.STREETADDRESS.toString()), "1234 1st Street");
}
 
Example #19
Source File: JWTClaimsTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
/**
 * Test the creation of a JWTToken with various claims set by a ClaimsHandler.
 * We have both a primary claim (sent in wst:RequestSecurityToken) and a secondary claim
 * (send in wst:RequestSecurityToken/wst:SecondaryParameters), and both have the
 * same dialect in this test.
 */
@org.junit.Test
public void testJWTMultipleClaimsSameDialect() throws Exception {
    TokenProvider tokenProvider = new JWTTokenProvider();
    TokenProviderParameters providerParameters =
        createProviderParameters(JWTTokenProvider.JWT_TOKEN_TYPE, null);

    ClaimsManager claimsManager = new ClaimsManager();
    ClaimsHandler claimsHandler = new CustomClaimsHandler();
    claimsManager.setClaimHandlers(Collections.singletonList(claimsHandler));
    providerParameters.setClaimsManager(claimsManager);

    ClaimCollection primaryClaims = createClaims();
    primaryClaims.setDialect(ClaimTypes.URI_BASE);
    providerParameters.setRequestedPrimaryClaims(primaryClaims);

    ClaimCollection secondaryClaims = new ClaimCollection();
    Claim claim = new Claim();
    claim.setClaimType(ClaimTypes.STREETADDRESS);
    secondaryClaims.add(claim);
    secondaryClaims.setDialect(ClaimTypes.URI_BASE);
    providerParameters.setRequestedSecondaryClaims(secondaryClaims);

    TokenProviderResponse providerResponse = tokenProvider.createToken(providerParameters);
    assertNotNull(providerResponse);
    assertTrue(providerResponse.getToken() != null && providerResponse.getTokenId() != null);

    String token = (String)providerResponse.getToken();
    assertNotNull(token);

    JwsJwtCompactConsumer jwtConsumer = new JwsJwtCompactConsumer(token);
    JwtToken jwt = jwtConsumer.getJwtToken();
    assertEquals(jwt.getClaim(ClaimTypes.EMAILADDRESS.toString()), "[email protected]");
    assertEquals(jwt.getClaim(ClaimTypes.FIRSTNAME.toString()), "alice");
    assertEquals(jwt.getClaim(ClaimTypes.LASTNAME.toString()), "doe");
    assertEquals(jwt.getClaim(ClaimTypes.STREETADDRESS.toString()), "1234 1st Street");
}
 
Example #20
Source File: JWTClaimsTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
/**
 * Test the creation of a JWTToken with StaticClaimsHandler
 */
@org.junit.Test
public void testJWTStaticClaims() throws Exception {
    TokenProvider tokenProvider = new JWTTokenProvider();
    TokenProviderParameters providerParameters =
        createProviderParameters(JWTTokenProvider.JWT_TOKEN_TYPE, null);

    ClaimsManager claimsManager = new ClaimsManager();
    StaticClaimsHandler claimsHandler = new StaticClaimsHandler();
    Map<String, String> staticClaimsMap = new HashMap<>();
    staticClaimsMap.put(CLAIM_STATIC_COMPANY.toString(), CLAIM_STATIC_COMPANY_VALUE);
    claimsHandler.setGlobalClaims(staticClaimsMap);
    claimsManager.setClaimHandlers(Collections.singletonList((ClaimsHandler)claimsHandler));
    providerParameters.setClaimsManager(claimsManager);

    ClaimCollection claims = new ClaimCollection();
    Claim claim = new Claim();
    claim.setClaimType(CLAIM_STATIC_COMPANY);
    claims.add(claim);
    providerParameters.setRequestedPrimaryClaims(claims);

    TokenProviderResponse providerResponse = tokenProvider.createToken(providerParameters);
    assertNotNull(providerResponse);
    assertTrue(providerResponse.getToken() != null && providerResponse.getTokenId() != null);

    String token = (String)providerResponse.getToken();
    assertNotNull(token);

    JwsJwtCompactConsumer jwtConsumer = new JwsJwtCompactConsumer(token);
    JwtToken jwt = jwtConsumer.getJwtToken();
    assertEquals(jwt.getClaim(CLAIM_STATIC_COMPANY.toString()), CLAIM_STATIC_COMPANY_VALUE);
}
 
Example #21
Source File: OIDCFlowTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void testAuthorizationCodeFlowWithKey() 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 Authorization Code
    String code = OAuth2TestUtils.getAuthorizationCode(client, "openid");
    assertNotNull(code);

    // Now get the access token
    client = WebClient.create(address, "consumer-id", "this-is-a-secret", busFile.toString());

    ClientAccessToken accessToken =
        OAuth2TestUtils.getAccessTokenWithAuthorizationCode(client, code);
    assertNotNull(accessToken.getTokenKey());
    assertTrue(accessToken.getApprovedScope().contains("openid"));

    String idToken = accessToken.getParameters().get("id_token");
    assertNotNull(idToken);

    JwsJwtCompactConsumer jwtConsumer = new JwsJwtCompactConsumer(idToken);

    // Now get the key to validate the token
    client = WebClient.create(address, OAuth2TestUtils.setupProviders(),
                              "alice", "security", busFile.toString());
    client.accept("application/json");

    client.path("keys/");
    Response response = client.get();
    JsonWebKeys jsonWebKeys = response.readEntity(JsonWebKeys.class);

    assertTrue(jwtConsumer.verifySignatureWith(jsonWebKeys.getKeys().get(0),
                                                      SignatureAlgorithm.RS256));
}
 
Example #22
Source File: JWTProviderActAsTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
/**
 * Create a JWT Token with ActAs from a SAML Assertion
 */
@org.junit.Test
public void testJWTActAsAssertion() throws Exception {
    TokenProvider tokenProvider = new JWTTokenProvider();

    String user = "bob";
    Element saml1Assertion = getSAMLAssertion(user);

    TokenProviderParameters providerParameters =
        createProviderParameters(
            JWTTokenProvider.JWT_TOKEN_TYPE, saml1Assertion
        );
    //Principal must be set in ReceivedToken/ActAs
    providerParameters.getTokenRequirements().getActAs().setPrincipal(
            new CustomTokenPrincipal(user));

    assertTrue(tokenProvider.canHandleToken(JWTTokenProvider.JWT_TOKEN_TYPE));
    TokenProviderResponse providerResponse = tokenProvider.createToken(providerParameters);
    assertNotNull(providerResponse);
    assertTrue(providerResponse.getToken() != null && providerResponse.getTokenId() != null);

    String token = (String)providerResponse.getToken();
    assertNotNull(token);

    // Validate the token
    JwsJwtCompactConsumer jwtConsumer = new JwsJwtCompactConsumer(token);
    JwtToken jwt = jwtConsumer.getJwtToken();
    Assert.assertEquals("technical-user", jwt.getClaim(JwtConstants.CLAIM_SUBJECT));
    Assert.assertEquals("bob", jwt.getClaim("ActAs"));
}
 
Example #23
Source File: JWTProviderLifetimeTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
/**
 * Issue JWT token with a valid requested lifetime
 */
@org.junit.Test
public void testJWTValidLifetime() throws Exception {

    int requestedLifetime = 60;
    JWTTokenProvider tokenProvider = new JWTTokenProvider();
    DefaultJWTClaimsProvider claimsProvider = new DefaultJWTClaimsProvider();
    claimsProvider.setAcceptClientLifetime(true);
    tokenProvider.setJwtClaimsProvider(claimsProvider);

    TokenProviderParameters providerParameters =
        createProviderParameters(JWTTokenProvider.JWT_TOKEN_TYPE);

    // Set expected lifetime to 1 minute
    Instant creationTime = Instant.now();
    Instant expirationTime = creationTime.plusSeconds(requestedLifetime);

    Lifetime lifetime = new Lifetime();
    lifetime.setCreated(creationTime.atZone(ZoneOffset.UTC).format(DateUtil.getDateTimeFormatter(true)));
    lifetime.setExpires(expirationTime.atZone(ZoneOffset.UTC).format(DateUtil.getDateTimeFormatter(true)));

    providerParameters.getTokenRequirements().setLifetime(lifetime);

    TokenProviderResponse providerResponse = tokenProvider.createToken(providerParameters);
    assertNotNull(providerResponse);
    assertTrue(providerResponse.getToken() != null && providerResponse.getTokenId() != null);

    long duration = Duration.between(providerResponse.getCreated(), providerResponse.getExpires()).getSeconds();
    assertEquals(requestedLifetime, duration);

    String token = (String)providerResponse.getToken();
    assertNotNull(token);

    JwsJwtCompactConsumer jwtConsumer = new JwsJwtCompactConsumer(token);
    JwtToken jwt = jwtConsumer.getJwtToken();
    assertEquals(jwt.getClaim(JwtConstants.CLAIM_ISSUED_AT), providerResponse.getCreated().getEpochSecond());
}
 
Example #24
Source File: JWTProviderLifetimeTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
/**
 * Issue JWT token with a lifetime configured in JWTTokenProvider
 * No specific lifetime requested
 */
@org.junit.Test
public void testJWTProviderLifetime() throws Exception {

    long providerLifetime = 10 * 600L;
    JWTTokenProvider tokenProvider = new JWTTokenProvider();
    DefaultJWTClaimsProvider claimsProvider = new DefaultJWTClaimsProvider();
    claimsProvider.setLifetime(providerLifetime);
    tokenProvider.setJwtClaimsProvider(claimsProvider);

    TokenProviderParameters providerParameters = createProviderParameters(JWTTokenProvider.JWT_TOKEN_TYPE);

    TokenProviderResponse providerResponse = tokenProvider.createToken(providerParameters);
    assertNotNull(providerResponse);
    assertTrue(providerResponse.getToken() != null && providerResponse.getTokenId() != null);

    long duration = Duration.between(providerResponse.getCreated(), providerResponse.getExpires()).getSeconds();
    assertEquals(providerLifetime, duration);

    String token = (String)providerResponse.getToken();
    assertNotNull(token);

    JwsJwtCompactConsumer jwtConsumer = new JwsJwtCompactConsumer(token);
    JwtToken jwt = jwtConsumer.getJwtToken();
    assertEquals(jwt.getClaim(JwtConstants.CLAIM_ISSUED_AT), providerResponse.getCreated().getEpochSecond());

    Instant now = Instant.now();
    Long expiry = (Long)jwt.getClaim(JwtConstants.CLAIM_EXPIRY);
    Instant.ofEpochSecond(expiry).isAfter(now);
}
 
Example #25
Source File: JWTProviderOnBehalfOfTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
/**
 * Create a JWT Token with OnBehalfOf from a UsernameToken
 */
@org.junit.Test
public void testJWTOnBehalfOfUsernameToken() throws Exception {
    TokenProvider tokenProvider = new JWTTokenProvider();

    UsernameTokenType usernameToken = new UsernameTokenType();
    AttributedString username = new AttributedString();
    username.setValue("bob");
    usernameToken.setUsername(username);
    JAXBElement<UsernameTokenType> usernameTokenType =
        new JAXBElement<UsernameTokenType>(
            QNameConstants.USERNAME_TOKEN, UsernameTokenType.class, usernameToken
        );

    TokenProviderParameters providerParameters =
        createProviderParameters(
            JWTTokenProvider.JWT_TOKEN_TYPE, usernameTokenType
        );
    //Principal must be set in ReceivedToken/OnBehalfOf
    providerParameters.getTokenRequirements().getOnBehalfOf().setPrincipal(
            new CustomTokenPrincipal(username.getValue()));

    assertTrue(tokenProvider.canHandleToken(JWTTokenProvider.JWT_TOKEN_TYPE));
    TokenProviderResponse providerResponse = tokenProvider.createToken(providerParameters);
    assertNotNull(providerResponse);
    assertTrue(providerResponse.getToken() != null && providerResponse.getTokenId() != null);

    String token = (String)providerResponse.getToken();
    assertNotNull(token);

    // Validate the token
    JwsJwtCompactConsumer jwtConsumer = new JwsJwtCompactConsumer(token);
    JwtToken jwt = jwtConsumer.getJwtToken();
    Assert.assertEquals("bob", jwt.getClaim(JwtConstants.CLAIM_SUBJECT));
}
 
Example #26
Source File: AccessTokenDataBinderImpl.java    From syncope with Apache License 2.0 5 votes vote down vote up
@Override
public Pair<String, Date> update(final AccessToken accessToken, final byte[] authorities) {
    JwsJwtCompactConsumer consumer = new JwsJwtCompactConsumer(accessToken.getBody());

    credentialChecker.checkIsDefaultJWSKeyInUse();

    long duration = confParamOps.get(AuthContextUtils.getDomain(), "jwt.lifetime.minutes", 120L, Long.class);
    long currentTime = new Date().getTime() / 1000L;
    long expiry = currentTime + 60L * duration;
    consumer.getJwtClaims().setExpiryTime(expiry);
    Date expiryDate = new Date(expiry * 1000L);

    JwsHeaders jwsHeaders = new JwsHeaders(JoseType.JWT, jwsSignatureProvider.getAlgorithm());
    JwtToken token = new JwtToken(jwsHeaders, consumer.getJwtClaims());
    JwsJwtCompactProducer producer = new JwsJwtCompactProducer(token);

    String body = producer.signWith(jwsSignatureProvider);

    accessToken.setBody(body);
    // AccessToken stores expiry time in milliseconds, as opposed to seconds for the JWT tokens.
    accessToken.setExpiryTime(expiryDate);

    if (!adminUser.equals(accessToken.getOwner())) {
        accessToken.setAuthorities(authorities);
    }

    accessTokenDAO.save(accessToken);

    return Pair.of(body, expiryDate);
}
 
Example #27
Source File: AccessTokenDirectoryPanel.java    From syncope with Apache License 2.0 5 votes vote down vote up
@Override
protected List<IColumn<AccessTokenTO, String>> getColumns() {
    List<IColumn<AccessTokenTO, String>> columns = new ArrayList<>();
    columns.add(new KeyPropertyColumn<>(
            new StringResourceModel(Constants.KEY_FIELD_NAME, this),
            Constants.KEY_FIELD_NAME,
            Constants.KEY_FIELD_NAME));

    columns.add(new PropertyColumn<>(new ResourceModel("owner"), "owner", "owner"));

    columns.add(new AbstractColumn<AccessTokenTO, String>(new ResourceModel("issuedAt", "")) {

        private static final long serialVersionUID = -1822504503325964706L;

        @Override
        public void populateItem(
                final Item<ICellPopulator<AccessTokenTO>> cellItem,
                final String componentId,
                final IModel<AccessTokenTO> model) {

            JwsJwtCompactConsumer consumer = new JwsJwtCompactConsumer(model.getObject().getBody());
            cellItem.add(new Label(componentId,
                    SyncopeConsoleSession.get().getDateFormat().format(
                            new Date(consumer.getJwtClaims().getIssuedAt() * 1000))));
        }
    });

    columns.add(new DatePropertyColumn<>(new ResourceModel("expiryTime"), "expiryTime", "expiryTime"));

    return columns;
}
 
Example #28
Source File: JWTProviderOnBehalfOfTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
/**
 * Create a JWT Token with OnBehalfOf from a SAML Assertion
 */
@org.junit.Test
public void testJWTOnBehalfOfAssertion() throws Exception {
    TokenProvider tokenProvider = new JWTTokenProvider();

    String user = "alice";
    Element saml1Assertion = getSAMLAssertion(user);

    TokenProviderParameters providerParameters =
        createProviderParameters(
            JWTTokenProvider.JWT_TOKEN_TYPE, saml1Assertion
        );
    //Principal must be set in ReceivedToken/OnBehalfOf
    providerParameters.getTokenRequirements().getOnBehalfOf().setPrincipal(
            new CustomTokenPrincipal(user));

    assertTrue(tokenProvider.canHandleToken(JWTTokenProvider.JWT_TOKEN_TYPE));
    TokenProviderResponse providerResponse = tokenProvider.createToken(providerParameters);
    assertNotNull(providerResponse);
    assertTrue(providerResponse.getToken() != null && providerResponse.getTokenId() != null);

    String token = (String)providerResponse.getToken();
    assertNotNull(token);

    // Validate the token
    JwsJwtCompactConsumer jwtConsumer = new JwsJwtCompactConsumer(token);
    JwtToken jwt = jwtConsumer.getJwtToken();
    Assert.assertEquals(user, jwt.getClaim(JwtConstants.CLAIM_SUBJECT));
}
 
Example #29
Source File: SAML2ITCase.java    From syncope with Apache License 2.0 5 votes vote down vote up
@Test
public void unsignedAssertionInLoginResponse() throws Exception {
    assumeTrue(SAML2SPDetector.isSAML2SPAvailable());

    // Get a valid login request for the Fediz realm
    SAML2SPService saml2Service = anonymous.getService(SAML2SPService.class);
    SAML2RequestTO loginRequest = saml2Service.createLoginRequest(ADDRESS, "urn:org:apache:cxf:fediz:idp:realm-A");
    assertNotNull(loginRequest);

    SAML2ReceivedResponseTO response = new SAML2ReceivedResponseTO();
    response.setSpEntityID("http://recipient.apache.org/");
    response.setUrlContext("saml2sp");
    response.setRelayState(loginRequest.getRelayState());

    // Create a SAML Response using WSS4J
    JwsJwtCompactConsumer relayState = new JwsJwtCompactConsumer(response.getRelayState());
    String inResponseTo = relayState.getJwtClaims().getSubject();

    org.opensaml.saml.saml2.core.Response samlResponse =
            createResponse(inResponseTo, false, SAML2Constants.CONF_SENDER_VOUCHES,
                    "urn:org:apache:cxf:fediz:idp:realm-A");

    Document doc = DOMUtils.newDocument();
    Element responseElement = OpenSAMLUtil.toDom(samlResponse, doc);
    String responseStr = DOM2Writer.nodeToString(responseElement);

    // Validate the SAML Response
    response.setSamlResponse(Base64.getEncoder().encodeToString(responseStr.getBytes()));
    try {
        saml2Service.validateLoginResponse(response);
        fail("Failure expected on an unsigned Assertion");
    } catch (SyncopeClientException e) {
        assertNotNull(e);
    }
}
 
Example #30
Source File: JWTITCase.java    From syncope with Apache License 2.0 5 votes vote down vote up
@Test
public void issueSYNCOPE1420() {
    Long orig = confParamOps.get(SyncopeConstants.MASTER_DOMAIN, "jwt.lifetime.minutes", null, Long.class);
    try {
        // set for immediate JWT expiration
        confParamOps.set(SyncopeConstants.MASTER_DOMAIN, "jwt.lifetime.minutes", 0);

        UserCR userCR = UserITCase.getUniqueSample("[email protected]");
        UserTO user = createUser(userCR).getEntity();
        assertNotNull(user);

        // login, get JWT with  expiryTime
        String jwt = clientFactory.create(user.getUsername(), "password123").getJWT();

        JwsJwtCompactConsumer consumer = new JwsJwtCompactConsumer(jwt);
        assertTrue(consumer.verifySignatureWith(jwsSignatureVerifier));
        Long expiryTime = consumer.getJwtClaims().getExpiryTime();
        assertNotNull(expiryTime);

        // wait for 1 sec, check that JWT is effectively expired
        try {
            Thread.sleep(1000L);
        } catch (InterruptedException e) {
            // ignore
        }
        assertTrue(expiryTime < System.currentTimeMillis());

        // login again, get new JWT
        // (even if ExpiredAccessTokenCleanup did not run yet, as it is scheduled every 5 minutes)
        String newJWT = clientFactory.create(user.getUsername(), "password123").getJWT();
        assertNotEquals(jwt, newJWT);
    } finally {
        confParamOps.set(SyncopeConstants.MASTER_DOMAIN, "jwt.lifetime.minutes", orig);
    }
}