use of org.opensaml.saml.saml2.core.Attribute in project cas by apereo.
the class SamlIdPSaml2AttributeQueryProfileHandlerController method handlePostRequest.
/**
* Handle post request.
*
* @param response the response
* @param request the request
* @throws Exception the exception
*/
@PostMapping(path = SamlIdPConstants.ENDPOINT_SAML2_SOAP_ATTRIBUTE_QUERY)
protected void handlePostRequest(final HttpServletResponse response, final HttpServletRequest request) throws Exception {
val enabled = configurationContext.getCasProperties().getAuthn().getSamlIdp().getCore().isAttributeQueryProfileEnabled();
if (!enabled) {
LOGGER.warn("SAML2 attribute query profile is not enabled");
response.setStatus(HttpStatus.SC_NOT_IMPLEMENTED);
return;
}
val ctx = decodeSoapRequest(request);
val query = (AttributeQuery) ctx.getMessage();
try {
val issuer = Objects.requireNonNull(query).getIssuer().getValue();
val registeredService = verifySamlRegisteredService(issuer);
val adaptor = getSamlMetadataFacadeFor(registeredService, query);
val facade = adaptor.orElseThrow(() -> new UnauthorizedServiceException(UnauthorizedServiceException.CODE_UNAUTHZ_SERVICE, "Cannot find metadata linked to " + issuer));
verifyAuthenticationContextSignature(ctx, request, query, facade, registeredService);
val nameIdValue = determineNameIdForQuery(query, registeredService, facade);
val factory = (SamlAttributeQueryTicketFactory) getConfigurationContext().getTicketFactory().get(SamlAttributeQueryTicket.class);
val id = factory.createTicketIdFor(nameIdValue, facade.getEntityId());
LOGGER.debug("Created ticket id for attribute query [{}]", id);
val ticket = getConfigurationContext().getTicketRegistry().getTicket(id, SamlAttributeQueryTicket.class);
if (ticket == null || ticket.isExpired()) {
LOGGER.warn("Attribute query ticket [{}] has either expired, or it is linked to " + "a single sign-on session that is no longer valid and has now expired", id);
throw new InvalidTicketException(id);
}
val authentication = ticket.getAuthentication();
val principal = resolvePrincipalForAttributeQuery(authentication, registeredService);
val releasePolicyContext = RegisteredServiceAttributeReleasePolicyContext.builder().registeredService(registeredService).service(ticket.getService()).principal(principal).build();
val principalAttributes = registeredService.getAttributeReleasePolicy().getConsentableAttributes(releasePolicyContext);
LOGGER.debug("Initial consentable principal attributes are [{}]", principalAttributes);
val authenticationAttributes = getConfigurationContext().getAuthenticationAttributeReleasePolicy().getAuthenticationAttributesForRelease(authentication, null, Map.of(), registeredService);
val finalAttributes = CollectionUtils.merge(principalAttributes, authenticationAttributes);
val principalId = registeredService.getUsernameAttributeProvider().resolveUsername(authentication.getPrincipal(), ticket.getService(), registeredService);
LOGGER.debug("Principal id used for attribute query response should be [{}]", principalId);
LOGGER.debug("Final attributes to be processed for the SAML2 response are [{}]", finalAttributes);
val casAssertion = buildCasAssertion(principalId, registeredService, finalAttributes);
request.setAttribute(AttributeQuery.class.getSimpleName(), query);
val buildContext = SamlProfileBuilderContext.builder().samlRequest(query).httpRequest(request).httpResponse(response).authenticatedAssertion(casAssertion).registeredService(registeredService).adaptor(facade).binding(SAMLConstants.SAML2_SOAP11_BINDING_URI).messageContext(ctx).build();
getConfigurationContext().getResponseBuilder().build(buildContext);
} catch (final Exception e) {
LoggingUtils.error(LOGGER, e);
request.setAttribute(SamlIdPConstants.REQUEST_ATTRIBUTE_ERROR, "Unable to build SOAP response: " + StringUtils.defaultString(e.getMessage()));
val buildContext = SamlProfileBuilderContext.builder().samlRequest(query).httpRequest(request).httpResponse(response).binding(SAMLConstants.SAML2_SOAP11_BINDING_URI).messageContext(ctx).build();
getConfigurationContext().getSamlFaultResponseBuilder().build(buildContext);
}
}
use of org.opensaml.saml.saml2.core.Attribute in project cas by apereo.
the class SamlProfileSamlNameIdBuilder method encodeNameIdBasedOnNameFormat.
/**
* Encode name id based on name format name id.
*
* @param context the context
* @param nameFormat the name format
* @return the name id
*/
protected NameID encodeNameIdBasedOnNameFormat(final SamlProfileBuilderContext context, final String nameFormat) {
try {
val attribute = prepareNameIdAttribute(context, nameFormat);
val encoder = SamlAttributeBasedNameIdGenerator.get(Optional.of(context.getSamlRequest()), nameFormat, context.getRegisteredService(), attribute);
context.getHttpRequest().setAttribute(NameID.class.getName(), attribute);
LOGGER.debug("Encoding NameID based on [{}]", nameFormat);
val prc = new ProfileRequestContext();
val nameId = Objects.requireNonNull(encoder.generate(prc, nameFormat));
LOGGER.debug("Final NameID encoded with format [{}] has value [{}]", nameId.getFormat(), nameId.getValue());
return nameId;
} catch (final Exception e) {
LoggingUtils.error(LOGGER, e);
}
return null;
}
use of org.opensaml.saml.saml2.core.Attribute in project cas by apereo.
the class AbstractSamlObjectBuilder method newAttributeValue.
/**
* New attribute value.
*
* @param value the value
* @param valueType the value type
* @param elementName the element name
* @return the xS string
*/
protected XMLObject newAttributeValue(final Object value, final String valueType, final QName elementName) {
LOGGER.trace("Creating new attribute value XMLObject for value: [{}], value type: [{}], QName: [{}]", value, valueType, elementName);
if (value instanceof NameIDType) {
LOGGER.trace(LOG_MESSAGE_ATTR_CREATED, value);
((NameIDType) value).detach();
return (NameIDType) value;
}
if (XSString.class.getSimpleName().equalsIgnoreCase(valueType)) {
val builder = new XSStringBuilder();
val attrValueObj = builder.buildObject(elementName, XSString.TYPE_NAME);
attrValueObj.setValue(value.toString());
LOGGER.trace(LOG_MESSAGE_ATTR_CREATED, attrValueObj);
return attrValueObj;
}
if (XSURI.class.getSimpleName().equalsIgnoreCase(valueType)) {
val builder = new XSURIBuilder();
val attrValueObj = builder.buildObject(elementName, XSURI.TYPE_NAME);
attrValueObj.setURI(value.toString());
LOGGER.trace(LOG_MESSAGE_ATTR_CREATED, attrValueObj);
return attrValueObj;
}
if (XSBoolean.class.getSimpleName().equalsIgnoreCase(valueType)) {
val builder = new XSBooleanBuilder();
val attrValueObj = builder.buildObject(elementName, XSBoolean.TYPE_NAME);
attrValueObj.setValue(XSBooleanValue.valueOf(value.toString().toLowerCase()));
LOGGER.trace(LOG_MESSAGE_ATTR_CREATED, attrValueObj);
return attrValueObj;
}
if (XSInteger.class.getSimpleName().equalsIgnoreCase(valueType)) {
val builder = new XSIntegerBuilder();
val attrValueObj = builder.buildObject(elementName, XSInteger.TYPE_NAME);
attrValueObj.setValue(Integer.valueOf(value.toString()));
LOGGER.trace(LOG_MESSAGE_ATTR_CREATED, attrValueObj);
return attrValueObj;
}
if (XSDateTime.class.getSimpleName().equalsIgnoreCase(valueType)) {
val builder = new XSDateTimeBuilder();
val attrValueObj = builder.buildObject(elementName, XSDateTime.TYPE_NAME);
attrValueObj.setValue(ZonedDateTime.parse(value.toString()).toInstant());
LOGGER.trace(LOG_MESSAGE_ATTR_CREATED, attrValueObj);
return attrValueObj;
}
if (XSBase64Binary.class.getSimpleName().equalsIgnoreCase(valueType)) {
val builder = new XSBase64BinaryBuilder();
val attrValueObj = builder.buildObject(elementName, XSBase64Binary.TYPE_NAME);
attrValueObj.setValue(value.toString());
LOGGER.trace(LOG_MESSAGE_ATTR_CREATED, attrValueObj);
return attrValueObj;
}
if (XSObject.class.getSimpleName().equalsIgnoreCase(valueType)) {
val mapper = new JacksonXmlSerializer();
val builder = new XSAnyBuilder();
val attrValueObj = builder.buildObject(elementName);
attrValueObj.setTextContent(mapper.writeValueAsString(value));
LOGGER.trace(LOG_MESSAGE_ATTR_CREATED, attrValueObj);
return attrValueObj;
}
val builder = new XSAnyBuilder();
val attrValueObj = builder.buildObject(elementName);
attrValueObj.setTextContent(value.toString());
LOGGER.trace(LOG_MESSAGE_ATTR_CREATED, attrValueObj);
return attrValueObj;
}
use of org.opensaml.saml.saml2.core.Attribute in project cas by apereo.
the class WsFederationHelper method createCredentialFromToken.
/**
* createCredentialFromToken converts a SAML 1.1 assertion to a WSFederationCredential.
*
* @param assertion the provided assertion
* @return an equivalent credential.
*/
public WsFederationCredential createCredentialFromToken(final Assertion assertion) {
val retrievedOn = ZonedDateTime.now(clock);
LOGGER.trace("Retrieved on [{}]", retrievedOn);
val credential = new WsFederationCredential();
credential.setRetrievedOn(retrievedOn);
credential.setId(assertion.getID());
credential.setIssuer(assertion.getIssuer());
credential.setIssuedOn(DateTimeUtils.zonedDateTimeOf(assertion.getIssueInstant()));
val conditions = assertion.getConditions();
if (conditions != null) {
credential.setNotBefore(DateTimeUtils.zonedDateTimeOf(conditions.getNotBefore()));
credential.setNotOnOrAfter(DateTimeUtils.zonedDateTimeOf(conditions.getNotOnOrAfter()));
if (!conditions.getAudienceRestrictionConditions().isEmpty()) {
credential.setAudience(conditions.getAudienceRestrictionConditions().get(0).getAudiences().get(0).getURI());
}
}
if (!assertion.getAuthenticationStatements().isEmpty()) {
credential.setAuthenticationMethod(assertion.getAuthenticationStatements().get(0).getAuthenticationMethod());
}
val attributes = new HashMap<String, List<Object>>();
assertion.getAttributeStatements().stream().flatMap(attributeStatement -> attributeStatement.getAttributes().stream()).forEach(item -> {
LOGGER.trace("Processed attribute: [{}]", item.getAttributeName());
final List<Object> itemList = item.getAttributeValues().stream().map(xmlObject -> ((XSAny) xmlObject).getTextContent()).collect(Collectors.toList());
if (!itemList.isEmpty()) {
attributes.put(item.getAttributeName(), itemList);
}
});
credential.setAttributes(attributes);
LOGGER.debug("WsFederation Credential retrieved as: [{}]", credential);
return credential;
}
use of org.opensaml.saml.saml2.core.Attribute in project cas by apereo.
the class MetadataRequestedAttributesAttributeReleasePolicy method fetchRequestedAttributes.
private Map<String, List<Object>> fetchRequestedAttributes(final Map<String, List<Object>> attributes, final RegisteredServiceAttributeReleasePolicyContext context, final SamlRegisteredServiceServiceProviderMetadataFacade facade) {
val releaseAttributes = new HashMap<String, List<Object>>();
Optional.ofNullable(facade.getSsoDescriptor()).ifPresent(sso -> sso.getAttributeConsumingServices().forEach(svc -> svc.getRequestedAttributes().stream().filter(attr -> {
val name = this.useFriendlyName ? attr.getFriendlyName() : attr.getName();
LOGGER.debug("Checking for requested attribute [{}] in metadata for [{}]", name, context.getRegisteredService().getName());
return attributes.containsKey(name);
}).forEach(attr -> {
val name = this.useFriendlyName ? attr.getFriendlyName() : attr.getName();
LOGGER.debug("Found requested attribute [{}] in metadata for [{}]", name, context.getRegisteredService().getName());
releaseAttributes.put(name, attributes.get(name));
})));
return releaseAttributes;
}
Aggregations