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

The following examples show how to use org.apache.cxf.rs.security.jose.jwt.JwtClaims#setNotBefore() . 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: JwsCompactReaderWriterTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testWriteReadJwsUnsigned() throws Exception {
    JwsHeaders headers = new JwsHeaders(JoseType.JWT);
    headers.setSignatureAlgorithm(SignatureAlgorithm.NONE);

    JwtClaims claims = new JwtClaims();
    claims.setIssuer("https://jwt-idp.example.com");
    claims.setSubject("mailto:[email protected]");
    claims.setAudiences(Collections.singletonList("https://jwt-rp.example.net"));
    claims.setNotBefore(1300815780L);
    claims.setExpiryTime(1300819380L);
    claims.setClaim("http://claims.example.com/member", true);

    JwsCompactProducer writer = new JwsJwtCompactProducer(headers, claims);
    String signed = writer.getSignedEncodedJws();

    JwsJwtCompactConsumer reader = new JwsJwtCompactConsumer(signed);
    assertEquals(0, reader.getDecodedSignature().length);

    JwtToken token = reader.getJwtToken();
    assertEquals(new JwtToken(headers, claims), token);
}
 
Example 2
Source File: AuthTokenProcessorHandler.java    From deprecated-security-advanced-modules with Apache License 2.0 5 votes vote down vote up
private String createJwt(SamlResponse samlResponse) throws Exception {
    JwtClaims jwtClaims = new JwtClaims();
    JwtToken jwt = new JwtToken(jwtClaims);

    jwtClaims.setNotBefore(System.currentTimeMillis() / 1000);
    jwtClaims.setExpiryTime(getJwtExpiration(samlResponse));

    jwtClaims.setProperty(this.jwtSubjectKey, this.extractSubject(samlResponse));

    if (this.samlSubjectKey != null) {
        jwtClaims.setProperty("saml_ni", samlResponse.getNameId());
    }

    if (samlResponse.getNameIdFormat() != null) {
        jwtClaims.setProperty("saml_nif", SamlNameIdFormat.getByUri(samlResponse.getNameIdFormat()).getShortName());
    }

    String sessionIndex = samlResponse.getSessionIndex();

    if (sessionIndex != null) {
        jwtClaims.setProperty("saml_si", sessionIndex);
    }

    if (this.samlRolesKey != null && this.jwtRolesKey != null) {
        String[] roles = this.extractRoles(samlResponse);

        jwtClaims.setProperty(this.jwtRolesKey, roles);
    }

    String encodedJwt = this.jwtProducer.processJwt(jwt);

    if (token_log.isDebugEnabled()) {
        token_log.debug("Created JWT: " + encodedJwt + "\n" + jsonMapReaderWriter.toJson(jwt.getJwsHeaders()) + "\n"
                + JwtUtils.claimsToJson(jwt.getClaims()));
    }

    return encodedJwt;
}
 
Example 3
Source File: JWTITCase.java    From syncope with Apache License 2.0 5 votes vote down vote up
@Test
public void tokenValidation() 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(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);
    jwtUserSelfService.read();
}
 
Example 4
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 5
Source File: JWTITCase.java    From syncope with Apache License 2.0 5 votes vote down vote up
@Test
public void thirdPartyToken() throws ParseException {
    assumeFalse(SignatureAlgorithm.isPublicKeyAlgorithm(JWS_ALGORITHM));

    // Create a new 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(UUID.randomUUID().toString());
    jwtClaims.setSubject("[email protected]");
    jwtClaims.setIssuedAt(currentTime);
    jwtClaims.setIssuer(CustomJWTSSOProvider.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);

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

    SyncopeClient jwtClient = clientFactory.create(signed);

    Pair<Map<String, Set<String>>, UserTO> self = jwtClient.self();
    assertFalse(self.getLeft().isEmpty());
    assertEquals("puccini", self.getRight().getUsername());
}
 
Example 6
Source File: JWTITCase.java    From syncope with Apache License 2.0 5 votes vote down vote up
@Test
public void thirdPartyTokenUnknownUser() throws ParseException {
    assumeFalse(SignatureAlgorithm.isPublicKeyAlgorithm(JWS_ALGORITHM));

    // Create a new 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(UUID.randomUUID().toString());
    jwtClaims.setSubject("[email protected]");
    jwtClaims.setIssuedAt(currentTime);
    jwtClaims.setIssuer(CustomJWTSSOProvider.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);

    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 an unknown subject");
    } catch (AccessControlException ex) {
        // expected
    }
}
 
Example 7
Source File: JWTITCase.java    From syncope with Apache License 2.0 5 votes vote down vote up
@Test
public void thirdPartyTokenUnknownIssuer() throws ParseException {
    assumeFalse(SignatureAlgorithm.isPublicKeyAlgorithm(JWS_ALGORITHM));

    // Create a new 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(UUID.randomUUID().toString());
    jwtClaims.setSubject("[email protected]");
    jwtClaims.setIssuedAt(currentTime);
    jwtClaims.setIssuer(CustomJWTSSOProvider.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);

    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 an unknown issuer");
    } catch (AccessControlException ex) {
        // expected
    }
}
 
Example 8
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 9
Source File: AccessTokenDataBinderImpl.java    From syncope with Apache License 2.0 5 votes vote down vote up
@Override
public Pair<String, Date> generateJWT(
        final String tokenId,
        final String subject,
        final long duration,
        final Map<String, Object> claims) {

    credentialChecker.checkIsDefaultJWSKeyInUse();

    long currentTime = new Date().getTime() / 1000L;
    long expiryTime = currentTime + 60L * duration;

    JwtClaims jwtClaims = new JwtClaims();
    jwtClaims.setTokenId(tokenId);
    jwtClaims.setSubject(subject);
    jwtClaims.setIssuedAt(currentTime);
    jwtClaims.setIssuer(jwtIssuer);
    jwtClaims.setExpiryTime(expiryTime);
    jwtClaims.setNotBefore(currentTime);
    claims.forEach(jwtClaims::setClaim);

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

    String signed = producer.signWith(jwsSignatureProvider);

    return Pair.of(signed, new Date(expiryTime * 1000L));
}
 
Example 10
Source File: JWTPropertiesTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void testNotBeforeFailure() throws Exception {

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

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

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

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

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

    JwtToken token = new JwtToken(claims);

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

    Response response = client.post(new Book("book", 123L));
    assertNotEquals(response.getStatus(), 200);
}
 
Example 11
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 12
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 13
Source File: JWTITCase.java    From syncope with Apache License 2.0 4 votes vote down vote up
@Test
public void expiredToken() 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(JWT_ISSUER);
    jwtClaims.setExpiryTime((now.getTime() - 5000L) / 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 expired token");
    } catch (AccessControlException ex) {
        // expected
    }
}
 
Example 14
Source File: JWTITCase.java    From syncope with Apache License 2.0 4 votes vote down vote up
@Test
public void notBefore() 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(JWT_ISSUER);
    jwtClaims.setExpiryTime(expiry.getTime().getTime() / 1000L);
    jwtClaims.setNotBefore(currentTime + 60L);

    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 a token that is not valid yet");
    } catch (AccessControlException 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: 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());
    }
}