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

The following examples show how to use org.apache.cxf.rs.security.jose.jwt.JwtClaims#setClaim() . 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: 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 2
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 3
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 4
Source File: DefaultJWTClaimsProvider.java    From cxf with Apache License 2.0 5 votes vote down vote up
protected void handleActAs(
    JWTClaimsProviderParameters jwtClaimsProviderParameters, JwtClaims claims
) {
    TokenProviderParameters providerParameters = jwtClaimsProviderParameters.getProviderParameters();

    if (providerParameters.getTokenRequirements().getActAs() != null) {
        ReceivedToken receivedToken = providerParameters.getTokenRequirements().getActAs();
        if (receivedToken.getState().equals(STATE.VALID)) {
            claims.setClaim("ActAs", receivedToken.getPrincipal().getName());
        }
    }
}
 
Example 5
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 6
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 7
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 8
Source File: BackChannelLogoutHandler.java    From cxf-fediz with Apache License 2.0 5 votes vote down vote up
private void submitBackChannelLogoutRequest(final Client client, final OidcUserSubject subject,
        final IdToken idTokenHint, final String uri) {
    // Application context is expected to contain HttpConduit HTTPS configuration
    final WebClient wc = WebClient.create(uri);
    IdToken idToken = idTokenHint != null ? idTokenHint : subject.getIdToken(); 
    JwtClaims claims = new JwtClaims();
    claims.setIssuer(idToken.getIssuer());
    claims.setSubject(idToken.getSubject());
    claims.setAudience(client.getClientId());
    claims.setIssuedAt(System.currentTimeMillis() / 1000);
    claims.setTokenId(Base64UrlUtility.encode(CryptoUtils.generateSecureRandomBytes(16)));
    claims.setClaim(EVENTS_PROPERTY, 
            Collections.singletonMap(BACK_CHANNEL_LOGOUT_EVENT, Collections.emptyMap()));
    if (idToken.getName() != null) {
        claims.setClaim(IdToken.NAME_CLAIM, idToken.getName());    
    }
    
    final String logoutToken = super.processJwt(new JwtToken(claims));
    executorService.submit(new Runnable() {

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