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

The following examples show how to use org.apache.cxf.rs.security.jose.jwt.JwtClaims. 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: JWTAlgorithmTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@org.junit.Test
public void testBadSignatureCertificateTest() throws Exception {

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

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

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

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

    JwtToken token = new JwtToken(claims);

    Map<String, Object> properties = new HashMap<>();
    properties.put("rs.security.keystore.type", "jks");
    properties.put("rs.security.keystore.password", "password");
    properties.put("rs.security.key.password", "password");
    properties.put("rs.security.keystore.alias", "bethal");
    properties.put("rs.security.keystore.file", "keys/Bethal.jks");
    properties.put("rs.security.signature.algorithm", "RS256");
    properties.put("rs.security.signature.include.cert", "true");
    properties.put(JwtConstants.JWT_TOKEN, token);
    WebClient.getConfig(client).getRequestContext().putAll(properties);

    Response response = client.post(new Book("book", 123L));
    assertNotEquals(response.getStatus(), 200);
}
 
Example #2
Source File: SyncopeJWTSSOProvider.java    From syncope with Apache License 2.0 6 votes vote down vote up
@Transactional(readOnly = true)
@Override
public Pair<User, Set<SyncopeGrantedAuthority>> resolve(final JwtClaims jwtClaims) {
    User user = userDAO.findByUsername(jwtClaims.getSubject());
    Set<SyncopeGrantedAuthority> authorities = Set.of();
    if (user != null) {
        AccessToken accessToken = accessTokenDAO.find(jwtClaims.getTokenId());
        if (accessToken != null && accessToken.getAuthorities() != null) {
            try {
                authorities = POJOHelper.deserialize(
                        ENCRYPTOR.decode(new String(accessToken.getAuthorities()), CipherAlgorithm.AES),
                        new TypeReference<Set<SyncopeGrantedAuthority>>() {
                });
            } catch (Throwable t) {
                LOG.error("Could not read stored authorities", t);
            }
        }
    }

    return Pair.of(user, authorities);
}
 
Example #3
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 #4
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 #5
Source File: AbstractOIDCTest.java    From cxf-fediz with Apache License 2.0 6 votes vote down vote up
private void validateIdToken(String idToken, String audience, String role) throws IOException {
    JwsJwtCompactConsumer jwtConsumer = new JwsJwtCompactConsumer(idToken);
    JwtToken jwt = jwtConsumer.getJwtToken();
    JwtClaims jwtClaims = jwt.getClaims();

    // Validate claims
    assertEquals("alice", jwtClaims.getClaim("preferred_username"));
    assertEquals("accounts.fediz.com", jwtClaims.getIssuer());
    assertEquals(audience, jwtClaims.getAudience());
    assertNotNull(jwtClaims.getIssuedAt());
    assertNotNull(jwtClaims.getExpiryTime());

    // Check role
    if (role != null) {
        List<String> roles = jwtClaims.getListStringProperty("roles");
        assertNotNull(roles);
        assertTrue(roles.contains(role));
    }

    JwsHeaders jwsHeaders = jwt.getJwsHeaders();
    assertTrue(jwtConsumer.verifySignatureWith(
        jsonWebKeys().getKey(jwsHeaders.getKeyId()), SignatureAlgorithm.valueOf(jwsHeaders.getAlgorithm())));
}
 
Example #6
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 #7
Source File: AbstractHTTPJwtAuthenticator.java    From deprecated-security-advanced-modules with Apache License 2.0 6 votes vote down vote up
protected String extractSubject(JwtClaims claims) {
    String subject = claims.getSubject();

    if (subjectKey != null) {
        Object subjectObject = claims.getClaim(subjectKey);

        if (subjectObject == null) {
            log.warn("Failed to get subject from JWT claims, check if subject_key '{}' is correct.", subjectKey);
            return null;
        }

        // We expect a String. If we find something else, convert to String but issue a
        // warning
        if (!(subjectObject instanceof String)) {
            log.warn(
                    "Expected type String for roles in the JWT for subject_key {}, but value was '{}' ({}). Will convert this value to String.",
                    subjectKey, subjectObject, subjectObject.getClass());
            subject = String.valueOf(subjectObject);
        } else {
            subject = (String) subjectObject;
        }
    }
    return subject;
}
 
Example #8
Source File: AuthorizationGrantTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
private static void validateAccessToken(String accessToken)
    throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException {
    JwsJwtCompactConsumer jwtConsumer = new JwsJwtCompactConsumer(accessToken);
    JwtClaims jwtClaims = jwtConsumer.getJwtToken().getClaims();

    // Validate claims
    if (!OAuthConstants.CLIENT_CREDENTIALS_GRANT.equals(jwtClaims.getStringProperty(OAuthConstants.GRANT_TYPE))) {
        // We don't have a Subject for the client credential grant
        assertNotNull(jwtClaims.getSubject());
    }
    assertNotNull(jwtClaims.getIssuedAt());
    assertNotNull(jwtClaims.getExpiryTime());
    assertEquals(ISSUER, jwtClaims.getIssuer());

    KeyStore keystore = KeyStore.getInstance("JKS");
    keystore.load(ClassLoaderUtils.getResourceAsStream("keys/alice.jks", AuthorizationGrantTest.class),
                  "password".toCharArray());
    Certificate cert = keystore.getCertificate("alice");
    assertNotNull(cert);

    assertTrue(jwtConsumer.verifySignatureWith((X509Certificate)cert,
                                                      SignatureAlgorithm.RS256));
}
 
Example #9
Source File: TestJwts.java    From deprecated-security-advanced-modules with Apache License 2.0 6 votes vote down vote up
static JwtToken create(String subject, String audience, Object... moreClaims) {
	JwtClaims claims = new JwtClaims();

	claims.setSubject(subject);
	claims.setAudience(audience);

	if (moreClaims != null) {
		for (int i = 0; i < moreClaims.length; i += 2) {
			claims.setClaim(String.valueOf(moreClaims[i]), moreClaims[i + 1]);
		}
	}

	JwtToken result = new JwtToken(claims);

	return result;
}
 
Example #10
Source File: DefaultJWTClaimsProvider.java    From cxf with Apache License 2.0 6 votes vote down vote up
/**
 * Get a JwtClaims object.
 */
public JwtClaims getJwtClaims(JWTClaimsProviderParameters jwtClaimsProviderParameters) {

    JwtClaims claims = new JwtClaims();
    claims.setSubject(getSubjectName(jwtClaimsProviderParameters));
    claims.setTokenId(UUID.randomUUID().toString());

    // Set the Issuer
    String issuer = jwtClaimsProviderParameters.getIssuer();
    if (issuer == null) {
        STSPropertiesMBean stsProperties = jwtClaimsProviderParameters.getProviderParameters().getStsProperties();
        claims.setIssuer(stsProperties.getIssuer());
    } else {
        claims.setIssuer(issuer);
    }

    handleWSTrustClaims(jwtClaimsProviderParameters, claims);

    handleConditions(jwtClaimsProviderParameters, claims);

    handleAudienceRestriction(jwtClaimsProviderParameters, claims);

    handleActAs(jwtClaimsProviderParameters, claims);

    return claims;
}
 
Example #11
Source File: DefaultJWTClaimsProvider.java    From cxf with Apache License 2.0 6 votes vote down vote up
protected void handleWSTrustClaims(JWTClaimsProviderParameters jwtClaimsProviderParameters, JwtClaims claims) {
    TokenProviderParameters providerParameters = jwtClaimsProviderParameters.getProviderParameters();

    // Handle Claims
    ProcessedClaimCollection retrievedClaims = ClaimsUtils.processClaims(providerParameters);
    if (retrievedClaims != null) {
        Iterator<ProcessedClaim> claimIterator = retrievedClaims.iterator();
        while (claimIterator.hasNext()) {
            ProcessedClaim claim = claimIterator.next();
            if (claim.getClaimType() != null && claim.getValues() != null && !claim.getValues().isEmpty()) {
                Object claimValues = claim.getValues();
                if (claim.getValues().size() == 1) {
                    claimValues = claim.getValues().get(0);
                }
                claims.setProperty(translateClaim(claim.getClaimType().toString()), claimValues);
            }
        }
    }
}
 
Example #12
Source File: AbstractOAuthDataProvider.java    From cxf with Apache License 2.0 5 votes vote down vote up
protected ServerAccessToken doCreateAccessToken(AccessTokenRegistration atReg) {
    ServerAccessToken at = createNewAccessToken(atReg.getClient(), atReg.getSubject());
    at.setAudiences(atReg.getAudiences());
    at.setGrantType(atReg.getGrantType());
    List<String> theScopes = atReg.getApprovedScope();
    List<OAuthPermission> thePermissions =
        convertScopeToPermissions(atReg.getClient(), theScopes);
    at.setScopes(thePermissions);
    at.setSubject(atReg.getSubject());
    at.setClientCodeVerifier(atReg.getClientCodeVerifier());
    at.setNonce(atReg.getNonce());
    at.setResponseType(atReg.getResponseType());
    at.setGrantCode(atReg.getGrantCode());
    at.getExtraProperties().putAll(atReg.getExtraProperties());

    if (messageContext != null) {
        String certCnf = (String)messageContext.get(JoseConstants.HEADER_X509_THUMBPRINT_SHA256);
        if (certCnf != null) {
            // At a later stage we will likely introduce a dedicated Confirmation bean (as it is used in POP etc)
            at.getExtraProperties().put(JoseConstants.HEADER_X509_THUMBPRINT_SHA256, certCnf);
        }
    }

    if (isUseJwtFormatForAccessTokens()) {
        JwtClaims claims = createJwtAccessToken(at);
        String jose = processJwtAccessToken(claims);
        if (isPersistJwtEncoding()) {
            at.setTokenKey(jose);
        } else {
            at.setEncodedToken(jose);
        }
    }

    return at;
}
 
Example #13
Source File: JwtRequestCodeGrant.java    From cxf with Apache License 2.0 5 votes vote down vote up
public String getRequest() {
    MultivaluedMap<String, String> map = super.toMap();
    JwtClaims claims = new JwtClaims();
    if (issuer != null) {
        claims.setIssuer(issuer);
    }
    for (String key : map.keySet()) {
        claims.setClaim(key, map.getFirst(key));
    }
    return joseProducer.processJwt(new JwtToken(claims), clientSecret);
}
 
Example #14
Source File: JWTAuthnAuthzTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void testAuthentication() 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", "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 #15
Source File: JWTPropertiesTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void testBadAudience() 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());
    String badAddress = "https://localhost:" + PORT + "/badunsignedjwt/bookstore/books";
    claims.setAudiences(toList(badAddress));

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

    Response response = client.post(new Book("book", 123L));
    assertNotEquals(response.getStatus(), 200);
}
 
Example #16
Source File: JWTPropertiesTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void testNoAudience() 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());

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

    Response response = client.post(new Book("book", 123L));
    assertEquals(response.getStatus(), 200);
}
 
Example #17
Source File: JWTPropertiesTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void testMultipleAudiences() 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());

    String badAddress = "https://localhost:" + PORT + "/badunsignedjwt/bookstore/books";
    List<String> audiences = new ArrayList<>();
    audiences.add(address);
    audiences.add(badAddress);
    claims.setAudiences(audiences);

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

    Response response = client.post(new Book("book", 123L));
    assertEquals(response.getStatus(), 200);
}
 
Example #18
Source File: JwsCompactReaderWriterTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testNoneSignature() throws Exception {
    JwtClaims claims = new JwtClaims();
    claims.setClaim("a", "b");
    JwsJwtCompactProducer producer = new JwsJwtCompactProducer(claims);
    producer.signWith(new NoneJwsSignatureProvider());

    JwsJwtCompactConsumer consumer = new JwsJwtCompactConsumer(producer.getSignedEncodedJws());
    assertTrue(consumer.verifySignatureWith(new NoneJwsSignatureVerifier()));
    JwtClaims claims2 = consumer.getJwtClaims();
    assertEquals(claims, claims2);
}
 
Example #19
Source File: DefaultJWTClaimsProvider.java    From cxf with Apache License 2.0 5 votes vote down vote up
/**
 * Set the audience restriction claim. The Audiences are from an AppliesTo address, and the wst:Participants
 * (if either exist).
 */
protected void handleAudienceRestriction(
    JWTClaimsProviderParameters jwtClaimsProviderParameters, JwtClaims claims
) {
    TokenProviderParameters providerParameters = jwtClaimsProviderParameters.getProviderParameters();

    List<String> audiences = new ArrayList<>();
    String appliesToAddress = providerParameters.getAppliesToAddress();
    if (appliesToAddress != null) {
        audiences.add(appliesToAddress);
    }

    Participants participants = providerParameters.getTokenRequirements().getParticipants();
    if (participants != null) {
        String address = TokenProviderUtils.extractAddressFromParticipantsEPR(participants.getPrimaryParticipant());
        if (address != null) {
            audiences.add(address);
        }

        if (participants.getParticipants() != null) {
            for (Object participant : participants.getParticipants()) {
                if (participant != null) {
                    address = TokenProviderUtils.extractAddressFromParticipantsEPR(participant);
                    if (address != null) {
                        audiences.add(address);
                    }
                }
            }
        }
    }
    if (!audiences.isEmpty()) {
        claims.setAudiences(audiences);
    }

}
 
Example #20
Source File: JWTPropertiesTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void testNearFutureTokenSuccess() 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.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 #21
Source File: JWTAlgorithmTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void testUnsignedTokenFailure() throws Exception {

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

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

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

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

    JwtToken token = new JwtToken(claims);

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

    Response response = client.post(new Book("book", 123L));
    assertNotEquals(response.getStatus(), 200);
}
 
Example #22
Source File: JWTAuthnAuthzTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void testAuthorizationWrongRole() throws Exception {

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

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

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

    // Create the JWT Token
    JwtClaims claims = new JwtClaims();
    claims.setSubject("alice");
    claims.setIssuer("DoubleItSTSIssuer");
    claims.setIssuedAt(Instant.now().getEpochSecond());
    claims.setProperty("role", "manager");
    claims.setAudiences(toList(address));

    JwtToken token = new JwtToken(claims);

    Map<String, Object> properties = new HashMap<>();
    properties.put("rs.security.keystore.type", "jwk");
    properties.put("rs.security.keystore.alias", "2011-04-29");
    properties.put("rs.security.keystore.file",
                   "org/apache/cxf/systest/jaxrs/security/certs/jwkPrivateSet.txt");
    properties.put("rs.security.signature.algorithm", "RS256");
    properties.put(JwtConstants.JWT_TOKEN, token);
    WebClient.getConfig(client).getRequestContext().putAll(properties);

    Response response = client.post(new Book("book", 123L));
    assertNotEquals(response.getStatus(), 200);
}
 
Example #23
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 #24
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 #25
Source File: JWTAuthnAuthzTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void testAuthorizationWrongRolesAllowedAnnotationGET() throws Exception {

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

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

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

    // Create the JWT Token
    JwtClaims claims = new JwtClaims();
    claims.setSubject("alice");
    claims.setIssuer("DoubleItSTSIssuer");
    claims.setIssuedAt(Instant.now().getEpochSecond());
    claims.setAudiences(toList(address));
    // The endpoint requires a role of "boss"
    claims.setProperty("role", "manager");

    JwtToken token = new JwtToken(claims);

    Map<String, Object> properties = new HashMap<>();
    properties.put("rs.security.keystore.type", "jwk");
    properties.put("rs.security.keystore.alias", "2011-04-29");
    properties.put("rs.security.keystore.file",
                   "org/apache/cxf/systest/jaxrs/security/certs/jwkPrivateSet.txt");
    properties.put("rs.security.signature.algorithm", "RS256");
    properties.put(JwtConstants.JWT_TOKEN, token);
    WebClient.getConfig(client).getRequestContext().putAll(properties);

    Response response = client.get();
    assertNotEquals(response.getStatus(), 200);
}
 
Example #26
Source File: JWTAlgorithmTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void testBadHMACSignature() throws Exception {

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

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

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

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

    JwtToken token = new JwtToken(claims);

    Map<String, Object> properties = new HashMap<>();
    properties.put("rs.security.keystore.type", "jwk");
    properties.put("rs.security.keystore.alias", "HMACKey");
    properties.put("rs.security.keystore.file",
                   "org/apache/cxf/systest/jaxrs/security/certs/jwkPrivateSet.txt");
    properties.put(JwtConstants.JWT_TOKEN, token);
    WebClient.getConfig(client).getRequestContext().putAll(properties);

    Response response = client.post(new Book("book", 123L));
    assertNotEquals(response.getStatus(), 200);
}
 
Example #27
Source File: JWTAlgorithmTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void testHMACSignature() throws Exception {

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

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

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

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

    JwtToken token = new JwtToken(claims);

    Map<String, Object> properties = new HashMap<>();
    properties.put("rs.security.keystore.type", "jwk");
    properties.put("rs.security.keystore.alias", "HMAC512Key");
    properties.put("rs.security.keystore.file",
                   "org/apache/cxf/systest/jaxrs/security/certs/jwkPrivateSet.txt");
    properties.put(JwtConstants.JWT_TOKEN, token);
    WebClient.getConfig(client).getRequestContext().putAll(properties);

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

    Book returnedBook = response.readEntity(Book.class);
    assertEquals(returnedBook.getName(), "book");
    assertEquals(returnedBook.getId(), 123L);
}
 
Example #28
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 #29
Source File: JWTAlgorithmTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void testSignatureEllipticCurve() 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 + "/signedjwtec/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", "ECKey");
    properties.put("rs.security.keystore.file",
                   "org/apache/cxf/systest/jaxrs/security/certs/jwkPrivateSet.txt");
    properties.put("rs.security.signature.algorithm", "ES256");
    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 #30
Source File: JWTAlgorithmTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void testBadSigningKey() throws Exception {

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

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

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

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

    JwtToken token = new JwtToken(claims);

    Map<String, Object> properties = new HashMap<>();
    properties.put("rs.security.keystore.type", "jks");
    properties.put("rs.security.keystore.password", "password");
    properties.put("rs.security.key.password", "password");
    properties.put("rs.security.keystore.alias", "alice");
    properties.put("rs.security.keystore.file", "keys/alice.jks");
    properties.put("rs.security.signature.algorithm", "RS256");
    properties.put(JwtConstants.JWT_TOKEN, token);
    WebClient.getConfig(client).getRequestContext().putAll(properties);

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