Java Code Examples for org.apache.cxf.rs.security.jose.jws.JwsJwtCompactConsumer#getJwtToken()

The following examples show how to use org.apache.cxf.rs.security.jose.jws.JwsJwtCompactConsumer#getJwtToken() . 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: 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 2
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 3
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 4
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 5
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 6
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 7
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 8
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 9
Source File: OIDCNegativeTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
@org.junit.Test
@org.junit.Ignore
public void testImplicitFlowMaxAge() 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", "1234565635");
    client.query("max_age", "300");
    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 IdToken
    String idToken = OAuth2TestUtils.getSubstring(location, "id_token");
    assertNotNull(idToken);

    JwsJwtCompactConsumer jwtConsumer = new JwsJwtCompactConsumer(idToken);
    JwtToken jwt = jwtConsumer.getJwtToken();
    assertNotNull(jwt.getClaims().getClaim(IdToken.AUTH_TIME_CLAIM));
}
 
Example 10
Source File: OIDCNegativeTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
@org.junit.Test
public void testImplicitFlowNoNonce() 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.path("authorize-implicit/");
    Response response = client.get();

    try {
        response.readEntity(OAuthAuthorizationData.class);
        fail("Failure expected on no nonce");
    } catch (Exception ex) {
        // expected
    }

    // Add a nonce and it should succeed
    String nonce = "1234565635";
    client.query("nonce", nonce);
    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 IdToken
    String idToken = OAuth2TestUtils.getSubstring(location, "id_token");
    assertNotNull(idToken);

    JwsJwtCompactConsumer jwtConsumer = new JwsJwtCompactConsumer(idToken);
    JwtToken jwt = jwtConsumer.getJwtToken();
    // Check the nonce is in the idToken
    assertEquals(jwt.getClaim("nonce"), nonce);
}
 
Example 11
Source File: OIDCNegativeTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
@org.junit.Test
public void testImplicitFlowNoATHash() 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", "1234565635");
    client.query("max_age", "300");
    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 IdToken
    String idToken = OAuth2TestUtils.getSubstring(location, "id_token");
    assertNotNull(idToken);

    JwsJwtCompactConsumer jwtConsumer = new JwsJwtCompactConsumer(idToken);
    JwtToken jwt = jwtConsumer.getJwtToken();
    Assert.assertNull(jwt.getClaims().getClaim(IdToken.ACCESS_TOKEN_HASH_CLAIM));
}
 
Example 12
Source File: JWTTokenProviderTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
@org.junit.Test
public void testCreateSignedPSJWT() throws Exception {
    try {
        Security.addProvider(new BouncyCastleProvider());

        TokenProvider jwtTokenProvider = new JWTTokenProvider();
        ((JWTTokenProvider)jwtTokenProvider).setSignToken(true);

        TokenProviderParameters providerParameters = createProviderParameters();
        SignatureProperties sigProps = new SignatureProperties();
        sigProps.setSignatureAlgorithm(SignatureAlgorithm.PS256.name());
        providerParameters.getStsProperties().setSignatureProperties(sigProps);

        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);

        assertFalse(jwtConsumer.verifySignatureWith(certs[0], SignatureAlgorithm.RS256));
        assertTrue(jwtConsumer.verifySignatureWith(certs[0], SignatureAlgorithm.PS256));
    } finally {
        Security.removeProvider(BouncyCastleProvider.PROVIDER_NAME);
    }
}
 
Example 13
Source File: UserInfoTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
@org.junit.Test
public void testSignedUserInfo() throws Exception {
    URL busFile = UserInfoTest.class.getResource("client.xml");

    String address = "https://localhost:" + port + "/services/oidc";
    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, OAuth2TestUtils.setupProviders(),
                              "consumer-id", "this-is-a-secret", busFile.toString());
    // Save the Cookie for the second request...
    WebClient.getConfig(client).getRequestContext().put(
        org.apache.cxf.message.Message.MAINTAIN_SESSION, Boolean.TRUE);

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

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

    // Now invoke on the UserInfo service with the access token
    String userInfoAddress = "https://localhost:" + port + "/services/signed/userinfo";
    WebClient userInfoClient = WebClient.create(userInfoAddress, OAuth2TestUtils.setupProviders(),
                                                busFile.toString());
    userInfoClient.accept("application/jwt");
    userInfoClient.header("Authorization", "Bearer " + accessToken.getTokenKey());

    Response serviceResponse = userInfoClient.get();
    assertEquals(serviceResponse.getStatus(), 200);

    String token = serviceResponse.readEntity(String.class);
    assertNotNull(token);

    JwsJwtCompactConsumer jwtConsumer = new JwsJwtCompactConsumer(token);
    JwtToken jwt = jwtConsumer.getJwtToken();

    assertEquals("alice", jwt.getClaim(JwtConstants.CLAIM_SUBJECT));
    assertEquals("consumer-id", jwt.getClaim(JwtConstants.CLAIM_AUDIENCE));

    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 14
Source File: JWTTokenValidator.java    From cxf with Apache License 2.0 4 votes vote down vote up
/**
 * Validate a Token using the given TokenValidatorParameters.
 */
public TokenValidatorResponse validateToken(TokenValidatorParameters tokenParameters) {
    LOG.fine("Validating JWT Token");
    STSPropertiesMBean stsProperties = tokenParameters.getStsProperties();

    TokenValidatorResponse response = new TokenValidatorResponse();
    ReceivedToken validateTarget = tokenParameters.getToken();
    validateTarget.setState(STATE.INVALID);
    response.setToken(validateTarget);

    String token = ((Element)validateTarget.getToken()).getTextContent();
    if (token == null || "".equals(token)) {
        return response;
    }

    if (token.split("\\.").length != 3) {
        LOG.log(Level.WARNING, "JWT Token appears not to be signed. Validation has failed");
        return response;
    }

    JwsJwtCompactConsumer jwtConsumer = new JwsJwtCompactConsumer(token);
    JwtToken jwt = jwtConsumer.getJwtToken();

    // Verify the signature
    Properties verificationProperties = new Properties();

    Crypto signatureCrypto = stsProperties.getSignatureCrypto();
    String alias = stsProperties.getSignatureUsername();

    if (alias != null) {
        verificationProperties.put(JoseConstants.RSSEC_KEY_STORE_ALIAS, alias);
    }

    if (!(signatureCrypto instanceof Merlin)) {
        throw new STSException("Can't get the keystore", STSException.REQUEST_FAILED);
    }
    KeyStore keystore = ((Merlin)signatureCrypto).getKeyStore();
    verificationProperties.put(JoseConstants.RSSEC_KEY_STORE, keystore);

    JwsSignatureVerifier signatureVerifier =
        JwsUtils.loadSignatureVerifier(verificationProperties, jwt.getJwsHeaders());

    if (!jwtConsumer.verifySignatureWith(signatureVerifier)) {
        return response;
    }

    try {
        validateToken(jwt);
    } catch (RuntimeException ex) {
        LOG.log(Level.WARNING, "JWT token validation failed", ex);
        return response;
    }


    // Get the realm of the JWT Token
    if (realmCodec != null) {
        String tokenRealm = realmCodec.getRealmFromToken(jwt);
        response.setTokenRealm(tokenRealm);
    }

    if (isVerifiedWithAPublicKey(jwt)) {
        Principal principal = new SimplePrincipal(jwt.getClaims().getSubject());
        response.setPrincipal(principal);

        // Parse roles from the validated token
        if (roleParser != null) {
            Set<Principal> roles =
                roleParser.parseRolesFromToken(principal, null, jwt);
            response.setRoles(roles);
        }
    }

    validateTarget.setState(STATE.VALID);
    LOG.fine("JWT Token successfully validated");

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

    TokenProviderParameters providerParameters = createProviderParameters();
    providerParameters.setEncryptToken(true);

    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 == 5);

    if (unrestrictedPoliciesInstalled) {
        // Validate the token
        JweJwtCompactConsumer jwtConsumer = new JweJwtCompactConsumer(token);
        Properties decProperties = new Properties();
        Crypto decryptionCrypto = CryptoFactory.getInstance(getDecryptionProperties());
        KeyStore keystore = ((Merlin)decryptionCrypto).getKeyStore();
        decProperties.put(JoseConstants.RSSEC_KEY_STORE, keystore);
        decProperties.put(JoseConstants.RSSEC_KEY_STORE_ALIAS, "myservicekey");
        decProperties.put(JoseConstants.RSSEC_KEY_PSWD, "skpass");

        JweDecryptionProvider decProvider =
            JweUtils.loadDecryptionProvider(decProperties, jwtConsumer.getHeaders());

        JweDecryptionOutput decOutput = decProvider.decrypt(token);
        String decToken = decOutput.getContentText();

        JwsJwtCompactConsumer jwtJwsConsumer = new JwsJwtCompactConsumer(decToken);
        JwtToken jwt = jwtJwsConsumer.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 16
Source File: JWTTokenProviderTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
@org.junit.Test
public void testCreateSignedEncryptedJWT() throws Exception {
    TokenProvider jwtTokenProvider = new JWTTokenProvider();

    TokenProviderParameters providerParameters = createProviderParameters();
    providerParameters.setEncryptToken(true);

    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 == 5);

    if (unrestrictedPoliciesInstalled) {
        // Validate the token
        JweJwtCompactConsumer jwtConsumer = new JweJwtCompactConsumer(token);
        Properties decProperties = new Properties();
        Crypto decryptionCrypto = CryptoFactory.getInstance(getDecryptionProperties());
        KeyStore keystore = ((Merlin)decryptionCrypto).getKeyStore();
        decProperties.put(JoseConstants.RSSEC_KEY_STORE, keystore);
        decProperties.put(JoseConstants.RSSEC_KEY_STORE_ALIAS, "myservicekey");
        decProperties.put(JoseConstants.RSSEC_KEY_PSWD, "skpass");

        JweDecryptionProvider decProvider =
            JweUtils.loadDecryptionProvider(decProperties, jwtConsumer.getHeaders());

        JweDecryptionOutput decOutput = decProvider.decrypt(token);
        String decToken = decOutput.getContentText();

        JwsJwtCompactConsumer jwtJwsConsumer = new JwsJwtCompactConsumer(decToken);
        JwtToken jwt = jwtJwsConsumer.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 17
Source File: OIDCFlowTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
@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();
    assertNull(jwt.getClaims().getClaim(IdToken.ACCESS_TOKEN_HASH_CLAIM));
    assertNotNull(jwt.getClaims().getClaim(IdToken.NONCE_CLAIM));
}
 
Example 18
Source File: JWTTokenProviderTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
@org.junit.Test
public void testCreateUnsignedEncryptedCBCJWT() throws Exception {
    try {
        Security.addProvider(new BouncyCastleProvider());

        TokenProvider jwtTokenProvider = new JWTTokenProvider();
        ((JWTTokenProvider)jwtTokenProvider).setSignToken(false);

        TokenProviderParameters providerParameters = createProviderParameters();
        providerParameters.setEncryptToken(true);
        providerParameters.getEncryptionProperties().setEncryptionAlgorithm(
            ContentAlgorithm.A128CBC_HS256.name()
        );

        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 == 5);

        if (unrestrictedPoliciesInstalled) {
            // Validate the token
            JweJwtCompactConsumer jwtConsumer = new JweJwtCompactConsumer(token);
            Properties decProperties = new Properties();
            Crypto decryptionCrypto = CryptoFactory.getInstance(getDecryptionProperties());
            KeyStore keystore = ((Merlin)decryptionCrypto).getKeyStore();
            decProperties.put(JoseConstants.RSSEC_KEY_STORE, keystore);
            decProperties.put(JoseConstants.RSSEC_KEY_STORE_ALIAS, "myservicekey");
            decProperties.put(JoseConstants.RSSEC_KEY_PSWD, "skpass");
            decProperties.put(JoseConstants.RSSEC_ENCRYPTION_CONTENT_ALGORITHM,
                              ContentAlgorithm.A128CBC_HS256.name());

            JweDecryptionProvider decProvider =
                JweUtils.loadDecryptionProvider(decProperties, jwtConsumer.getHeaders());

            JweDecryptionOutput decOutput = decProvider.decrypt(token);
            String decToken = decOutput.getContentText();

            JwsJwtCompactConsumer jwtJwsConsumer = new JwsJwtCompactConsumer(decToken);
            JwtToken jwt = jwtJwsConsumer.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));
        }
    } finally {
        Security.removeProvider(BouncyCastleProvider.PROVIDER_NAME);
    }
}
 
Example 19
Source File: OIDCFlowTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
@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();
    assertNotNull(jwt.getClaims().getClaim(IdToken.ACCESS_TOKEN_HASH_CLAIM));
    assertNotNull(jwt.getClaims().getClaim(IdToken.NONCE_CLAIM));
    OidcUtils.validateAccessTokenHash(accessToken, jwt, true);

    if (isAccessTokenInJWTFormat()) {
        validateAccessToken(accessToken);
    }
}
 
Example 20
Source File: JwtVerifier.java    From deprecated-security-advanced-modules with Apache License 2.0 4 votes vote down vote up
public JwtToken getVerifiedJwtToken(String encodedJwt) throws BadCredentialsException {
	try {
		JwsJwtCompactConsumer jwtConsumer = new JwsJwtCompactConsumer(encodedJwt);
		JwtToken jwt = jwtConsumer.getJwtToken();

		String escapedKid = jwt.getJwsHeaders().getKeyId();
		String kid = escapedKid;
		if (!Strings.isNullOrEmpty(kid) && !kid.isEmpty()) {
			kid = StringEscapeUtils.unescapeJava(escapedKid);
			if (escapedKid != kid) {
				log.info("Escaped Key ID from JWT Token");
			}
		}
		JsonWebKey key = keyProvider.getKey(kid);
		
		// Algorithm is not mandatory for the key material, so we set it to the same as the JWT
		if (key.getAlgorithm() == null && key.getPublicKeyUse() == PublicKeyUse.SIGN && key.getKeyType() == KeyType.RSA)
		{
			key.setAlgorithm(jwt.getJwsHeaders().getAlgorithm());
		}
		
		JwsSignatureVerifier signatureVerifier = getInitializedSignatureVerifier(key, jwt);


		boolean signatureValid = jwtConsumer.verifySignatureWith(signatureVerifier);

		if (!signatureValid && Strings.isNullOrEmpty(kid)) {
			key = keyProvider.getKeyAfterRefresh(null);
			signatureVerifier = getInitializedSignatureVerifier(key, jwt);
			signatureValid = jwtConsumer.verifySignatureWith(signatureVerifier);
		}

		if (!signatureValid) {
			throw new BadCredentialsException("Invalid JWT signature");
		}

		validateClaims(jwt);

		return jwt;
	} catch (JwtException e) {
		throw new BadCredentialsException(e.getMessage(), e);
	}
}