use of org.apache.cxf.sts.token.validator.TokenValidatorResponse in project ddf by codice.
the class TestUsernameTokenValidator method testValidateBadTokenNoTokenStore.
@Test
public void testValidateBadTokenNoTokenStore() {
UsernameTokenValidator usernameTokenValidator = getUsernameTokenValidator(new XmlParser(), meanValidator);
usernameTokenValidator.addRealm(null);
TokenValidatorParameters tokenValidatorParameters = mock(TokenValidatorParameters.class);
STSPropertiesMBean stsPropertiesMBean = mock(STSPropertiesMBean.class);
when(stsPropertiesMBean.getSignatureCrypto()).thenReturn(mock(Crypto.class));
when(tokenValidatorParameters.getStsProperties()).thenReturn(stsPropertiesMBean);
ReceivedToken receivedToken = mock(ReceivedToken.class);
doCallRealMethod().when(receivedToken).setState(any(ReceivedToken.STATE.class));
doCallRealMethod().when(receivedToken).getState();
when(receivedToken.isUsernameToken()).thenReturn(true);
when(tokenValidatorParameters.getToken()).thenReturn(receivedToken);
Set<Class<?>> classes = new HashSet<>();
classes.add(ObjectFactory.class);
classes.add(org.apache.cxf.ws.security.sts.provider.model.wstrust14.ObjectFactory.class);
JAXBContextCache.CachedContextAndSchemas cache = null;
try {
cache = JAXBContextCache.getCachedContextAndSchemas(classes, null, null, null, false);
} catch (JAXBException e) {
fail(e.getMessage());
}
JAXBContext jaxbContext = cache.getContext();
Unmarshaller unmarshaller = null;
try {
if (jaxbContext != null) {
unmarshaller = jaxbContext.createUnmarshaller();
}
} catch (JAXBException e) {
fail(e.getMessage());
}
JAXBElement<?> token = null;
if (unmarshaller != null) {
try {
token = (JAXBElement<?>) unmarshaller.unmarshal(this.getClass().getResourceAsStream("/user-no-password.xml"));
} catch (JAXBException e) {
fail(e.getMessage());
}
}
when(receivedToken.getToken()).thenReturn(token.getValue());
TokenValidatorResponse tokenValidatorResponse = usernameTokenValidator.validateToken(tokenValidatorParameters);
assertEquals(ReceivedToken.STATE.INVALID, tokenValidatorResponse.getToken().getState());
verify(failedLoginDelayer, times(1)).delay(anyString());
}
use of org.apache.cxf.sts.token.validator.TokenValidatorResponse in project ddf by codice.
the class TestUsernameTokenValidator method testValidateBadToken.
@Test
public void testValidateBadToken() {
UsernameTokenValidator usernameTokenValidator = getUsernameTokenValidator(new XmlParser(), meanValidator);
usernameTokenValidator.addRealm(null);
TokenValidatorParameters tokenValidatorParameters = mock(TokenValidatorParameters.class);
STSPropertiesMBean stsPropertiesMBean = mock(STSPropertiesMBean.class);
when(stsPropertiesMBean.getSignatureCrypto()).thenReturn(mock(Crypto.class));
when(tokenValidatorParameters.getStsProperties()).thenReturn(stsPropertiesMBean);
ReceivedToken receivedToken = mock(ReceivedToken.class);
doCallRealMethod().when(receivedToken).setState(any(ReceivedToken.STATE.class));
doCallRealMethod().when(receivedToken).getState();
when(receivedToken.isUsernameToken()).thenReturn(true);
when(tokenValidatorParameters.getToken()).thenReturn(receivedToken);
Set<Class<?>> classes = new HashSet<>();
classes.add(ObjectFactory.class);
classes.add(org.apache.cxf.ws.security.sts.provider.model.wstrust14.ObjectFactory.class);
JAXBContextCache.CachedContextAndSchemas cache = null;
try {
cache = JAXBContextCache.getCachedContextAndSchemas(classes, null, null, null, false);
} catch (JAXBException e) {
fail(e.getMessage());
}
JAXBContext jaxbContext = cache.getContext();
Unmarshaller unmarshaller = null;
try {
if (jaxbContext != null) {
unmarshaller = jaxbContext.createUnmarshaller();
}
} catch (JAXBException e) {
fail(e.getMessage());
}
JAXBElement<?> token = null;
if (unmarshaller != null) {
try {
token = (JAXBElement<?>) unmarshaller.unmarshal(this.getClass().getResourceAsStream("/user.xml"));
} catch (JAXBException e) {
fail(e.getMessage());
}
}
when(receivedToken.getToken()).thenReturn(token.getValue());
TokenValidatorResponse tokenValidatorResponse = usernameTokenValidator.validateToken(tokenValidatorParameters);
assertEquals(ReceivedToken.STATE.INVALID, tokenValidatorResponse.getToken().getState());
verify(failedLoginDelayer, times(1)).delay(anyString());
}
use of org.apache.cxf.sts.token.validator.TokenValidatorResponse in project cxf by apache.
the class TokenRenewOperation method renew.
public RequestSecurityTokenResponseType renew(RequestSecurityTokenType request, Principal principal, Map<String, Object> messageContext) {
long start = System.currentTimeMillis();
TokenRenewerParameters renewerParameters = new TokenRenewerParameters();
try {
RequestRequirements requestRequirements = parseRequest(request, messageContext);
KeyRequirements keyRequirements = requestRequirements.getKeyRequirements();
TokenRequirements tokenRequirements = requestRequirements.getTokenRequirements();
renewerParameters.setStsProperties(stsProperties);
renewerParameters.setPrincipal(principal);
renewerParameters.setMessageContext(messageContext);
renewerParameters.setTokenStore(getTokenStore());
renewerParameters.setKeyRequirements(keyRequirements);
renewerParameters.setTokenRequirements(tokenRequirements);
ReceivedToken renewTarget = tokenRequirements.getRenewTarget();
if (renewTarget == null || renewTarget.getToken() == null) {
throw new STSException("No element presented for renewal", STSException.INVALID_REQUEST);
}
renewerParameters.setToken(renewTarget);
if (tokenRequirements.getTokenType() == null) {
LOG.fine("Received TokenType is null");
}
// Get the realm of the request
String realm = null;
if (stsProperties.getRealmParser() != null) {
RealmParser realmParser = stsProperties.getRealmParser();
realm = realmParser.parseRealm(messageContext);
}
renewerParameters.setRealm(realm);
// Validate the request
TokenValidatorResponse tokenResponse = validateReceivedToken(principal, messageContext, realm, tokenRequirements, renewTarget);
if (tokenResponse == null) {
LOG.fine("No Token Validator has been found that can handle this token");
renewTarget.setState(STATE.INVALID);
throw new STSException("No Token Validator has been found that can handle this token" + tokenRequirements.getTokenType(), STSException.REQUEST_FAILED);
}
// Reject an invalid token
if (tokenResponse.getToken().getState() != STATE.EXPIRED && tokenResponse.getToken().getState() != STATE.VALID) {
LOG.fine("The token is not valid or expired, and so it cannot be renewed");
throw new STSException("No Token Validator has been found that can handle this token" + tokenRequirements.getTokenType(), STSException.REQUEST_FAILED);
}
//
// Renew the token
//
TokenRenewerResponse tokenRenewerResponse = null;
renewerParameters = createTokenRenewerParameters(requestRequirements, principal, messageContext);
Map<String, Object> additionalProperties = tokenResponse.getAdditionalProperties();
if (additionalProperties != null) {
renewerParameters.setAdditionalProperties(additionalProperties);
}
renewerParameters.setRealm(tokenResponse.getTokenRealm());
renewerParameters.setToken(tokenResponse.getToken());
realm = tokenResponse.getTokenRealm();
for (TokenRenewer tokenRenewer : tokenRenewers) {
boolean canHandle = false;
if (realm == null) {
canHandle = tokenRenewer.canHandleToken(tokenResponse.getToken());
} else {
canHandle = tokenRenewer.canHandleToken(tokenResponse.getToken(), realm);
}
if (canHandle) {
try {
tokenRenewerResponse = tokenRenewer.renewToken(renewerParameters);
} catch (STSException ex) {
LOG.log(Level.WARNING, "", ex);
throw ex;
} catch (RuntimeException ex) {
LOG.log(Level.WARNING, "", ex);
throw new STSException("Error in providing a token", ex, STSException.REQUEST_FAILED);
}
break;
}
}
if (tokenRenewerResponse == null || tokenRenewerResponse.getToken() == null) {
LOG.fine("No Token Renewer has been found that can handle this token");
throw new STSException("No token renewer found for requested token type", STSException.REQUEST_FAILED);
}
// prepare response
try {
EncryptionProperties encryptionProperties = renewerParameters.getEncryptionProperties();
RequestSecurityTokenResponseType response = createResponse(encryptionProperties, tokenRenewerResponse, tokenRequirements, keyRequirements);
STSRenewSuccessEvent event = new STSRenewSuccessEvent(renewerParameters, System.currentTimeMillis() - start);
publishEvent(event);
return response;
} catch (Throwable ex) {
LOG.log(Level.WARNING, "", ex);
throw new STSException("Error in creating the response", ex, STSException.REQUEST_FAILED);
}
} catch (RuntimeException ex) {
STSRenewFailureEvent event = new STSRenewFailureEvent(renewerParameters, System.currentTimeMillis() - start, ex);
publishEvent(event);
throw ex;
}
}
use of org.apache.cxf.sts.token.validator.TokenValidatorResponse in project cxf by apache.
the class TokenValidateOperation method validate.
public RequestSecurityTokenResponseType validate(RequestSecurityTokenType request, Principal principal, Map<String, Object> messageContext) {
long start = System.currentTimeMillis();
TokenValidatorParameters validatorParameters = new TokenValidatorParameters();
try {
RequestRequirements requestRequirements = parseRequest(request, messageContext);
TokenRequirements tokenRequirements = requestRequirements.getTokenRequirements();
validatorParameters.setStsProperties(stsProperties);
validatorParameters.setPrincipal(principal);
validatorParameters.setMessageContext(messageContext);
validatorParameters.setTokenStore(getTokenStore());
// validatorParameters.setKeyRequirements(keyRequirements);
validatorParameters.setTokenRequirements(tokenRequirements);
ReceivedToken validateTarget = tokenRequirements.getValidateTarget();
if (validateTarget == null || validateTarget.getToken() == null) {
throw new STSException("No element presented for validation", STSException.INVALID_REQUEST);
}
validatorParameters.setToken(validateTarget);
if (tokenRequirements.getTokenType() == null) {
tokenRequirements.setTokenType(STSConstants.STATUS);
LOG.fine("Received TokenType is null, falling back to default token type: " + STSConstants.STATUS);
}
// Get the realm of the request
String realm = null;
if (stsProperties.getRealmParser() != null) {
RealmParser realmParser = stsProperties.getRealmParser();
realm = realmParser.parseRealm(messageContext);
}
validatorParameters.setRealm(realm);
TokenValidatorResponse tokenResponse = validateReceivedToken(principal, messageContext, realm, tokenRequirements, validateTarget);
if (tokenResponse == null) {
LOG.fine("No Token Validator has been found that can handle this token");
tokenResponse = new TokenValidatorResponse();
validateTarget.setState(STATE.INVALID);
tokenResponse.setToken(validateTarget);
}
//
// Create a new token (if requested)
//
TokenProviderResponse tokenProviderResponse = null;
String tokenType = tokenRequirements.getTokenType();
if (tokenResponse.getToken().getState() == STATE.VALID && !STSConstants.STATUS.equals(tokenType)) {
TokenProviderParameters providerParameters = createTokenProviderParameters(requestRequirements, principal, messageContext);
processValidToken(providerParameters, validateTarget, tokenResponse);
// Check if the requested claims can be handled by the configured claim handlers
providerParameters.setClaimsManager(claimsManager);
Map<String, Object> additionalProperties = tokenResponse.getAdditionalProperties();
if (additionalProperties != null) {
providerParameters.setAdditionalProperties(additionalProperties);
}
realm = providerParameters.getRealm();
for (TokenProvider tokenProvider : tokenProviders) {
boolean canHandle = false;
if (realm == null) {
canHandle = tokenProvider.canHandleToken(tokenType);
} else {
canHandle = tokenProvider.canHandleToken(tokenType, realm);
}
if (canHandle) {
try {
tokenProviderResponse = tokenProvider.createToken(providerParameters);
} catch (STSException ex) {
LOG.log(Level.WARNING, "", ex);
throw ex;
} catch (RuntimeException ex) {
LOG.log(Level.WARNING, "", ex);
throw new STSException("Error in providing a token", ex, STSException.REQUEST_FAILED);
}
break;
}
}
if (tokenProviderResponse == null || tokenProviderResponse.getToken() == null) {
LOG.fine("No Token Provider has been found that can handle this token");
throw new STSException("No token provider found for requested token type: " + tokenType, STSException.REQUEST_FAILED);
}
}
// prepare response
try {
RequestSecurityTokenResponseType response = createResponse(tokenResponse, tokenProviderResponse, tokenRequirements);
STSValidateSuccessEvent event = new STSValidateSuccessEvent(validatorParameters, System.currentTimeMillis() - start);
publishEvent(event);
return response;
} catch (Throwable ex) {
LOG.log(Level.WARNING, "", ex);
throw new STSException("Error in creating the response", ex, STSException.REQUEST_FAILED);
}
} catch (RuntimeException ex) {
STSValidateFailureEvent event = new STSValidateFailureEvent(validatorParameters, System.currentTimeMillis() - start, ex);
publishEvent(event);
throw ex;
}
}
use of org.apache.cxf.sts.token.validator.TokenValidatorResponse 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;
}
Aggregations