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

The following examples show how to use org.apache.cxf.rs.security.jose.jwt.JwtClaims#setExpiryTime() . 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
private void doTestWriteJwsWithJwkSignedByMac(Object jsonWebKey) throws Exception {
    JwsHeaders headers = new JwsHeaders();
    headers.setType(JoseType.JWT);
    headers.setSignatureAlgorithm(SignatureAlgorithm.HS256);
    headers.setHeader(JoseConstants.HEADER_JSON_WEB_KEY, jsonWebKey);

    JwtClaims claims = new JwtClaims();
    claims.setIssuer("joe");
    claims.setExpiryTime(1300819380L);
    claims.setClaim("http://example.com/is_root", Boolean.TRUE);

    JwtToken token = new JwtToken(headers, claims);
    JwsCompactProducer jws = new JwsJwtCompactProducer(token, getWriter());
    jws.signWith(new HmacJwsSignatureProvider(ENCODED_MAC_KEY, SignatureAlgorithm.HS256));

    assertEquals(ENCODED_TOKEN_WITH_JSON_KEY_SIGNED_BY_MAC, jws.getSignedEncodedJws());
}
 
Example 2
Source File: BigQueryServer.java    From cxf with Apache License 2.0 6 votes vote down vote up
private static ClientAccessToken getAccessToken(PrivateKey privateKey, String issuer) {
    JwsHeaders headers = new JwsHeaders(JoseType.JWT, SignatureAlgorithm.RS256);
    JwtClaims claims = new JwtClaims();
    claims.setIssuer(issuer);
    claims.setAudience("https://www.googleapis.com/oauth2/v3/token");

    long issuedAt = OAuthUtils.getIssuedAt();
    claims.setIssuedAt(issuedAt);
    claims.setExpiryTime(issuedAt + 60 * 60);
    claims.setProperty("scope", "https://www.googleapis.com/auth/bigquery.readonly");

    JwtToken token = new JwtToken(headers, claims);
    JwsJwtCompactProducer p = new JwsJwtCompactProducer(token);
    String base64UrlAssertion = p.signWith(privateKey);

    JwtBearerGrant grant = new JwtBearerGrant(base64UrlAssertion);

    WebClient accessTokenService = WebClient.create("https://www.googleapis.com/oauth2/v3/token",
                                                    Arrays.asList(new OAuthJSONProvider(),
                                                                  new AccessTokenGrantWriter()));
    WebClient.getConfig(accessTokenService).getInInterceptors().add(new LoggingInInterceptor());

    accessTokenService.type(MediaType.APPLICATION_FORM_URLENCODED).accept(MediaType.APPLICATION_JSON);

    return accessTokenService.post(grant, ClientAccessToken.class);
}
 
Example 3
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 4
Source File: JwsCompactReaderWriterTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
private JwsCompactProducer initSpecJwtTokenWriter(JwsHeaders jwsHeaders) throws Exception {

        JwtClaims claims = new JwtClaims();
        claims.setIssuer("joe");
        claims.setExpiryTime(1300819380L);
        claims.setClaim("http://example.com/is_root", Boolean.TRUE);

        JwtToken token = new JwtToken(jwsHeaders, claims);
        return new JwsJwtCompactProducer(token, getWriter());
    }
 
Example 5
Source File: JWTPropertiesTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void testExpiredToken() throws Exception {

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

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

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

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

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

    JwtToken token = new JwtToken(claims);

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

    Response response = client.post(new Book("book", 123L));
    assertNotEquals(response.getStatus(), 200);
}
 
Example 6
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 7
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 8
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 9
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 10
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 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: 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 13
Source File: TokenCache.java    From g-suite-identity-sync with Apache License 2.0 5 votes vote down vote up
private ClientAccessToken getAccessToken() throws NoPrivateKeyException {
    JwsHeaders headers = new JwsHeaders(JoseType.JWT, SignatureAlgorithm.RS256);
    JwtClaims claims = new JwtClaims();
    claims.setIssuer(config.getServiceAccountEmail());
    claims.setAudience(config.getServiceAccountTokenUri());
    claims.setSubject(config.getServiceAccountSubject());

    long issuedAt = OAuthUtils.getIssuedAt();
    long tokenTimeout = config.getServiceAccountTokenLifetime();
    claims.setIssuedAt(issuedAt);
    claims.setExpiryTime(issuedAt + tokenTimeout);
    String scopes = String.join(" ", config.getServiceAccountScopes());
    claims.setProperty("scope", scopes);

    JwtToken token = new JwtToken(headers, claims);
    JwsJwtCompactProducer p = new JwsJwtCompactProducer(token);
    String base64UrlAssertion = p.signWith(config.readServiceAccountKey());

    JwtBearerGrant grant = new JwtBearerGrant(base64UrlAssertion);

    WebClient accessTokenService = WebClient.create(config.getServiceAccountTokenUri(),
            Arrays.asList(new OAuthJSONProvider(), new AccessTokenGrantWriter()));

    accessTokenService.type(MediaType.APPLICATION_FORM_URLENCODED).accept(MediaType.APPLICATION_JSON);

    return accessTokenService.post(grant, ClientAccessToken.class);
}
 
Example 14
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 15
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 16
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 17
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 18
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 19
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 20
Source File: AbstractOAuthDataProvider.java    From cxf with Apache License 2.0 4 votes vote down vote up
protected JwtClaims createJwtAccessToken(ServerAccessToken at) {
    JwtClaims claims = new JwtClaims();
    claims.setTokenId(at.getTokenKey());

    // 'client_id' or 'cid', default client_id
    String clientIdClaimName =
        JwtTokenUtils.getClaimName(OAuthConstants.CLIENT_ID, OAuthConstants.CLIENT_ID,
                                         getJwtAccessTokenClaimMap());
    claims.setClaim(clientIdClaimName, at.getClient().getClientId());
    claims.setIssuedAt(at.getIssuedAt());
    if (at.getExpiresIn() > 0) {
        claims.setExpiryTime(at.getIssuedAt() + at.getExpiresIn());
    }
    UserSubject userSubject = at.getSubject();
    if (userSubject != null) {
        if (userSubject.getId() != null) {
            claims.setSubject(userSubject.getId());
        }

        // 'username' by default to be consistent with the token introspection response
        final String usernameProp = "username";
        String usernameClaimName =
            JwtTokenUtils.getClaimName(usernameProp, usernameProp, getJwtAccessTokenClaimMap());
        claims.setClaim(usernameClaimName, userSubject.getLogin());
    }
    if (at.getIssuer() != null) {
        claims.setIssuer(at.getIssuer());
    }
    if (!at.getScopes().isEmpty()) {
        claims.setClaim(OAuthConstants.SCOPE,
                        OAuthUtils.convertPermissionsToScopeList(at.getScopes()));
    }
    // OAuth2 resource indicators (resource server audience)
    if (!at.getAudiences().isEmpty()) {
        List<String> resourceAudiences = at.getAudiences();
        if (resourceAudiences.size() == 1) {
            claims.setAudience(resourceAudiences.get(0));
        } else {
            claims.setAudiences(resourceAudiences);
        }
    }
    if (!at.getExtraProperties().isEmpty()) {
        Map<String, String> actualExtraProps = new HashMap<>();
        for (Map.Entry<String, String> entry : at.getExtraProperties().entrySet()) {
            if (JoseConstants.HEADER_X509_THUMBPRINT_SHA256.equals(entry.getKey())) {
                claims.setClaim(JwtConstants.CLAIM_CONFIRMATION,
                    Collections.singletonMap(JoseConstants.HEADER_X509_THUMBPRINT_SHA256,
                                             entry.getValue()));
            } else {
                actualExtraProps.put(entry.getKey(), entry.getValue());
            }
        }
        claims.setClaim("extra_properties", actualExtraProps);
    }
    // Can be used to check at RS/etc which grant was used to get this token issued
    if (at.getGrantType() != null) {
        claims.setClaim(OAuthConstants.GRANT_TYPE, at.getGrantType());
    }
    // Can be used to check the original code grant value which was removed from the storage
    // (and is no longer valid) when this token was issued; relevant only if the authorization
    // code flow was used
    if (at.getGrantCode() != null) {
        claims.setClaim(OAuthConstants.AUTHORIZATION_CODE_GRANT, at.getGrantCode());
    }
    // Can be used to link the clients (especially public ones) to this token
    // to have a knowledge which client instance is using this token - might be handy at the RS/etc
    if (at.getClientCodeVerifier() != null) {
        claims.setClaim(OAuthConstants.AUTHORIZATION_CODE_VERIFIER, at.getClientCodeVerifier());
    }
    if (at.getNonce() != null) {
        claims.setClaim(OAuthConstants.NONCE, at.getNonce());
    }
    return claims;
}