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);
}
}
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;
}
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;
}
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");
}
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");
}
Aggregations