org.apache.cxf.rs.security.jose.jwt.JwtConstants Java Examples

The following examples show how to use org.apache.cxf.rs.security.jose.jwt.JwtConstants. 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: TrustedIdpOIDCProtocolHandler.java    From cxf-fediz with Apache License 2.0 6 votes vote down vote up
protected void validateToken(JwtToken jwt, String clientId) {
    // We must have the following claims
    if (jwt.getClaim(JwtConstants.CLAIM_ISSUER) == null
        || jwt.getClaim(JwtConstants.CLAIM_SUBJECT) == null
        || jwt.getClaim(JwtConstants.CLAIM_AUDIENCE) == null
        || jwt.getClaim(JwtConstants.CLAIM_EXPIRY) == null
        || jwt.getClaim(JwtConstants.CLAIM_ISSUED_AT) == null) {
        LOG.warn("The IdToken is missing a required claim");
        throw new IllegalStateException("The IdToken is missing a required claim");
    }

    // The audience must match the client_id of this client
    boolean match = false;
    for (String audience : jwt.getClaims().getAudiences()) {
        if (clientId.equals(audience)) {
            match = true;
            break;
        }
    }
    if (!match) {
        LOG.warn("The audience of the token does not match this client");
        throw new IllegalStateException("The audience of the token does not match this client");
    }

    JwtUtils.validateTokenClaims(jwt.getClaims(), 300, 0, false);
}
 
Example #2
Source File: JwtBearerAuthHandler.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Override
protected void validateToken(JwtToken jwt) {
    super.validateToken(jwt);

    // We must have an issuer
    if (jwt.getClaim(JwtConstants.CLAIM_ISSUER) == null) {
        throw new OAuthServiceException(OAuthConstants.INVALID_GRANT);
    }

    // We must have a Subject
    if (jwt.getClaim(JwtConstants.CLAIM_SUBJECT) == null) {
        throw new OAuthServiceException(OAuthConstants.INVALID_GRANT);
    }

    // We must have an Expiry
    if (jwt.getClaim(JwtConstants.CLAIM_EXPIRY) == null) {
        throw new OAuthServiceException(OAuthConstants.INVALID_GRANT);
    }

    JwtUtils.validateTokenClaims(jwt.getClaims(), getTtl(), getClockOffset(), isValidateAudience());
}
 
Example #3
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 #4
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 #5
Source File: JWTAlgorithmTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@org.junit.Test
public void testBadSignatureCertificateTest() throws Exception {

    URL busFile = JWTAlgorithmTest.class.getResource("client.xml");

    List<Object> providers = new ArrayList<>();
    providers.add(new JacksonJsonProvider());
    providers.add(new JwtAuthenticationClientFilter());

    String address = "https://localhost:" + PORT + "/signedjwtincludecert/bookstore/books";
    WebClient client =
        WebClient.create(address, providers, busFile.toString());
    client.type("application/json").accept("application/json");

    // Create the JWT Token
    JwtClaims claims = new JwtClaims();
    claims.setSubject("alice");
    claims.setIssuer("DoubleItSTSIssuer");
    claims.setIssuedAt(Instant.now().getEpochSecond());
    claims.setAudiences(toList(address));

    JwtToken token = new JwtToken(claims);

    Map<String, Object> properties = new HashMap<>();
    properties.put("rs.security.keystore.type", "jks");
    properties.put("rs.security.keystore.password", "password");
    properties.put("rs.security.key.password", "password");
    properties.put("rs.security.keystore.alias", "bethal");
    properties.put("rs.security.keystore.file", "keys/Bethal.jks");
    properties.put("rs.security.signature.algorithm", "RS256");
    properties.put("rs.security.signature.include.cert", "true");
    properties.put(JwtConstants.JWT_TOKEN, token);
    WebClient.getConfig(client).getRequestContext().putAll(properties);

    Response response = client.post(new Book("book", 123L));
    assertNotEquals(response.getStatus(), 200);
}
 
Example #6
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 #7
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 #8
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 #9
Source File: JWTPropertiesTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void testMultipleAudiences() throws Exception {

    URL busFile = JWTPropertiesTest.class.getResource("client.xml");

    List<Object> providers = new ArrayList<>();
    providers.add(new JacksonJsonProvider());
    providers.add(new JwtAuthenticationClientFilter());

    String address = "https://localhost:" + PORT + "/unsignedjwt/bookstore/books";
    WebClient client =
        WebClient.create(address, providers, busFile.toString());
    client.type("application/json").accept("application/json");

    // Create the JWT Token
    JwtClaims claims = new JwtClaims();
    claims.setSubject("alice");
    claims.setIssuer("DoubleItSTSIssuer");
    ZonedDateTime now = ZonedDateTime.now(ZoneOffset.UTC);
    claims.setIssuedAt(now.toEpochSecond());

    String badAddress = "https://localhost:" + PORT + "/badunsignedjwt/bookstore/books";
    List<String> audiences = new ArrayList<>();
    audiences.add(address);
    audiences.add(badAddress);
    claims.setAudiences(audiences);

    Map<String, Object> properties = new HashMap<>();
    properties.put("rs.security.signature.algorithm", "none");
    properties.put(JwtConstants.JWT_CLAIMS, claims);
    WebClient.getConfig(client).getRequestContext().putAll(properties);

    Response response = client.post(new Book("book", 123L));
    assertEquals(response.getStatus(), 200);
}
 
Example #10
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 #11
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 #12
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 #13
Source File: JWTProviderLifetimeTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
/**
 * Issue JWT token with a near future Created Lifetime. This should pass as we allow a future
 * dated Lifetime up to 60 seconds to avoid clock skew problems.
 */
@org.junit.Test
public void testJWTNearFutureCreatedLifetime() 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);
    creationTime = creationTime.plusSeconds(10);

    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(50, 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 #14
Source File: AbstractOAuthDataProviderTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
private void validateAccessToken(ServerAccessToken accessToken) {
    if (getProvider().isUseJwtFormatForAccessTokens()) {
        JwsJwtCompactConsumer jwtConsumer = new JwsJwtCompactConsumer(accessToken.getTokenKey());
        JwtToken jwt = jwtConsumer.getJwtToken();

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

        assertTrue(jwtConsumer.verifySignatureWith(keyPair.getPublic(), SignatureAlgorithm.RS256));
    }
}
 
Example #15
Source File: AbstractJwtHandler.java    From cxf with Apache License 2.0 5 votes vote down vote up
protected void validateClaims(Client client, JwtClaims claims) {
    if (getAudience() != null) {
        JAXRSUtils.getCurrentMessage().put(JwtConstants.EXPECTED_CLAIM_AUDIENCE, getAudience());
    }
    JwtUtils.validateTokenClaims(claims, ttl, clockOffset, true);

    validateIssuer(claims.getIssuer());
    validateSubject(client, claims.getSubject());

    // We must have an Expiry
    if (claims.getClaim(JwtConstants.CLAIM_EXPIRY) == null) {
        throw new OAuthServiceException(OAuthConstants.INVALID_GRANT);
    }
}
 
Example #16
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 #17
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 #18
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 #19
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 #20
Source File: JWTPropertiesTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void testNoAudience() throws Exception {

    URL busFile = JWTPropertiesTest.class.getResource("client.xml");

    List<Object> providers = new ArrayList<>();
    providers.add(new JacksonJsonProvider());
    providers.add(new JwtAuthenticationClientFilter());

    String address = "https://localhost:" + PORT + "/unsignedjwt/bookstore/books";
    WebClient client =
        WebClient.create(address, providers, busFile.toString());
    client.type("application/json").accept("application/json");

    // Create the JWT Token
    JwtClaims claims = new JwtClaims();
    claims.setSubject("alice");
    claims.setIssuer("DoubleItSTSIssuer");
    ZonedDateTime now = ZonedDateTime.now(ZoneOffset.UTC);
    claims.setIssuedAt(now.toEpochSecond());

    Map<String, Object> properties = new HashMap<>();
    properties.put("rs.security.signature.algorithm", "none");
    properties.put(JwtConstants.JWT_CLAIMS, claims);
    WebClient.getConfig(client).getRequestContext().putAll(properties);

    Response response = client.post(new Book("book", 123L));
    assertEquals(response.getStatus(), 200);
}
 
Example #21
Source File: JWTPropertiesTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void testBadAudience() throws Exception {

    URL busFile = JWTPropertiesTest.class.getResource("client.xml");

    List<Object> providers = new ArrayList<>();
    providers.add(new JacksonJsonProvider());
    providers.add(new JwtAuthenticationClientFilter());

    String address = "https://localhost:" + PORT + "/unsignedjwt/bookstore/books";
    WebClient client =
        WebClient.create(address, providers, busFile.toString());
    client.type("application/json").accept("application/json");

    // Create the JWT Token
    JwtClaims claims = new JwtClaims();
    claims.setSubject("alice");
    claims.setIssuer("DoubleItSTSIssuer");
    ZonedDateTime now = ZonedDateTime.now(ZoneOffset.UTC);
    claims.setIssuedAt(now.toEpochSecond());
    String badAddress = "https://localhost:" + PORT + "/badunsignedjwt/bookstore/books";
    claims.setAudiences(toList(badAddress));

    Map<String, Object> properties = new HashMap<>();
    properties.put("rs.security.signature.algorithm", "none");
    properties.put(JwtConstants.JWT_CLAIMS, claims);
    WebClient.getConfig(client).getRequestContext().putAll(properties);

    Response response = client.post(new Book("book", 123L));
    assertNotEquals(response.getStatus(), 200);
}
 
Example #22
Source File: JWTPropertiesTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void testSetClaimsDirectly() throws Exception {

    URL busFile = JWTPropertiesTest.class.getResource("client.xml");

    List<Object> providers = new ArrayList<>();
    providers.add(new JacksonJsonProvider());
    providers.add(new JwtAuthenticationClientFilter());

    String address = "https://localhost:" + PORT + "/unsignedjwt/bookstore/books";
    WebClient client =
        WebClient.create(address, providers, busFile.toString());
    client.type("application/json").accept("application/json");

    // Create the JWT Token
    JwtClaims claims = new JwtClaims();
    claims.setSubject("alice");
    claims.setIssuer("DoubleItSTSIssuer");
    ZonedDateTime now = ZonedDateTime.now(ZoneOffset.UTC);
    claims.setIssuedAt(now.toEpochSecond());
    claims.setAudiences(toList(address));

    Map<String, Object> properties = new HashMap<>();
    properties.put("rs.security.signature.algorithm", "none");
    properties.put(JwtConstants.JWT_CLAIMS, claims);
    WebClient.getConfig(client).getRequestContext().putAll(properties);

    Response response = client.post(new Book("book", 123L));
    assertEquals(response.getStatus(), 200);
}
 
Example #23
Source File: JWTPropertiesTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void testNotBeforeFailure() throws Exception {

    URL busFile = JWTPropertiesTest.class.getResource("client.xml");

    List<Object> providers = new ArrayList<>();
    providers.add(new JacksonJsonProvider());
    providers.add(new JwtAuthenticationClientFilter());

    String address = "https://localhost:" + PORT + "/unsignedjwt/bookstore/books";
    WebClient client =
        WebClient.create(address, providers, busFile.toString());
    client.type("application/json").accept("application/json");

    // Create the JWT Token
    JwtClaims claims = new JwtClaims();
    claims.setSubject("alice");
    claims.setIssuer("DoubleItSTSIssuer");
    claims.setAudiences(toList(address));

    // Set the issued date to be in the near future
    ZonedDateTime now = ZonedDateTime.now(ZoneOffset.UTC);
    claims.setIssuedAt(now.toEpochSecond());
    claims.setNotBefore(now.plusSeconds(30L).toEpochSecond());

    JwtToken token = new JwtToken(claims);

    Map<String, Object> properties = new HashMap<>();
    properties.put("rs.security.signature.algorithm", "none");
    properties.put(JwtConstants.JWT_TOKEN, token);
    WebClient.getConfig(client).getRequestContext().putAll(properties);

    Response response = client.post(new Book("book", 123L));
    assertNotEquals(response.getStatus(), 200);
}
 
Example #24
Source File: JWTPropertiesTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void testNearFutureTokenSuccess() throws Exception {

    URL busFile = JWTPropertiesTest.class.getResource("client.xml");

    List<Object> providers = new ArrayList<>();
    providers.add(new JacksonJsonProvider());
    providers.add(new JwtAuthenticationClientFilter());

    String address = "https://localhost:" + PORT + "/unsignedjwtnearfuture/bookstore/books";
    WebClient client =
        WebClient.create(address, providers, busFile.toString());
    client.type("application/json").accept("application/json");

    // Create the JWT Token
    JwtClaims claims = new JwtClaims();
    claims.setSubject("alice");
    claims.setIssuer("DoubleItSTSIssuer");
    claims.setAudiences(toList(address));

    // Set the issued date to be in the near future
    ZonedDateTime now = ZonedDateTime.now(ZoneOffset.UTC);
    claims.setIssuedAt(now.plusSeconds(30L).toEpochSecond());

    JwtToken token = new JwtToken(claims);

    Map<String, Object> properties = new HashMap<>();
    properties.put("rs.security.signature.algorithm", "none");
    properties.put(JwtConstants.JWT_TOKEN, token);
    WebClient.getConfig(client).getRequestContext().putAll(properties);

    Response response = client.post(new Book("book", 123L));
    assertEquals(response.getStatus(), 200);
}
 
Example #25
Source File: JWTPropertiesTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void testNearFutureTokenFailure() throws Exception {

    URL busFile = JWTPropertiesTest.class.getResource("client.xml");

    List<Object> providers = new ArrayList<>();
    providers.add(new JacksonJsonProvider());
    providers.add(new JwtAuthenticationClientFilter());

    String address = "https://localhost:" + PORT + "/unsignedjwt/bookstore/books";
    WebClient client =
        WebClient.create(address, providers, busFile.toString());
    client.type("application/json").accept("application/json");

    // Create the JWT Token
    JwtClaims claims = new JwtClaims();
    claims.setSubject("alice");
    claims.setIssuer("DoubleItSTSIssuer");
    claims.setAudiences(toList(address));

    // Set the issued date to be in the near future
    ZonedDateTime now = ZonedDateTime.now(ZoneOffset.UTC);
    claims.setIssuedAt(now.plusSeconds(30L).toEpochSecond());

    JwtToken token = new JwtToken(claims);

    Map<String, Object> properties = new HashMap<>();
    properties.put("rs.security.signature.algorithm", "none");
    properties.put(JwtConstants.JWT_TOKEN, token);
    WebClient.getConfig(client).getRequestContext().putAll(properties);

    Response response = client.post(new Book("book", 123L));
    assertNotEquals(response.getStatus(), 200);
}
 
Example #26
Source File: JWTPropertiesTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void testFutureToken() throws Exception {

    URL busFile = JWTPropertiesTest.class.getResource("client.xml");

    List<Object> providers = new ArrayList<>();
    providers.add(new JacksonJsonProvider());
    providers.add(new JwtAuthenticationClientFilter());

    String address = "https://localhost:" + PORT + "/unsignedjwt/bookstore/books";
    WebClient client =
        WebClient.create(address, providers, busFile.toString());
    client.type("application/json").accept("application/json");

    // Create the JWT Token
    JwtClaims claims = new JwtClaims();
    claims.setSubject("alice");
    claims.setIssuer("DoubleItSTSIssuer");
    claims.setAudiences(toList(address));

    // Set the issued date to be in the future
    ZonedDateTime now = ZonedDateTime.now(ZoneOffset.UTC);
    claims.setIssuedAt(now.plusDays(1L).toEpochSecond());

    JwtToken token = new JwtToken(claims);

    Map<String, Object> properties = new HashMap<>();
    properties.put("rs.security.signature.algorithm", "none");
    properties.put(JwtConstants.JWT_TOKEN, token);
    WebClient.getConfig(client).getRequestContext().putAll(properties);

    Response response = client.post(new Book("book", 123L));
    assertNotEquals(response.getStatus(), 200);
}
 
Example #27
Source File: JWTPropertiesTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void testExpiredToken() throws Exception {

    URL busFile = JWTPropertiesTest.class.getResource("client.xml");

    List<Object> providers = new ArrayList<>();
    providers.add(new JacksonJsonProvider());
    providers.add(new JwtAuthenticationClientFilter());

    String address = "https://localhost:" + PORT + "/unsignedjwt/bookstore/books";
    WebClient client =
        WebClient.create(address, providers, busFile.toString());
    client.type("application/json").accept("application/json");

    // Create the JWT Token
    JwtClaims claims = new JwtClaims();
    claims.setSubject("alice");
    claims.setIssuer("DoubleItSTSIssuer");
    ZonedDateTime now = ZonedDateTime.now(ZoneOffset.UTC);
    claims.setIssuedAt(now.toEpochSecond());
    claims.setAudiences(toList(address));

    // Set the expiry date to be yesterday
    claims.setExpiryTime(now.minusDays(1L).toEpochSecond());

    JwtToken token = new JwtToken(claims);

    Map<String, Object> properties = new HashMap<>();
    properties.put("rs.security.signature.algorithm", "none");
    properties.put(JwtConstants.JWT_TOKEN, token);
    WebClient.getConfig(client).getRequestContext().putAll(properties);

    Response response = client.post(new Book("book", 123L));
    assertNotEquals(response.getStatus(), 200);
}
 
Example #28
Source File: JWTAuthnAuthzTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void testClaimsAuthorizationNoClaims() throws Exception {

    URL busFile = JWTAuthnAuthzTest.class.getResource("client.xml");

    List<Object> providers = new ArrayList<>();
    providers.add(new JacksonJsonProvider());
    providers.add(new JwtAuthenticationClientFilter());

    String address = "https://localhost:" + PORT + "/signedjwtauthz/bookstore/booksclaims";
    WebClient client =
        WebClient.create(address, providers, busFile.toString());
    client.type("application/json").accept("application/json");

    // Create the JWT Token
    JwtClaims claims = new JwtClaims();
    claims.setSubject("alice");
    claims.setIssuer("DoubleItSTSIssuer");
    claims.setIssuedAt(Instant.now().getEpochSecond());
    claims.setAudiences(toList(address));
    // The endpoint requires a role of "boss"
    claims.setProperty("role", "boss");

    JwtToken token = new JwtToken(claims);

    Map<String, Object> properties = new HashMap<>();
    properties.put("rs.security.keystore.type", "jwk");
    properties.put("rs.security.keystore.alias", "2011-04-29");
    properties.put("rs.security.keystore.file",
                   "org/apache/cxf/systest/jaxrs/security/certs/jwkPrivateSet.txt");
    properties.put("rs.security.signature.algorithm", "RS256");
    properties.put(JwtConstants.JWT_TOKEN, token);
    WebClient.getConfig(client).getRequestContext().putAll(properties);

    Response response = client.post(new Book("book", 123L));
    assertEquals(response.getStatus(), 403);
}
 
Example #29
Source File: JWTPropertiesTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void testNotBeforeSuccess() throws Exception {

    URL busFile = JWTPropertiesTest.class.getResource("client.xml");

    List<Object> providers = new ArrayList<>();
    providers.add(new JacksonJsonProvider());
    providers.add(new JwtAuthenticationClientFilter());

    String address = "https://localhost:" + PORT + "/unsignedjwtnearfuture/bookstore/books";
    WebClient client =
        WebClient.create(address, providers, busFile.toString());
    client.type("application/json").accept("application/json");

    // Create the JWT Token
    JwtClaims claims = new JwtClaims();
    claims.setSubject("alice");
    claims.setIssuer("DoubleItSTSIssuer");
    claims.setAudiences(toList(address));

    // Set the issued date to be in the near future
    ZonedDateTime now = ZonedDateTime.now(ZoneOffset.UTC);
    claims.setIssuedAt(now.toEpochSecond());
    claims.setNotBefore(now.plusSeconds(30L).toEpochSecond());

    JwtToken token = new JwtToken(claims);

    Map<String, Object> properties = new HashMap<>();
    properties.put("rs.security.signature.algorithm", "none");
    properties.put(JwtConstants.JWT_TOKEN, token);
    WebClient.getConfig(client).getRequestContext().putAll(properties);

    Response response = client.post(new Book("book", 123L));
    assertEquals(response.getStatus(), 200);
}
 
Example #30
Source File: JWTAuthnAuthzTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void testClaimsAuthorizationWeakClaims() throws Exception {

    URL busFile = JWTAuthnAuthzTest.class.getResource("client.xml");

    List<Object> providers = new ArrayList<>();
    providers.add(new JacksonJsonProvider());
    providers.add(new JwtAuthenticationClientFilter());

    String address = "https://localhost:" + PORT + "/signedjwtauthz/bookstore/booksclaims";
    WebClient client =
        WebClient.create(address, providers, busFile.toString());
    client.type("application/json").accept("application/json");

    // Create the JWT Token
    JwtClaims claims = new JwtClaims();
    claims.setSubject("alice");
    claims.setIssuer("DoubleItSTSIssuer");
    claims.setIssuedAt(Instant.now().getEpochSecond());
    claims.setAudiences(toList(address));
    // The endpoint requires a role of "boss"
    claims.setProperty("role", "boss");
    claims.setProperty("http://claims/authentication", "password");

    JwtToken token = new JwtToken(claims);

    Map<String, Object> properties = new HashMap<>();
    properties.put("rs.security.keystore.type", "jwk");
    properties.put("rs.security.keystore.alias", "2011-04-29");
    properties.put("rs.security.keystore.file",
                   "org/apache/cxf/systest/jaxrs/security/certs/jwkPrivateSet.txt");
    properties.put("rs.security.signature.algorithm", "RS256");
    properties.put(JwtConstants.JWT_TOKEN, token);
    WebClient.getConfig(client).getRequestContext().putAll(properties);

    Response response = client.post(new Book("book", 123L));
    assertEquals(response.getStatus(), 403);
}