use of org.pac4j.saml.exceptions.SAMLException in project pac4j by pac4j.
the class SAML2DefaultResponseValidator method validate.
/**
* Validates the SAML protocol response and the SAML SSO response.
* The method decrypt encrypted assertions if any.
*
* @param context the context
*/
@Override
public Credentials validate(final SAML2MessageContext context) {
final SAMLObject message = context.getMessage();
if (!(message instanceof Response)) {
throw new SAMLException("Response instance is an unsupported type");
}
final Response response = (Response) message;
final SignatureTrustEngine engine = this.signatureTrustEngineProvider.build();
validateSamlProtocolResponse(response, context, engine);
if (decrypter != null) {
decryptEncryptedAssertions(response, decrypter);
}
validateSamlSSOResponse(response, context, engine, decrypter);
return buildSAML2Credentials(context);
}
use of org.pac4j.saml.exceptions.SAMLException in project pac4j by pac4j.
the class SAML2LogoutResponseValidator method validateSamlProtocolResponse.
/**
* Validates the SAML protocol response:
* - IssueInstant
* - Issuer
* - StatusCode
* - Signature
*
* @param response the response
* @param context the context
* @param engine the engine
*/
protected final void validateSamlProtocolResponse(final Response response, final SAML2MessageContext context, final SignatureTrustEngine engine) {
if (!StatusCode.SUCCESS.equals(response.getStatus().getStatusCode().getValue())) {
String status = response.getStatus().getStatusCode().getValue();
if (response.getStatus().getStatusMessage() != null) {
status += " / " + response.getStatus().getStatusMessage().getMessage();
}
throw new SAMLException("Logout response is not success ; actual " + status);
}
if (response.getSignature() != null) {
final String entityId = context.getSAMLPeerEntityContext().getEntityId();
validateSignature(response.getSignature(), entityId, engine);
context.getSAMLPeerEntityContext().setAuthenticated(true);
}
if (!isIssueInstantValid(response.getIssueInstant())) {
throw new SAMLIssueInstantException("Response issue instant is too old or in the future");
}
final SAMLMessageStorage messageStorage = context.getSAMLMessageStorage();
if (messageStorage != null && response.getInResponseTo() != null) {
final XMLObject xmlObject = messageStorage.retrieveMessage(response.getInResponseTo());
if (xmlObject == null) {
throw new SAMLInResponseToMismatchException("InResponseToField of the Response doesn't correspond to sent message " + response.getInResponseTo());
} else if (!(xmlObject instanceof LogoutRequest)) {
throw new SAMLInResponseToMismatchException("Sent request was of different type than the expected LogoutRequest " + response.getInResponseTo());
}
}
verifyEndpoint(context.getSAMLEndpointContext().getEndpoint(), response.getDestination());
if (response.getIssuer() != null) {
validateIssuer(response.getIssuer(), context);
}
}
use of org.pac4j.saml.exceptions.SAMLException in project pac4j by pac4j.
the class SAML2WebSSOMessageSender method sendMessage.
@Override
public void sendMessage(final SAML2MessageContext context, final AuthnRequest authnRequest, final Object relayState) {
final SPSSODescriptor spDescriptor = context.getSPSSODescriptor();
final IDPSSODescriptor idpssoDescriptor = context.getIDPSSODescriptor();
final SingleSignOnService ssoService = context.getIDPSingleSignOnService(destinationBindingType);
final AssertionConsumerService acsService = context.getSPAssertionConsumerService();
final MessageEncoder encoder = getMessageEncoder(context);
final SAML2MessageContext outboundContext = new SAML2MessageContext(context);
outboundContext.getProfileRequestContext().setProfileId(context.getProfileRequestContext().getProfileId());
outboundContext.getProfileRequestContext().setInboundMessageContext(context.getProfileRequestContext().getInboundMessageContext());
outboundContext.getProfileRequestContext().setOutboundMessageContext(context.getProfileRequestContext().getOutboundMessageContext());
outboundContext.setMessage(authnRequest);
outboundContext.getSAMLEndpointContext().setEndpoint(acsService);
outboundContext.getSAMLPeerEndpointContext().setEndpoint(ssoService);
outboundContext.getSAMLPeerEntityContext().setRole(context.getSAMLPeerEntityContext().getRole());
outboundContext.getSAMLPeerEntityContext().setEntityId(context.getSAMLPeerEntityContext().getEntityId());
outboundContext.getSAMLProtocolContext().setProtocol(context.getSAMLProtocolContext().getProtocol());
outboundContext.getSecurityParametersContext().setSignatureSigningParameters(this.signatureSigningParametersProvider.build(spDescriptor));
if (relayState != null) {
outboundContext.getSAMLBindingContext().setRelayState(relayState.toString());
}
try {
invokeOutboundMessageHandlers(spDescriptor, idpssoDescriptor, outboundContext);
encoder.setMessageContext(outboundContext);
encoder.initialize();
encoder.prepareContext();
encoder.encode();
final SAMLMessageStorage messageStorage = context.getSAMLMessageStorage();
if (messageStorage != null) {
messageStorage.storeMessage(authnRequest.getID(), authnRequest);
}
} catch (final MessageEncodingException e) {
throw new SAMLException("Error encoding saml message", e);
} catch (final ComponentInitializationException e) {
throw new SAMLException("Error initializing saml encoder", e);
}
}
use of org.pac4j.saml.exceptions.SAMLException in project pac4j by pac4j.
the class SAML2WebSSOMessageSender method invokeOutboundMessageHandlers.
protected final void invokeOutboundMessageHandlers(final SPSSODescriptor spDescriptor, final IDPSSODescriptor idpssoDescriptor, final SAML2MessageContext outboundContext) {
try {
final EndpointURLSchemeSecurityHandler handlerEnd = new EndpointURLSchemeSecurityHandler();
handlerEnd.initialize();
handlerEnd.invoke(outboundContext);
final SAMLOutboundDestinationHandler handlerDest = new SAMLOutboundDestinationHandler();
handlerDest.initialize();
handlerDest.invoke(outboundContext);
boolean signOutboundContext = false;
if (this.isAuthnRequestSigned) {
logger.debug("Authn requests are expected to be always signed before submission");
signOutboundContext = true;
} else if (spDescriptor.isAuthnRequestsSigned()) {
logger.debug("The service provider metadata indicates that authn requests are signed");
signOutboundContext = true;
} else if (idpssoDescriptor.getWantAuthnRequestsSigned()) {
logger.debug("The identity provider metadata indicates that authn requests may be signed");
signOutboundContext = true;
}
if (signOutboundContext) {
logger.debug("Signing SAML2 outbound context...");
final SAMLOutboundProtocolMessageSigningHandler handler = new SAMLOutboundProtocolMessageSigningHandler();
handler.invoke(outboundContext);
}
} catch (final Exception e) {
throw new SAMLException(e);
}
}
use of org.pac4j.saml.exceptions.SAMLException in project pac4j by pac4j.
the class SAML2ClientConfiguration method createKeystore.
private void createKeystore() {
try {
if (CommonHelper.isBlank(this.keyStoreAlias)) {
this.keyStoreAlias = getClass().getSimpleName();
LOGGER.warn("Using keystore alias {}", this.keyStoreAlias);
}
if (CommonHelper.isBlank(this.keyStoreType)) {
this.keyStoreType = KeyStore.getDefaultType();
LOGGER.warn("Using keystore type {}", this.keyStoreType);
}
final KeyStore ks = KeyStore.getInstance(this.keyStoreType);
final char[] password = this.keystorePassword.toCharArray();
ks.load(null, password);
final KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
kpg.initialize(2048);
final KeyPair kp = kpg.genKeyPair();
final String sigAlgName = "SHA1WithRSA";
final AlgorithmIdentifier sigAlgID = new AlgorithmIdentifier(PKCSObjectIdentifiers.sha1WithRSAEncryption, DERNull.INSTANCE);
final String dn = InetAddress.getLocalHost().getHostName();
final PrivateKey signingKey = kp.getPrivate();
final X509Certificate certificate = createSelfSignedCert(new X500Name("CN=" + dn), sigAlgName, sigAlgID, kp);
final char[] keyPassword = this.privateKeyPassword.toCharArray();
ks.setKeyEntry(this.keyStoreAlias, signingKey, keyPassword, new Certificate[] { certificate });
try (final FileOutputStream fos = new FileOutputStream(this.keystoreResource.getFile().getCanonicalPath())) {
ks.store(fos, password);
fos.flush();
}
LOGGER.info("Created keystore {} with key alias {} ", keystoreResource.getFile().getCanonicalPath(), ks.aliases().nextElement());
} catch (final Exception e) {
throw new SAMLException("Could not create keystore", e);
}
}
Aggregations