Search in sources :

Example 1 with JwsJwtCompactConsumer

use of org.apache.cxf.rs.security.jose.jws.JwsJwtCompactConsumer in project cxf by apache.

the class JwtBearerGrantHandler method createAccessToken.

@Override
public ServerAccessToken createAccessToken(Client client, MultivaluedMap<String, String> params) throws OAuthServiceException {
    String assertion = params.getFirst(Constants.CLIENT_GRANT_ASSERTION_PARAM);
    if (assertion == null) {
        throw new OAuthServiceException(OAuthConstants.INVALID_GRANT);
    }
    try {
        JwsJwtCompactConsumer jwsReader = getJwsReader(assertion);
        JwtToken jwtToken = jwsReader.getJwtToken();
        validateSignature(new JwsHeaders(jwtToken.getJwsHeaders()), jwsReader.getUnsignedEncodedSequence(), jwsReader.getDecodedSignature());
        validateClaims(client, jwtToken.getClaims());
        UserSubject grantSubject = new UserSubject(jwtToken.getClaims().getSubject());
        return doCreateAccessToken(client, grantSubject, Constants.JWT_BEARER_GRANT, OAuthUtils.parseScope(params.getFirst(OAuthConstants.SCOPE)));
    } catch (OAuthServiceException ex) {
        throw ex;
    } catch (Exception ex) {
        throw new OAuthServiceException(OAuthConstants.INVALID_GRANT, ex);
    }
}
Also used : JwtToken(org.apache.cxf.rs.security.jose.jwt.JwtToken) JwsHeaders(org.apache.cxf.rs.security.jose.jws.JwsHeaders) UserSubject(org.apache.cxf.rs.security.oauth2.common.UserSubject) OAuthServiceException(org.apache.cxf.rs.security.oauth2.provider.OAuthServiceException) JwsJwtCompactConsumer(org.apache.cxf.rs.security.jose.jws.JwsJwtCompactConsumer) OAuthServiceException(org.apache.cxf.rs.security.oauth2.provider.OAuthServiceException)

Example 2 with JwsJwtCompactConsumer

use of org.apache.cxf.rs.security.jose.jws.JwsJwtCompactConsumer in project cxf by apache.

the class JoseJwtConsumer method getJwtToken.

public JwtToken getJwtToken(String wrappedJwtToken, JweDecryptionProvider theDecryptor, JwsSignatureVerifier theSigVerifier) {
    super.checkProcessRequirements();
    JweHeaders jweHeaders = new JweHeaders();
    if (isJweRequired()) {
        JweJwtCompactConsumer jwtConsumer = new JweJwtCompactConsumer(wrappedJwtToken);
        if (theDecryptor == null) {
            theDecryptor = getInitializedDecryptionProvider(jwtConsumer.getHeaders());
        }
        if (theDecryptor == null) {
            throw new JwtException("Unable to decrypt JWT");
        }
        if (!isJwsRequired()) {
            return jwtConsumer.decryptWith(theDecryptor);
        }
        JweDecryptionOutput decOutput = theDecryptor.decrypt(wrappedJwtToken);
        wrappedJwtToken = decOutput.getContentText();
        jweHeaders = decOutput.getHeaders();
    }
    JwsJwtCompactConsumer jwtConsumer = new JwsJwtCompactConsumer(wrappedJwtToken);
    JwtToken jwt = jwtConsumer.getJwtToken();
    // Store the encryption headers as well
    jwt = new JwtToken(jwt.getJwsHeaders(), jweHeaders, jwt.getClaims());
    if (isJwsRequired()) {
        if (theSigVerifier == null) {
            theSigVerifier = getInitializedSignatureVerifier(jwt);
        }
        if (theSigVerifier == null) {
            throw new JwtException("Unable to validate JWT");
        }
        if (!jwtConsumer.verifySignatureWith(theSigVerifier)) {
            throw new JwtException("Invalid Signature");
        }
    }
    validateToken(jwt);
    return jwt;
}
Also used : JweDecryptionOutput(org.apache.cxf.rs.security.jose.jwe.JweDecryptionOutput) JwsJwtCompactConsumer(org.apache.cxf.rs.security.jose.jws.JwsJwtCompactConsumer) JweJwtCompactConsumer(org.apache.cxf.rs.security.jose.jwe.JweJwtCompactConsumer) JweHeaders(org.apache.cxf.rs.security.jose.jwe.JweHeaders)

Example 3 with JwsJwtCompactConsumer

use of org.apache.cxf.rs.security.jose.jws.JwsJwtCompactConsumer 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 4 with JwsJwtCompactConsumer

use of org.apache.cxf.rs.security.jose.jws.JwsJwtCompactConsumer 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)

Example 5 with JwsJwtCompactConsumer

use of org.apache.cxf.rs.security.jose.jws.JwsJwtCompactConsumer in project cxf by apache.

the class IssueJWTClaimsUnitTest method testIssueJaxbJWTToken.

/**
 * Test to successfully issue a JWT token. The claims information is included as a
 * JAXB Element under RequestSecurityToken, rather than as a child of SecondaryParameters.
 */
@org.junit.Test
public void testIssueJaxbJWTToken() throws Exception {
    TokenIssueOperation issueOperation = new TokenIssueOperation();
    // Add Token Provider
    List<TokenProvider> providerList = new ArrayList<>();
    providerList.add(new JWTTokenProvider());
    issueOperation.setTokenProviders(providerList);
    addService(issueOperation);
    addSTSProperties(issueOperation);
    // Set the ClaimsManager
    ClaimsManager claimsManager = new ClaimsManager();
    ClaimsHandler claimsHandler = new CustomClaimsHandler();
    claimsManager.setClaimHandlers(Collections.singletonList(claimsHandler));
    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);
    Document doc = DOMUtils.getEmptyDocument();
    Element claimType = createClaimsType(doc);
    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"));
    Map<String, Object> messageContext = setupMessageContext();
    List<RequestSecurityTokenResponseType> securityTokenResponse = issueToken(issueOperation, request, new CustomTokenPrincipal("alice"), messageContext);
    // Test the generated token.
    Element token = null;
    for (Object tokenObject : securityTokenResponse.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();
    Assert.assertEquals("alice", jwt.getClaim(JwtConstants.CLAIM_SUBJECT));
    assertEquals(jwt.getClaim(ClaimTypes.LASTNAME.toString()), "doe");
}
Also used : 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) ClaimsManager(org.apache.cxf.sts.claims.ClaimsManager) JwsJwtCompactConsumer(org.apache.cxf.rs.security.jose.jws.JwsJwtCompactConsumer) 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) JAXBElement(javax.xml.bind.JAXBElement) JwtToken(org.apache.cxf.rs.security.jose.jwt.JwtToken)

Aggregations

JwsJwtCompactConsumer (org.apache.cxf.rs.security.jose.jws.JwsJwtCompactConsumer)76 JwtToken (org.apache.cxf.rs.security.jose.jwt.JwtToken)61 JWTTokenProvider (org.apache.cxf.sts.token.provider.jwt.JWTTokenProvider)33 Response (javax.ws.rs.core.Response)20 WebClient (org.apache.cxf.jaxrs.client.WebClient)18 URL (java.net.URL)17 Element (org.w3c.dom.Element)15 JAXBElement (javax.xml.bind.JAXBElement)13 Crypto (org.apache.wss4j.common.crypto.Crypto)13 KeyStore (java.security.KeyStore)12 X509Certificate (java.security.cert.X509Certificate)12 ArrayList (java.util.ArrayList)10 Date (java.util.Date)10 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 Document (org.w3c.dom.Document)9 Certificate (java.security.cert.Certificate)8