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

The following examples show how to use org.apache.cxf.rs.security.jose.jwt.JwtToken. 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: DefaultJWTRoleParser.java    From cxf with Apache License 2.0 6 votes vote down vote up
/**
 * Return the set of User/Principal roles from the token.
 * @param principal the Principal associated with the token
 * @param subject the JAAS Subject associated with a successful validation of the token
 * @param token The JWTToken
 * @return the set of User/Principal roles from the token.
 */
public Set<Principal> parseRolesFromToken(
    Principal principal, Subject subject, JwtToken token
) {
    if (subject != null && useJaasSubject) {
        return super.parseRolesFromSubject(principal, subject);
    }

    Set<Principal> roles = null;
    if (roleClaim != null && token != null && token.getClaims().containsProperty(roleClaim)) {
        roles = new HashSet<>();
        String role = token.getClaims().getStringProperty(roleClaim).trim();
        for (String r : role.split(",")) {
            roles.add(new SimpleGroup(r));
        }
    } else {
        roles = Collections.emptySet();
    }

    return roles;
}
 
Example #2
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 #3
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 #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: IdTokenResponseFilter.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Override
public String processJwt(JwtToken jwt, Client client) {
    if (keyServiceClient != null) {
        List<String> opers = new LinkedList<>();
        if (super.isJwsRequired()) {
            opers.add(JsonWebKey.KEY_OPER_SIGN);
        }
        if (super.isJweRequired()) {
            opers.add(JsonWebKey.KEY_OPER_ENCRYPT);
        }
        // the form request can be supported too
        keyServiceClient.resetQuery();
        keyServiceClient.query(JsonWebKey.KEY_OPERATIONS, opers);
        //TODO: OIDC core talks about various security algorithm preferences
        // that may be set during the client registrations, they can be passed along too
        return keyServiceClient.post(jwt, String.class);
    }
    return super.processJwt(jwt, client);
}
 
Example #6
Source File: JwsCompactReaderWriterTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testReadJwsWithJwkSignedByMac() throws Exception {
    JwsJwtCompactConsumer jws = new JwsJwtCompactConsumer(ENCODED_TOKEN_WITH_JSON_KEY_SIGNED_BY_MAC);
    assertTrue(jws.verifySignatureWith(new HmacJwsSignatureVerifier(ENCODED_MAC_KEY,
                                                                    SignatureAlgorithm.HS256)));
    JwtToken token = jws.getJwtToken();
    JwsHeaders headers = new JwsHeaders(token.getJwsHeaders());
    assertEquals(JoseType.JWT, headers.getType());
    assertEquals(SignatureAlgorithm.HS256, headers.getSignatureAlgorithm());

    JsonWebKey key = headers.getJsonWebKey();
    assertEquals(KeyType.OCTET, key.getKeyType());
    List<KeyOperation> keyOps = key.getKeyOperation();
    assertEquals(2, keyOps.size());
    assertEquals(KeyOperation.SIGN, keyOps.get(0));
    assertEquals(KeyOperation.VERIFY, keyOps.get(1));

    validateSpecClaim(token.getClaims());
}
 
Example #7
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 #8
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 #9
Source File: STSRESTTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@org.junit.Test
public void testIssueJWTTokenClaims() throws Exception {
    WebClient client = webClient()
        .path("jwt")
        .accept(MediaType.TEXT_PLAIN);

    // First check that the role isn't usually in the generated token

    String token = client.get(String.class);
    JwtToken jwt = validateJWTToken(token);

    assertNull(jwt.getClaim("roles"));

    // Now get another token specifying the role
    client.query("claim", "roles");

    token = client.get(String.class);
    jwt = validateJWTToken(token);

    assertEquals("ordinary-user", jwt.getClaim("roles"));
}
 
Example #10
Source File: JWTAlgorithmTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void testBadHMACSignature() 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 + "/hmacsignedjwt/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", "jwk");
    properties.put("rs.security.keystore.alias", "HMACKey");
    properties.put("rs.security.keystore.file",
                   "org/apache/cxf/systest/jaxrs/security/certs/jwkPrivateSet.txt");
    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 #11
Source File: JWTITCase.java    From syncope with Apache License 2.0 5 votes vote down vote up
@Test
public void noneSignature() throws ParseException {
    // Get an initial token
    SyncopeClient localClient = clientFactory.create(ADMIN_UNAME, ADMIN_PWD);
    AccessTokenService accessTokenService = localClient.getService(AccessTokenService.class);

    Response response = accessTokenService.login();
    String token = response.getHeaderString(RESTHeaders.TOKEN);
    assertNotNull(token);
    JwsJwtCompactConsumer consumer = new JwsJwtCompactConsumer(token);
    String tokenId = consumer.getJwtClaims().getTokenId();

    // Create a new token using the Id of the first token
    JwtClaims jwtClaims = new JwtClaims();
    jwtClaims.setTokenId(tokenId);
    jwtClaims.setSubject(consumer.getJwtClaims().getSubject());
    jwtClaims.setIssuedAt(consumer.getJwtClaims().getIssuedAt());
    jwtClaims.setIssuer(consumer.getJwtClaims().getIssuer());
    jwtClaims.setExpiryTime(consumer.getJwtClaims().getExpiryTime());
    jwtClaims.setNotBefore(consumer.getJwtClaims().getNotBefore());

    JwsHeaders jwsHeaders = new JwsHeaders(JoseType.JWT, SignatureAlgorithm.NONE);
    JwtToken jwtToken = new JwtToken(jwsHeaders, jwtClaims);
    JwsJwtCompactProducer producer = new JwsJwtCompactProducer(jwtToken);

    JwsSignatureProvider noneJwsSignatureProvider = new NoneJwsSignatureProvider();
    String signed = producer.signWith(noneJwsSignatureProvider);

    SyncopeClient jwtClient = clientFactory.create(signed);
    UserSelfService jwtUserSelfService = jwtClient.getService(UserSelfService.class);
    try {
        jwtUserSelfService.read();
        fail("Failure expected on no signature");
    } catch (AccessControlException ex) {
        // expected
    }
}
 
Example #12
Source File: JwtAccessTokenValidator.java    From cxf with Apache License 2.0 5 votes vote down vote up
public AccessTokenValidation validateAccessToken(MessageContext mc,
                                                 String authScheme,
                                                 String authSchemeData,
                                                 MultivaluedMap<String, String> extraProps)
    throws OAuthServiceException {
    try {
        JwtToken token = super.getJwtToken(authSchemeData);
        return convertClaimsToValidation(token.getClaims());
    } catch (Exception ex) {
        throw new OAuthServiceException(ex);
    }
}
 
Example #13
Source File: TestJwts.java    From deprecated-security-advanced-modules with Apache License 2.0 5 votes vote down vote up
static String createSigned(JwtToken baseJwt, JsonWebKey jwk, JwsSignatureProvider signatureProvider) {
	JwsHeaders jwsHeaders = new JwsHeaders();
	JwtToken signedToken = new JwtToken(jwsHeaders, baseJwt.getClaims());

	jwsHeaders.setKeyId(jwk.getKeyId());

       return new JoseJwtProducer().processJwt(signedToken, null, signatureProvider);
}
 
Example #14
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 #15
Source File: JWTAlgorithmTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void testUnsignedTokenFailure() 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 + "/signedjwt/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.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 #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: JWTAlgorithmTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void testUnsignedTokenSuccess() 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 + "/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.setIssuedAt(Instant.now().getEpochSecond());
    claims.setAudiences(toList(address));

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

    Book returnedBook = response.readEntity(Book.class);
    assertEquals(returnedBook.getName(), "book");
    assertEquals(returnedBook.getId(), 123L);
}
 
Example #18
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 #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: AbstractJwtAuthenticationFilter.java    From cxf with Apache License 2.0 5 votes vote down vote up
private boolean isVerifiedWithAPublicKey(JwtToken jwt) {
    if (isJwsRequired()) {
        String alg = (String)jwt.getJwsHeader(JoseConstants.HEADER_ALGORITHM);
        SignatureAlgorithm sigAlg = SignatureAlgorithm.getAlgorithm(alg);
        return SignatureAlgorithm.isPublicKeyAlgorithm(sigAlg);
    }

    return false;
}
 
Example #21
Source File: JWTAuthnAuthzTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void testAuthorizationNoRole() 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/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", "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));
    assertNotEquals(response.getStatus(), 200);
}
 
Example #22
Source File: JWTAuthnAuthzTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void testAuthorizationWrongRolesAllowedAnnotationGET() 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 + "/signedjwtauthzannotations/bookstore/booksrolesallowed";
    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", "manager");

    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.get();
    assertNotEquals(response.getStatus(), 200);
}
 
Example #23
Source File: JWTAuthnAuthzTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void testAuthorizationWrongRolesAllowedAnnotation() 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 + "/signedjwtauthzannotations/bookstore/booksrolesallowed";
    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", "manager");

    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));
    assertNotEquals(response.getStatus(), 200);
}
 
Example #24
Source File: JWTAuthnAuthzTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void testAuthorizationRolesAllowedAnnotationHEAD() 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 + "/signedjwtauthzannotations/bookstore/booksrolesallowed";
    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.head();
    assertEquals(response.getStatus(), 200);
}
 
Example #25
Source File: JWTAlgorithmTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void testBadSigningKey() 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 + "/signedjwt/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", "alice");
    properties.put("rs.security.keystore.file", "keys/alice.jks");
    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));
    assertNotEquals(response.getStatus(), 200);
}
 
Example #26
Source File: JwtRequestCodeGrant.java    From cxf with Apache License 2.0 5 votes vote down vote up
public String getRequest() {
    MultivaluedMap<String, String> map = super.toMap();
    JwtClaims claims = new JwtClaims();
    if (issuer != null) {
        claims.setIssuer(issuer);
    }
    for (String key : map.keySet()) {
        claims.setClaim(key, map.getFirst(key));
    }
    return joseProducer.processJwt(new JwtToken(claims), clientSecret);
}
 
Example #27
Source File: JWTAuthnAuthzTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void testAuthorizationWrongRole() 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/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.setProperty("role", "manager");
    claims.setAudiences(toList(address));

    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));
    assertNotEquals(response.getStatus(), 200);
}
 
Example #28
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 #29
Source File: JWTAlgorithmTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void testWrongSignatureAlgorithm() 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 + "/signedjwt/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", "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", "PS256");
    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 #30
Source File: BackChannelLogoutHandler.java    From cxf-fediz with Apache License 2.0 5 votes vote down vote up
private void submitBackChannelLogoutRequest(final Client client, final OidcUserSubject subject,
        final IdToken idTokenHint, final String uri) {
    // Application context is expected to contain HttpConduit HTTPS configuration
    final WebClient wc = WebClient.create(uri);
    IdToken idToken = idTokenHint != null ? idTokenHint : subject.getIdToken(); 
    JwtClaims claims = new JwtClaims();
    claims.setIssuer(idToken.getIssuer());
    claims.setSubject(idToken.getSubject());
    claims.setAudience(client.getClientId());
    claims.setIssuedAt(System.currentTimeMillis() / 1000);
    claims.setTokenId(Base64UrlUtility.encode(CryptoUtils.generateSecureRandomBytes(16)));
    claims.setClaim(EVENTS_PROPERTY, 
            Collections.singletonMap(BACK_CHANNEL_LOGOUT_EVENT, Collections.emptyMap()));
    if (idToken.getName() != null) {
        claims.setClaim(IdToken.NAME_CLAIM, idToken.getName());    
    }
    
    final String logoutToken = super.processJwt(new JwtToken(claims));
    executorService.submit(new Runnable() {

        @Override
        public void run() {
            try {
                wc.form(new Form().param(LOGOUT_TOKEN, logoutToken));
            } catch (Exception ex) {
                LOG.info(String.format("Back channel request to %s to log out %s from client %s has failed",
                    uri, subject.getLogin(), client.getClientId()));
                LOG.fine(String.format("%s request failure: %s", uri, ExceptionUtils.getStackTrace(ex)));
            }
        }
    
    });
    
}