Java Code Examples for org.apache.cxf.rs.security.jose.jwt.JwtClaims#setIssuedAt()

The following examples show how to use org.apache.cxf.rs.security.jose.jwt.JwtClaims#setIssuedAt() . 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: JWTITCase.java    From syncope with Apache License 2.0 5 votes vote down vote up
@Test
public void thirdPartyTokenBadSignature() throws ParseException {
    assumeFalse(SignatureAlgorithm.isPublicKeyAlgorithm(JWS_ALGORITHM));

    // Create a new token
    Date now = new Date();

    Calendar expiry = Calendar.getInstance();
    expiry.setTime(now);
    expiry.add(Calendar.MINUTE, 5);

    JwtClaims jwtClaims = new JwtClaims();
    jwtClaims.setTokenId(UUID.randomUUID().toString());
    jwtClaims.setSubject("[email protected]");
    jwtClaims.setIssuedAt(now.getTime());
    jwtClaims.setIssuer(CustomJWTSSOProvider.ISSUER);
    jwtClaims.setExpiryTime(expiry.getTime().getTime());
    jwtClaims.setNotBefore(now.getTime());

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

    JwsSignatureProvider customSignatureProvider =
            new HmacJwsSignatureProvider((CustomJWTSSOProvider.CUSTOM_KEY + '_').getBytes(), JWS_ALGORITHM);
    String signed = producer.signWith(customSignatureProvider);

    SyncopeClient jwtClient = clientFactory.create(signed);

    try {
        jwtClient.self();
        fail("Failure expected on a bad signature");
    } catch (AccessControlException ex) {
        // expected
    }
}
 
Example 2
Source File: JWTAlgorithmTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void testWrongKeyEncryptionAlgorithm() throws Exception {

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

    List<Object> providers = new ArrayList<>();
    providers.add(new JacksonJsonProvider());
    JwtAuthenticationClientFilter clientFilter = new JwtAuthenticationClientFilter();
    clientFilter.setJwsRequired(false);
    clientFilter.setJweRequired(true);
    providers.add(clientFilter);

    String address = "https://localhost:" + PORT + "/encryptedjwt/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/jwkPublicSet.txt");
    properties.put("rs.security.encryption.content.algorithm", "A128GCM");
    properties.put("rs.security.encryption.key.algorithm", "RSA1_5");
    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 3
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 4
Source File: JWTAlgorithmTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void testEncryptionProperties() throws Exception {

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

    List<Object> providers = new ArrayList<>();
    providers.add(new JacksonJsonProvider());
    JwtAuthenticationClientFilter clientFilter = new JwtAuthenticationClientFilter();
    clientFilter.setJwsRequired(false);
    clientFilter.setJweRequired(true);
    providers.add(clientFilter);

    String address = "https://localhost:" + PORT + "/encryptedjwt/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.encryption.properties",
        "org/apache/cxf/systest/jaxrs/security/bob.jwk.properties");
    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 5
Source File: JWTAlgorithmTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void testSmallSignatureKeySize() 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.alias", "smallkey");
    properties.put("rs.security.keystore.password", "security");
    properties.put("rs.security.key.password", "security");
    properties.put("rs.security.keystore.file",
        "org/apache/cxf/systest/jaxrs/security/certs/smallkeysize.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 6
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 7
Source File: JWTAlgorithmTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void testSignatureDynamic() 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", "RS256");
    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 8
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 9
Source File: JWTAuthnAuthzTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void testAuthenticationFailure() 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 + "/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 10
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 11
Source File: JWTAlgorithmTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void testSignatureProperties() 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.properties",
                   "org/apache/cxf/systest/jaxrs/security/alice.jwk.properties");
    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 12
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 13
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)));
            }
        }
    
    });
    
}
 
Example 14
Source File: AuthorizationGrantNegativeTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
@org.junit.Test
public void testJWTUnauthenticatedSignature() throws Exception {
    URL busFile = AuthorizationGrantNegativeTest.class.getResource("client.xml");

    String address = "https://localhost:" + port + "/services/";
    WebClient client = WebClient.create(address, OAuth2TestUtils.setupProviders(),
                                        "alice", "security", busFile.toString());

    // Create the JWT Token
    // Create the JWT Token
    JwtClaims claims = new JwtClaims();
    claims.setSubject("consumer-id");
    claims.setIssuer("DoubleItSTSIssuer");
    Instant now = Instant.now();
    claims.setIssuedAt(now.getEpochSecond());
    claims.setExpiryTime(now.plusSeconds(60L).getEpochSecond());
    String audience = "https://localhost:" + port + "/services/token";
    claims.setAudiences(Collections.singletonList(audience));

    // Sign the JWT Token
    Properties signingProperties = new Properties();
    signingProperties.put("rs.security.keystore.type", "jks");
    signingProperties.put("rs.security.keystore.password", "security");
    signingProperties.put("rs.security.keystore.alias", "smallkey");
    signingProperties.put("rs.security.keystore.file",
        "org/apache/cxf/systest/jaxrs/security/certs/smallkeysize.jks");
    signingProperties.put("rs.security.key.password", "security");
    signingProperties.put("rs.security.signature.algorithm", "RS256");

    JwsHeaders jwsHeaders = new JwsHeaders(signingProperties);
    JwsJwtCompactProducer jws = new JwsJwtCompactProducer(jwsHeaders, claims);

    JwsSignatureProvider sigProvider =
        JwsUtils.loadSignatureProvider(signingProperties, jwsHeaders);

    String token = jws.signWith(sigProvider);

    // Get Access Token
    client.type("application/x-www-form-urlencoded").accept("application/json");
    client.path("token");

    Form form = new Form();
    form.param("grant_type", "urn:ietf:params:oauth:grant-type:jwt-bearer");
    form.param("assertion", token);
    form.param("client_id", "consumer-id");
    Response response = client.post(form);

    try {
        response.readEntity(ClientAccessToken.class);
        fail("Failure expected on an unauthenticated token");
    } catch (Exception ex) {
        // expected
    }
}
 
Example 15
Source File: JWTITCase.java    From syncope with Apache License 2.0 4 votes vote down vote up
@Test
public void unknownId() 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);

    // Create a new token using an unknown Id
    Date now = new Date();
    long currentTime = now.getTime() / 1000L;

    Calendar expiry = Calendar.getInstance();
    expiry.setTime(now);
    expiry.add(Calendar.MINUTE, 5);

    JwtClaims jwtClaims = new JwtClaims();
    jwtClaims.setTokenId(UUID.randomUUID().toString());
    jwtClaims.setSubject(ADMIN_UNAME);
    jwtClaims.setIssuedAt(currentTime);
    jwtClaims.setIssuer(JWT_ISSUER);
    jwtClaims.setExpiryTime(expiry.getTime().getTime() / 1000L);
    jwtClaims.setNotBefore(currentTime);

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

    String signed = producer.signWith(jwsSignatureProvider);

    SyncopeClient jwtClient = clientFactory.create(signed);
    UserSelfService jwtUserSelfService = jwtClient.getService(UserSelfService.class);
    try {
        jwtUserSelfService.read();
        fail("Failure expected on an unknown id");
    } catch (AccessControlException ex) {
        // expected
    }
}
 
Example 16
Source File: OIDCNegativeTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
@org.junit.Test
public void testJWTRequestNonmatchingResponseType() throws Exception {
    URL busFile = OIDCNegativeTest.class.getResource("client.xml");

    String address = "https://localhost:" + port + "/unsignedjwtservices/";
    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);

    JwtClaims claims = new JwtClaims();
    claims.setIssuer("consumer-id");
    claims.setIssuedAt(Instant.now().getEpochSecond());
    claims.setAudiences(
        Collections.singletonList("https://localhost:" + port + "/unsignedjwtservices/"));
    claims.setProperty("response_type", "token");

    JwsHeaders headers = new JwsHeaders();
    headers.setAlgorithm("none");

    JwtToken token = new JwtToken(headers, claims);

    JwsJwtCompactProducer jws = new JwsJwtCompactProducer(token);
    String request = jws.getSignedEncodedJws();

    AuthorizationCodeParameters parameters = new AuthorizationCodeParameters();
    parameters.setConsumerId("consumer-id");
    parameters.setScope("openid");
    parameters.setResponseType("code");
    parameters.setPath("authorize/");
    parameters.setRequest(request);

    // Get Authorization Code
    try {
        OAuth2TestUtils.getLocation(client, parameters);
        fail("Failure expected on a non-matching response_type");
    } catch (ResponseProcessingException ex) {
        // expected
    }
}
 
Example 17
Source File: DefaultJWTClaimsProvider.java    From cxf with Apache License 2.0 4 votes vote down vote up
protected void handleConditions(JWTClaimsProviderParameters jwtClaimsProviderParameters, JwtClaims claims) {
    TokenProviderParameters providerParameters = jwtClaimsProviderParameters.getProviderParameters();

    Instant currentDate = Instant.now();
    long currentTime = currentDate.getEpochSecond();

    // Set the defaults first
    claims.setIssuedAt(currentTime);
    claims.setNotBefore(currentTime);
    claims.setExpiryTime(currentTime + lifetime);

    Lifetime tokenLifetime = providerParameters.getTokenRequirements().getLifetime();
    if (lifetime > 0 && acceptClientLifetime && tokenLifetime != null
        && tokenLifetime.getCreated() != null && tokenLifetime.getExpires() != null) {
        Instant creationTime = null;
        Instant expirationTime = null;
        try {
            creationTime = ZonedDateTime.parse(tokenLifetime.getCreated()).toInstant();
            expirationTime = ZonedDateTime.parse(tokenLifetime.getExpires()).toInstant();
        } catch (DateTimeParseException ex) {
            LOG.fine("Error in parsing Timestamp Created or Expiration Strings");
            throw new STSException(
                                   "Error in parsing Timestamp Created or Expiration Strings",
                                   STSException.INVALID_TIME
                );
        }

        // Check to see if the created time is in the future
        Instant validCreation = Instant.now();
        if (futureTimeToLive > 0) {
            validCreation = validCreation.plusSeconds(futureTimeToLive);
        }
        if (creationTime.isAfter(validCreation)) {
            LOG.fine("The Created Time is too far in the future");
            throw new STSException("The Created Time is too far in the future", STSException.INVALID_TIME);
        }

        long requestedLifetime = Duration.between(creationTime, expirationTime).getSeconds();
        if (requestedLifetime > getMaxLifetime()) {
            StringBuilder sb = new StringBuilder();
            sb.append("Requested lifetime [").append(requestedLifetime);
            sb.append(" sec] exceed configured maximum lifetime [").append(getMaxLifetime());
            sb.append(" sec]");
            LOG.warning(sb.toString());
            if (isFailLifetimeExceedance()) {
                throw new STSException("Requested lifetime exceeds maximum lifetime",
                                       STSException.INVALID_TIME);
            }
            expirationTime = creationTime.plusSeconds(getMaxLifetime());
        }

        long creationTimeInSeconds = creationTime.getEpochSecond();
        claims.setIssuedAt(creationTimeInSeconds);
        claims.setNotBefore(creationTimeInSeconds);
        claims.setExpiryTime(expirationTime.getEpochSecond());
    }
}
 
Example 18
Source File: JWTAuthnAuthzTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
@org.junit.Test
public void testAuthorizationRolesAllowedAnnotation() 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.post(new Book("book", 123L));
    assertEquals(response.getStatus(), 200);

    Book returnedBook = response.readEntity(Book.class);
    assertEquals(returnedBook.getName(), "book");
    assertEquals(returnedBook.getId(), 123L);
}
 
Example 19
Source File: JWTITCase.java    From syncope with Apache License 2.0 4 votes vote down vote up
@Test
public void invalidIssuer() 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
    Date now = new Date();
    long currentTime = now.getTime() / 1000L;

    Calendar expiry = Calendar.getInstance();
    expiry.setTime(now);
    expiry.add(Calendar.MINUTE, 5);

    JwtClaims jwtClaims = new JwtClaims();
    jwtClaims.setTokenId(tokenId);
    jwtClaims.setSubject(ADMIN_UNAME);
    jwtClaims.setIssuedAt(currentTime);
    jwtClaims.setIssuer("UnknownIssuer");
    jwtClaims.setExpiryTime(expiry.getTime().getTime() / 1000L);
    jwtClaims.setNotBefore(currentTime);

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

    String signed = producer.signWith(jwsSignatureProvider);

    SyncopeClient jwtClient = clientFactory.create(signed);
    UserSelfService jwtUserSelfService = jwtClient.getService(UserSelfService.class);
    try {
        jwtUserSelfService.read();
        fail("Failure expected on an invalid issuer");
    } catch (AccessControlException ex) {
        // expected
    }
}
 
Example 20
Source File: JWTAlgorithmTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
@org.junit.Test
public void testBadEncryptingKey() throws Exception {
    if (!SecurityTestUtil.checkUnrestrictedPoliciesInstalled()) {
        return;
    }

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

    List<Object> providers = new ArrayList<>();
    providers.add(new JacksonJsonProvider());
    JwtAuthenticationClientFilter clientFilter = new JwtAuthenticationClientFilter();
    clientFilter.setJwsRequired(false);
    clientFilter.setJweRequired(true);
    providers.add(clientFilter);

    String address = "https://localhost:" + PORT + "/encryptedjwt/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", "AliceCert");
    properties.put("rs.security.keystore.file", "org/apache/cxf/systest/jaxrs/security/certs/jwkPublicSet.txt");
    properties.put("rs.security.encryption.content.algorithm", "A128GCM");
    properties.put("rs.security.encryption.key.algorithm", "RSA-OAEP");
    properties.put(JwtConstants.JWT_TOKEN, token);
    WebClient.getConfig(client).getRequestContext().putAll(properties);

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