Search in sources :

Example 11 with JwtToken

use of org.apache.cxf.rs.security.jose.jwt.JwtToken in project cxf by apache.

the class IdTokenReader method getIdJwtToken.

public JwtToken getIdJwtToken(String idJwtToken, Consumer client) {
    JwtToken jwt = getJwtToken(idJwtToken, client.getClientSecret());
    validateJwtClaims(jwt.getClaims(), client.getClientId(), true);
    return jwt;
}
Also used : JwtToken(org.apache.cxf.rs.security.jose.jwt.JwtToken)

Example 12 with JwtToken

use of org.apache.cxf.rs.security.jose.jwt.JwtToken in project cxf by apache.

the class JwsJwtCompactConsumer method getJwtToken.

public JwtToken getJwtToken() {
    if (token == null) {
        JwsHeaders theHeaders = super.getJwsHeaders();
        JwtClaims theClaims = new JwtClaims(getReader().fromJson(getDecodedJwsPayload()));
        token = new JwtToken(theHeaders, theClaims);
    }
    return token;
}
Also used : JwtToken(org.apache.cxf.rs.security.jose.jwt.JwtToken) JwtClaims(org.apache.cxf.rs.security.jose.jwt.JwtClaims)

Example 13 with JwtToken

use of org.apache.cxf.rs.security.jose.jwt.JwtToken in project cxf by apache.

the class JwtAuthenticationClientFilter method filter.

@Override
public void filter(ClientRequestContext requestContext) throws IOException {
    JwtToken jwt = getJwtToken(requestContext);
    if (jwt == null && super.isJweRequired()) {
        AuthorizationPolicy ap = JAXRSUtils.getCurrentMessage().getExchange().getEndpoint().getEndpointInfo().getExtensor(AuthorizationPolicy.class);
        if (ap != null && ap.getUserName() != null) {
            JwtClaims claims = new JwtClaims();
            claims.setSubject(ap.getUserName());
            claims.setClaim("password", ap.getPassword());
            claims.setIssuedAt(System.currentTimeMillis() / 1000L);
            jwt = new JwtToken(new JweHeaders(), claims);
        }
    }
    if (jwt == null) {
        throw new JoseException("JWT token is not available");
    }
    String data = super.processJwt(jwt);
    requestContext.getHeaders().putSingle(HttpHeaders.AUTHORIZATION, authScheme + " " + data);
}
Also used : JwtToken(org.apache.cxf.rs.security.jose.jwt.JwtToken) AuthorizationPolicy(org.apache.cxf.configuration.security.AuthorizationPolicy) JwtClaims(org.apache.cxf.rs.security.jose.jwt.JwtClaims) JoseException(org.apache.cxf.rs.security.jose.common.JoseException) JweHeaders(org.apache.cxf.rs.security.jose.jwe.JweHeaders)

Example 14 with JwtToken

use of org.apache.cxf.rs.security.jose.jwt.JwtToken in project cxf by apache.

the class JWTTokenValidator method validateToken.

/**
 * Validate a Token using the given TokenValidatorParameters.
 */
public TokenValidatorResponse validateToken(TokenValidatorParameters tokenParameters) {
    LOG.fine("Validating JWT Token");
    STSPropertiesMBean stsProperties = tokenParameters.getStsProperties();
    TokenValidatorResponse response = new TokenValidatorResponse();
    ReceivedToken validateTarget = tokenParameters.getToken();
    validateTarget.setState(STATE.INVALID);
    response.setToken(validateTarget);
    String token = ((Element) validateTarget.getToken()).getTextContent();
    if (token == null || "".equals(token)) {
        return response;
    }
    if (token.split("\\.").length != 3) {
        LOG.log(Level.WARNING, "JWT Token appears not to be signed. Validation has failed");
        return response;
    }
    JwsJwtCompactConsumer jwtConsumer = new JwsJwtCompactConsumer(token);
    JwtToken jwt = jwtConsumer.getJwtToken();
    // Verify the signature
    Properties verificationProperties = new Properties();
    Crypto signatureCrypto = stsProperties.getSignatureCrypto();
    String alias = stsProperties.getSignatureUsername();
    if (alias != null) {
        verificationProperties.put(JoseConstants.RSSEC_KEY_STORE_ALIAS, alias);
    }
    if (!(signatureCrypto instanceof Merlin)) {
        throw new STSException("Can't get the keystore", STSException.REQUEST_FAILED);
    }
    KeyStore keystore = ((Merlin) signatureCrypto).getKeyStore();
    verificationProperties.put(JoseConstants.RSSEC_KEY_STORE, keystore);
    JwsSignatureVerifier signatureVerifier = JwsUtils.loadSignatureVerifier(verificationProperties, jwt.getJwsHeaders());
    if (!jwtConsumer.verifySignatureWith(signatureVerifier)) {
        return response;
    }
    try {
        validateToken(jwt);
    } catch (RuntimeException ex) {
        LOG.log(Level.WARNING, "JWT token validation failed", ex);
        return response;
    }
    // Get the realm of the JWT Token
    if (realmCodec != null) {
        String tokenRealm = realmCodec.getRealmFromToken(jwt);
        response.setTokenRealm(tokenRealm);
    }
    if (isVerifiedWithAPublicKey(jwt)) {
        Principal principal = new SimplePrincipal(jwt.getClaims().getSubject());
        response.setPrincipal(principal);
        // Parse roles from the validated token
        if (roleParser != null) {
            Set<Principal> roles = roleParser.parseRolesFromToken(principal, null, jwt);
            response.setRoles(roles);
        }
    }
    validateTarget.setState(STATE.VALID);
    LOG.fine("JWT Token successfully validated");
    return response;
}
Also used : Element(org.w3c.dom.Element) STSException(org.apache.cxf.ws.security.sts.provider.STSException) Properties(java.util.Properties) KeyStore(java.security.KeyStore) JwtToken(org.apache.cxf.rs.security.jose.jwt.JwtToken) JwsSignatureVerifier(org.apache.cxf.rs.security.jose.jws.JwsSignatureVerifier) Crypto(org.apache.wss4j.common.crypto.Crypto) STSPropertiesMBean(org.apache.cxf.sts.STSPropertiesMBean) TokenValidatorResponse(org.apache.cxf.sts.token.validator.TokenValidatorResponse) JwsJwtCompactConsumer(org.apache.cxf.rs.security.jose.jws.JwsJwtCompactConsumer) ReceivedToken(org.apache.cxf.sts.request.ReceivedToken) Merlin(org.apache.wss4j.common.crypto.Merlin) SimplePrincipal(org.apache.cxf.common.security.SimplePrincipal) Principal(java.security.Principal) SimplePrincipal(org.apache.cxf.common.security.SimplePrincipal)

Example 15 with JwtToken

use of org.apache.cxf.rs.security.jose.jwt.JwtToken in project cxf by apache.

the class IssueJWTClaimsUnitTest method runIssueJWTTokenOnBehalfOfSaml2DifferentRealmFederateIdentity.

private void runIssueJWTTokenOnBehalfOfSaml2DifferentRealmFederateIdentity(boolean useGlobalIdentityMapper) throws WSSecurityException {
    TokenIssueOperation issueOperation = new TokenIssueOperation();
    Map<String, RealmProperties> realms = createSamlRealms();
    // Add Token Provider
    List<TokenProvider> providerList = new ArrayList<>();
    JWTTokenProvider tokenProvider = new JWTTokenProvider();
    tokenProvider.setRealmMap(realms);
    providerList.add(tokenProvider);
    issueOperation.setTokenProviders(providerList);
    TokenDelegationHandler delegationHandler = new SAMLDelegationHandler();
    issueOperation.setDelegationHandlers(Collections.singletonList(delegationHandler));
    // Add Token Validator
    List<TokenValidator> validatorList = new ArrayList<>();
    SAMLTokenValidator samlTokenValidator = new SAMLTokenValidator();
    samlTokenValidator.setSamlRealmCodec(new IssuerSAMLRealmCodec());
    validatorList.add(samlTokenValidator);
    issueOperation.setTokenValidators(validatorList);
    addService(issueOperation);
    // Add Relationship list
    List<Relationship> relationshipList = new ArrayList<>();
    Relationship rs = createRelationship();
    rs.setType(Relationship.FED_TYPE_IDENTITY);
    rs.setIdentityMapper(new CustomIdentityMapper());
    relationshipList.add(rs);
    // Add STSProperties object
    Crypto crypto = CryptoFactory.getInstance(getEncryptionProperties());
    STSPropertiesMBean stsProperties = createSTSPropertiesMBean(crypto);
    stsProperties.setRealmParser(new CustomRealmParser());
    if (useGlobalIdentityMapper) {
        stsProperties.setIdentityMapper(new CustomIdentityMapper());
    } else {
        stsProperties.setRelationships(relationshipList);
    }
    issueOperation.setStsProperties(stsProperties);
    // Set the ClaimsManager
    ClaimsManager claimsManager = new ClaimsManager();
    claimsManager.setClaimHandlers(Collections.singletonList((ClaimsHandler) new CustomClaimsHandler()));
    issueOperation.setClaimsManager(claimsManager);
    // Mock up a request
    RequestSecurityTokenType request = new RequestSecurityTokenType();
    JAXBElement<String> tokenType = new JAXBElement<String>(QNameConstants.TOKEN_TYPE, String.class, JWTTokenProvider.JWT_TOKEN_TYPE);
    request.getAny().add(tokenType);
    // Add a ClaimsType
    ClaimsType claimsType = new ClaimsType();
    claimsType.setDialect(STSConstants.IDT_NS_05_05);
    Element claimType = createClaimsType(DOMUtils.getEmptyDocument());
    claimsType.getAny().add(claimType);
    JAXBElement<ClaimsType> claimsTypeJaxb = new JAXBElement<ClaimsType>(QNameConstants.CLAIMS, ClaimsType.class, claimsType);
    request.getAny().add(claimsTypeJaxb);
    // request.getAny().add(createAppliesToElement("http://dummy-service.com/dummy"));
    // create a SAML Token via the SAMLTokenProvider which contains claims
    CallbackHandler callbackHandler = new PasswordCallbackHandler();
    Element samlToken = createSAMLAssertion(WSS4JConstants.WSS_SAML2_TOKEN_TYPE, crypto, "mystskey", callbackHandler, realms);
    Document docToken = samlToken.getOwnerDocument();
    samlToken = (Element) docToken.appendChild(samlToken);
    String samlString = DOM2Writer.nodeToString(samlToken);
    assertTrue(samlString.contains("AttributeStatement"));
    assertTrue(samlString.contains("alice"));
    assertTrue(samlString.contains("doe"));
    assertTrue(samlString.contains(SAML2Constants.CONF_BEARER));
    // add SAML token as On-Behalf-Of element
    OnBehalfOfType onbehalfof = new OnBehalfOfType();
    onbehalfof.setAny(samlToken);
    JAXBElement<OnBehalfOfType> onbehalfofType = new JAXBElement<OnBehalfOfType>(QNameConstants.ON_BEHALF_OF, OnBehalfOfType.class, onbehalfof);
    request.getAny().add(onbehalfofType);
    // Mock up message context
    MessageImpl msg = new MessageImpl();
    WrappedMessageContext msgCtx = new WrappedMessageContext(msg);
    msgCtx.put("url", "https");
    List<RequestSecurityTokenResponseType> securityTokenResponseList = issueToken(issueOperation, request, new CustomTokenPrincipal("alice"), msgCtx);
    // Test the generated token.
    Element token = null;
    for (Object tokenObject : securityTokenResponseList.get(0).getAny()) {
        if (tokenObject instanceof JAXBElement<?> && REQUESTED_SECURITY_TOKEN.equals(((JAXBElement<?>) tokenObject).getName())) {
            RequestedSecurityTokenType rstType = (RequestedSecurityTokenType) ((JAXBElement<?>) tokenObject).getValue();
            token = (Element) rstType.getAny();
            break;
        }
    }
    assertNotNull(token);
    // Validate the token
    JwsJwtCompactConsumer jwtConsumer = new JwsJwtCompactConsumer(token.getTextContent());
    JwtToken jwt = jwtConsumer.getJwtToken();
    // subject changed (to uppercase)
    Assert.assertEquals("ALICE", jwt.getClaim(JwtConstants.CLAIM_SUBJECT));
    // claim unchanged but requested
    assertEquals(jwt.getClaim(ClaimTypes.LASTNAME.toString()), "doe");
}
Also used : CallbackHandler(javax.security.auth.callback.CallbackHandler) PasswordCallbackHandler(org.apache.cxf.sts.common.PasswordCallbackHandler) RequestSecurityTokenType(org.apache.cxf.ws.security.sts.provider.model.RequestSecurityTokenType) JAXBElement(javax.xml.bind.JAXBElement) Element(org.w3c.dom.Element) ArrayList(java.util.ArrayList) RequestSecurityTokenResponseType(org.apache.cxf.ws.security.sts.provider.model.RequestSecurityTokenResponseType) RequestedSecurityTokenType(org.apache.cxf.ws.security.sts.provider.model.RequestedSecurityTokenType) Document(org.w3c.dom.Document) CustomClaimsHandler(org.apache.cxf.sts.common.CustomClaimsHandler) CustomTokenPrincipal(org.apache.wss4j.common.principal.CustomTokenPrincipal) TokenProvider(org.apache.cxf.sts.token.provider.TokenProvider) JWTTokenProvider(org.apache.cxf.sts.token.provider.jwt.JWTTokenProvider) SAMLTokenProvider(org.apache.cxf.sts.token.provider.SAMLTokenProvider) TokenValidator(org.apache.cxf.sts.token.validator.TokenValidator) SAMLTokenValidator(org.apache.cxf.sts.token.validator.SAMLTokenValidator) IssuerSAMLRealmCodec(org.apache.cxf.sts.token.validator.IssuerSAMLRealmCodec) ClaimsManager(org.apache.cxf.sts.claims.ClaimsManager) PasswordCallbackHandler(org.apache.cxf.sts.common.PasswordCallbackHandler) JwsJwtCompactConsumer(org.apache.cxf.rs.security.jose.jws.JwsJwtCompactConsumer) TokenDelegationHandler(org.apache.cxf.sts.token.delegation.TokenDelegationHandler) RealmProperties(org.apache.cxf.sts.token.realm.RealmProperties) JWTTokenProvider(org.apache.cxf.sts.token.provider.jwt.JWTTokenProvider) ClaimsHandler(org.apache.cxf.sts.claims.ClaimsHandler) CustomClaimsHandler(org.apache.cxf.sts.common.CustomClaimsHandler) ClaimsType(org.apache.cxf.ws.security.sts.provider.model.ClaimsType) SAMLDelegationHandler(org.apache.cxf.sts.token.delegation.SAMLDelegationHandler) JAXBElement(javax.xml.bind.JAXBElement) JwtToken(org.apache.cxf.rs.security.jose.jwt.JwtToken) OnBehalfOfType(org.apache.cxf.ws.security.sts.provider.model.OnBehalfOfType) Crypto(org.apache.wss4j.common.crypto.Crypto) STSPropertiesMBean(org.apache.cxf.sts.STSPropertiesMBean) Relationship(org.apache.cxf.sts.token.realm.Relationship) WrappedMessageContext(org.apache.cxf.jaxws.context.WrappedMessageContext) SAMLTokenValidator(org.apache.cxf.sts.token.validator.SAMLTokenValidator) MessageImpl(org.apache.cxf.message.MessageImpl)

Aggregations

JwtToken (org.apache.cxf.rs.security.jose.jwt.JwtToken)102 JwsJwtCompactConsumer (org.apache.cxf.rs.security.jose.jws.JwsJwtCompactConsumer)47 WebClient (org.apache.cxf.jaxrs.client.WebClient)42 JwtClaims (org.apache.cxf.rs.security.jose.jwt.JwtClaims)42 URL (java.net.URL)41 ArrayList (java.util.ArrayList)37 Response (javax.ws.rs.core.Response)35 JWTTokenProvider (org.apache.cxf.sts.token.provider.jwt.JWTTokenProvider)33 HashMap (java.util.HashMap)31 JacksonJsonProvider (com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider)28 JwtAuthenticationClientFilter (org.apache.cxf.rs.security.jose.jaxrs.JwtAuthenticationClientFilter)28 Book (org.apache.cxf.systest.jaxrs.security.Book)28 JAXBElement (javax.xml.bind.JAXBElement)13 Crypto (org.apache.wss4j.common.crypto.Crypto)13 Element (org.w3c.dom.Element)12 ClaimsHandler (org.apache.cxf.sts.claims.ClaimsHandler)10 ClaimsManager (org.apache.cxf.sts.claims.ClaimsManager)10 CustomClaimsHandler (org.apache.cxf.sts.common.CustomClaimsHandler)10 CustomTokenPrincipal (org.apache.wss4j.common.principal.CustomTokenPrincipal)10 TokenProvider (org.apache.cxf.sts.token.provider.TokenProvider)9