Java Examples for org.opensaml.saml.saml2.core.Assertion
The following java examples will help you to understand the usage of org.opensaml.saml.saml2.core.Assertion. These source code samples are taken from different open source projects.
Example 1
| Project: wss4j-master File: SAML2ComponentBuilder.java View source code |
/**
* Create a SAML 2 assertion
*
* @return a SAML 2 assertion
*/
@SuppressWarnings("unchecked")
public static Assertion createAssertion() {
if (assertionBuilder == null) {
assertionBuilder = (SAMLObjectBuilder<Assertion>) builderFactory.getBuilder(Assertion.DEFAULT_ELEMENT_NAME);
if (assertionBuilder == null) {
throw new IllegalStateException("OpenSaml engine not initialized. Please make sure to initialize the OpenSaml engine " + "prior using it");
}
}
Assertion assertion = assertionBuilder.buildObject(Assertion.DEFAULT_ELEMENT_NAME, Assertion.TYPE_NAME);
assertion.setID(IDGenerator.generateID("_"));
assertion.setVersion(SAMLVersion.VERSION_20);
assertion.setIssueInstant(new DateTime());
return assertion;
}Example 2
| Project: tesb-rt-se-master File: SAML2AuthorizingInterceptor.java View source code |
private String getRoleFromAssertion(SamlAssertionWrapper assertion) {
Assertion saml2Assertion = assertion.getSaml2();
if (saml2Assertion == null) {
return null;
}
List<AttributeStatement> attributeStatements = saml2Assertion.getAttributeStatements();
if (attributeStatements == null || attributeStatements.isEmpty()) {
return null;
}
String nameFormat = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims";
for (AttributeStatement statement : attributeStatements) {
List<Attribute> attributes = statement.getAttributes();
for (Attribute attribute : attributes) {
if ("role".equals(attribute.getName()) && nameFormat.equals(attribute.getNameFormat())) {
Element attributeValueElement = attribute.getAttributeValues().get(0).getDOM();
return attributeValueElement.getTextContent();
}
}
}
return null;
}Example 3
| Project: cxf-master File: SAMLProtocolResponseValidator.java View source code |
/**
* Validate a SAML 2 Protocol Response
* @param samlResponse
* @param sigCrypto
* @param callbackHandler
* @throws WSSecurityException
*/
public void validateSamlResponse(org.opensaml.saml.saml2.core.Response samlResponse, Crypto sigCrypto, CallbackHandler callbackHandler) throws WSSecurityException {
// Check the Status Code
if (samlResponse.getStatus() == null || samlResponse.getStatus().getStatusCode() == null) {
LOG.fine("Either the SAML Response Status or StatusCode is null");
throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity");
}
if (!SAML2_STATUSCODE_SUCCESS.equals(samlResponse.getStatus().getStatusCode().getValue())) {
LOG.fine("SAML Status code of " + samlResponse.getStatus().getStatusCode().getValue() + "does not equal " + SAML2_STATUSCODE_SUCCESS);
throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity");
}
if (samlResponse.getIssueInstant() != null) {
DateTime currentTime = new DateTime();
currentTime = currentTime.plusSeconds(futureTTL);
if (samlResponse.getIssueInstant().isAfter(currentTime)) {
LOG.fine("SAML Response IssueInstant not met");
throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity");
}
}
if (SAMLVersion.VERSION_20 != samlResponse.getVersion()) {
LOG.fine("SAML Version of " + samlResponse.getVersion() + "does not equal " + SAMLVersion.VERSION_20);
throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity");
}
validateResponseSignature(samlResponse, sigCrypto, callbackHandler);
Document doc = samlResponse.getDOM().getOwnerDocument();
// signature on the Response)
for (org.opensaml.saml.saml2.core.EncryptedAssertion assertion : samlResponse.getEncryptedAssertions()) {
Element decAssertion = decryptAssertion(assertion, sigCrypto, callbackHandler);
SamlAssertionWrapper wrapper = new SamlAssertionWrapper(decAssertion);
samlResponse.getAssertions().add(wrapper.getSaml2());
}
// Validate Assertions
for (org.opensaml.saml.saml2.core.Assertion assertion : samlResponse.getAssertions()) {
SamlAssertionWrapper wrapper = new SamlAssertionWrapper(assertion);
validateAssertion(wrapper, sigCrypto, callbackHandler, doc, samlResponse.isSigned());
}
}Example 4
| Project: Consent2Share-master File: SamlTokenParser.java View source code |
// change this to redirect output if desired
// private static PrintStream out = System.out;
// private static String WS_SECURITY_URI =
// "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd";
@NO_LOG
public String parse(SamlAssertionWrapper assertionWrapper, String urn) {
try {
Assertion samlAssertion = assertionWrapper.getSaml2();
// List<AttributeStatement> stmt =
// samlAssertion.getAttributeStatements();
// String nameId =
// samlAssertion.getSubject().getNameID().getValue();
/**
* Below code works with OpenSAML API to check Authentication,
* Authorization, and attributes. Using the XPath API with the
* assertionElement above would probably be an easier and more
* readable option.
*/
// Element assertionElement = assertionWrapper.getElement();
// Check if math degree, error otherwise
List<AttributeStatement> asList = samlAssertion.getAttributeStatements();
if (asList == null || asList.size() == 0) {
throw createSOAPFaultException("Attributes are missing.", true);
} else {
boolean hasValidAttribute = false;
String additionalValue = "";
for (Iterator<AttributeStatement> it = asList.iterator(); it.hasNext(); ) {
AttributeStatement as = it.next();
List<Attribute> attList = as.getAttributes();
if (attList == null || attList.size() == 0) {
throw createSOAPFaultException("Attributes are missing.", true);
} else {
for (Iterator<Attribute> it2 = attList.iterator(); it2.hasNext(); ) {
Attribute att = it2.next();
if (!att.getName().equals(urn)) {
continue;
} else {
List<XMLObject> xoList = att.getAttributeValues();
if (xoList == null || xoList.size() < 1 || xoList.size() > 1) {
throw createSOAPFaultException("Attributes are missing.", true);
} else {
XMLObject xmlObj = xoList.get(0);
additionalValue = xmlObj.getDOM().getFirstChild().getTextContent();
return xmlObj.getDOM().getFirstChild().getTextContent();
// if (xmlObj.getDOM().getFirstChild()
// .getTextContent()
// .equals("Mathematics")) {
// hasMathDegree = true;
// }
}
}
}
}
}
if (hasValidAttribute == false) {
System.out.println("No Valid Attribute.");
System.out.println(additionalValue);
}
}
} catch (Exception e) {
throw createSOAPFaultException("Internal Error: " + e.getMessage(), false);
}
return null;
}Example 5
| Project: cas-master File: WsFederationHelper.java View source code |
/**
* 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) {
final ZonedDateTime retrievedOn = ZonedDateTime.now();
LOGGER.debug("Retrieved on [{}]", retrievedOn);
final WsFederationCredential credential = new WsFederationCredential();
credential.setRetrievedOn(retrievedOn);
credential.setId(assertion.getID());
credential.setIssuer(assertion.getIssuer());
credential.setIssuedOn(ZonedDateTime.parse(assertion.getIssueInstant().toDateTimeISO().toString()));
final Conditions conditions = assertion.getConditions();
if (conditions != null) {
credential.setNotBefore(ZonedDateTime.parse(conditions.getNotBefore().toDateTimeISO().toString()));
credential.setNotOnOrAfter(ZonedDateTime.parse(conditions.getNotOnOrAfter().toDateTimeISO().toString()));
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());
}
//retrieve an attributes from the assertion
final HashMap<String, List<Object>> attributes = new HashMap<>();
assertion.getAttributeStatements().stream().flatMap( attributeStatement -> attributeStatement.getAttributes().stream()).forEach( item -> {
LOGGER.debug("Processed attribute: [{}]", item.getAttributeName());
final List<Object> itemList = IntStream.range(0, item.getAttributeValues().size()).mapToObj( i -> ((XSAny) item.getAttributeValues().get(i)).getTextContent()).collect(Collectors.toList());
if (!itemList.isEmpty()) {
attributes.put(item.getAttributeName(), itemList);
}
});
credential.setAttributes(attributes);
LOGGER.debug("Credential: [{}]", credential);
return credential;
}Example 6
| Project: cxf-fediz-master File: STSAuthenticationProvider.java View source code |
protected List<Claim> parseClaimsInAssertion(org.opensaml.saml.saml2.core.Assertion assertion) {
List<org.opensaml.saml.saml2.core.AttributeStatement> attributeStatements = assertion.getAttributeStatements();
if (attributeStatements == null || attributeStatements.isEmpty()) {
LOG.debug("No attribute statements found");
return Collections.emptyList();
}
List<Claim> collection = new ArrayList<>();
Map<String, Claim> claimsMap = new HashMap<>();
for (org.opensaml.saml.saml2.core.AttributeStatement statement : attributeStatements) {
LOG.debug("parsing statement: {}", statement.getElementQName());
List<org.opensaml.saml.saml2.core.Attribute> attributes = statement.getAttributes();
for (org.opensaml.saml.saml2.core.Attribute attribute : attributes) {
LOG.debug("parsing attribute: {}", attribute.getName());
Claim c = new Claim();
// Workaround for CXF-4484
// Value of Attribute Name not fully qualified
// if NameFormat is http://schemas.xmlsoap.org/ws/2005/05/identity/claims
// but ClaimType value must be fully qualified as Namespace attribute goes away
URI attrName = URI.create(attribute.getName());
if (ClaimTypes.URI_BASE.toString().equals(attribute.getNameFormat()) && !attrName.isAbsolute()) {
c.setClaimType(URI.create(ClaimTypes.URI_BASE + "/" + attribute.getName()));
} else {
c.setClaimType(URI.create(attribute.getName()));
}
c.setIssuer(assertion.getIssuer().getNameQualifier());
List<String> valueList = new ArrayList<>();
for (XMLObject attributeValue : attribute.getAttributeValues()) {
Element attributeValueElement = attributeValue.getDOM();
String value = attributeValueElement.getTextContent();
LOG.debug(" [{}]", value);
valueList.add(value);
}
mergeClaimToMap(claimsMap, c, valueList);
}
}
collection.addAll(claimsMap.values());
return collection;
}Example 7
| Project: ddf-master File: IdpEndpoint.java View source code |
private AuthObj determineAuthMethod(String bodyStr, AuthnRequest authnRequest) {
XMLStreamReader xmlStreamReader = null;
try {
xmlStreamReader = xmlInputFactory.createXMLStreamReader(new StringReader(bodyStr));
} catch (XMLStreamException e) {
LOGGER.debug("Unable to parse SOAP message from client.", e);
}
SoapMessage soapMessage = new SoapMessage(Soap11.getInstance());
SAAJInInterceptor.SAAJPreInInterceptor preInInterceptor = new SAAJInInterceptor.SAAJPreInInterceptor();
soapMessage.setContent(XMLStreamReader.class, xmlStreamReader);
preInInterceptor.handleMessage(soapMessage);
SAAJInInterceptor inInterceptor = new SAAJInInterceptor();
inInterceptor.handleMessage(soapMessage);
SOAPPart soapMessageContent = (SOAPPart) soapMessage.getContent(Node.class);
AuthObj authObj = new AuthObj();
try {
Iterator soapHeaderElements = soapMessageContent.getEnvelope().getHeader().examineAllHeaderElements();
while (soapHeaderElements.hasNext()) {
SOAPHeaderElement soapHeaderElement = (SOAPHeaderElement) soapHeaderElements.next();
if (soapHeaderElement.getLocalName().equals("Security")) {
Iterator childElements = soapHeaderElement.getChildElements();
while (childElements.hasNext()) {
Object nextElement = childElements.next();
if (nextElement instanceof SOAPElement) {
SOAPElement element = (SOAPElement) nextElement;
if (element.getLocalName().equals("UsernameToken")) {
Iterator usernameTokenElements = element.getChildElements();
Object next;
while (usernameTokenElements.hasNext()) {
if ((next = usernameTokenElements.next()) instanceof Element) {
Element nextEl = (Element) next;
if (nextEl.getLocalName().equals("Username")) {
authObj.username = nextEl.getTextContent();
} else if (nextEl.getLocalName().equals("Password")) {
authObj.password = nextEl.getTextContent();
}
}
}
if (authObj.username != null && authObj.password != null) {
authObj.method = USER_PASS;
break;
}
} else if (element.getLocalName().equals("Assertion") && element.getNamespaceURI().equals("urn:oasis:names:tc:SAML:2.0:assertion")) {
authObj.assertion = new SecurityToken(element.getAttribute("ID"), element, null, null);
authObj.method = SAML;
break;
}
}
}
}
}
} catch (SOAPException e) {
LOGGER.debug("Unable to parse SOAP message.", e);
}
RequestedAuthnContext requestedAuthnContext = authnRequest.getRequestedAuthnContext();
boolean requestingPki = false;
boolean requestingUp = false;
if (requestedAuthnContext != null) {
List<AuthnContextClassRef> authnContextClassRefs = requestedAuthnContext.getAuthnContextClassRefs();
for (AuthnContextClassRef authnContextClassRef : authnContextClassRefs) {
String authnContextClassRefStr = authnContextClassRef.getAuthnContextClassRef();
if (SAML2Constants.AUTH_CONTEXT_CLASS_REF_X509.equals(authnContextClassRefStr) || SAML2Constants.AUTH_CONTEXT_CLASS_REF_SMARTCARD_PKI.equals(authnContextClassRefStr) || SAML2Constants.AUTH_CONTEXT_CLASS_REF_SOFTWARE_PKI.equals(authnContextClassRefStr) || SAML2Constants.AUTH_CONTEXT_CLASS_REF_SPKI.equals(authnContextClassRefStr) || SAML2Constants.AUTH_CONTEXT_CLASS_REF_TLS_CLIENT.equals(authnContextClassRefStr)) {
requestingPki = true;
} else if (SAML2Constants.AUTH_CONTEXT_CLASS_REF_PASSWORD.equals(authnContextClassRefStr) || SAML2Constants.AUTH_CONTEXT_CLASS_REF_PASSWORD_PROTECTED_TRANSPORT.equals(authnContextClassRefStr)) {
requestingUp = true;
}
}
} else {
//The requested auth context isn't required so we don't know what they want... just set both to true
requestingPki = true;
requestingUp = true;
}
if (requestingUp && authObj.method != null && authObj.method.equals(USER_PASS)) {
LOGGER.trace("Found UsernameToken and correct AuthnContextClassRef");
return authObj;
} else if (requestingPki && authObj.method == null) {
LOGGER.trace("Found no token, but client requested PKI AuthnContextClassRef");
authObj.method = PKI;
return authObj;
} else if (authObj.method == null) {
LOGGER.debug("No authentication tokens found for the current request and the client did not request PKI authentication");
}
return authObj;
}Example 8
| Project: pac4j-master File: SAML2DefaultResponseValidator.java View source code |
protected final SAML2Credentials buildSAML2Credentials(final SAML2MessageContext context) {
final NameID nameId = context.getSAMLSubjectNameIdentifierContext().getSAML2SubjectNameID();
final Assertion subjectAssertion = context.getSubjectAssertion();
final String sessionIndex = getSessionIndex(subjectAssertion);
final List<Attribute> attributes = new ArrayList<Attribute>();
for (final AttributeStatement attributeStatement : subjectAssertion.getAttributeStatements()) {
for (final Attribute attribute : attributeStatement.getAttributes()) {
attributes.add(attribute);
}
if (!attributeStatement.getEncryptedAttributes().isEmpty()) {
if (decrypter == null) {
logger.warn("Encrypted attributes returned, but no keystore was provided.");
} else {
for (final EncryptedAttribute encryptedAttribute : attributeStatement.getEncryptedAttributes()) {
try {
attributes.add(decrypter.decrypt(encryptedAttribute));
} catch (final DecryptionException e) {
logger.warn("Decryption of attribute failed, continue with the next one", e);
}
}
}
}
}
return new SAML2Credentials(nameId, attributes, subjectAssertion.getConditions(), SAML2Client.class.getSimpleName(), sessionIndex);
}Example 9
| Project: shibboleth-idp-ext-cas-master File: BuildSamlValidationSuccessMessageAction.java View source code |
@Nonnull
@Override
protected Response buildSamlResponse(@Nonnull final RequestContext springRequestContext, @Nonnull final ProfileRequestContext<SAMLObject, SAMLObject> profileRequestContext) {
final DateTime now = DateTime.now();
final TicketValidationRequest request = FlowStateSupport.getTicketValidationRequest(springRequestContext);
if (request == null) {
log.info("TicketValidationRequest not found in flow state.");
throw new IllegalStateException("TicketValidationRequest not found in flow state.");
}
final TicketValidationResponse ticketResponse = FlowStateSupport.getTicketValidationResponse(springRequestContext);
if (ticketResponse == null) {
log.info("TicketValidationResponse not found in flow state.");
throw new IllegalStateException("TicketValidationResponse not found in flow state.");
}
final SessionContext sessionCtx = profileRequestContext.getSubcontext(SessionContext.class, false);
if (sessionCtx == null || sessionCtx.getIdPSession() == null) {
log.info("Cannot locate IdP session");
throw new IllegalStateException("Cannot locate IdP session");
}
final IdPSession session = sessionCtx.getIdPSession();
final Response response = newSAMLObject(Response.class, Response.DEFAULT_ELEMENT_NAME);
final Status status = newSAMLObject(Status.class, Status.DEFAULT_ELEMENT_NAME);
final StatusCode code = newSAMLObject(StatusCode.class, StatusCode.DEFAULT_ELEMENT_NAME);
code.setValue(StatusCode.SUCCESS);
status.setStatusCode(code);
response.setStatus(status);
final Assertion assertion = newSAMLObject(Assertion.class, Assertion.DEFAULT_ELEMENT_NAME);
assertion.setID(identifierGenerationStrategy.generateIdentifier());
assertion.setIssueInstant(now);
assertion.setVersion(SAMLVersion.VERSION_11);
assertion.setIssuer(entityID);
final Conditions conditions = newSAMLObject(Conditions.class, Conditions.DEFAULT_ELEMENT_NAME);
conditions.setNotBefore(now);
conditions.setNotOnOrAfter(now.plusSeconds(60));
final AudienceRestrictionCondition audienceRestriction = newSAMLObject(AudienceRestrictionCondition.class, AudienceRestrictionCondition.DEFAULT_ELEMENT_NAME);
final Audience audience = newSAMLObject(Audience.class, Audience.DEFAULT_ELEMENT_NAME);
audience.setUri(request.getService());
audienceRestriction.getAudiences().add(audience);
conditions.getAudienceRestrictionConditions().add(audienceRestriction);
assertion.setConditions(conditions);
// Use flow ID for authentication method
for (AuthenticationResult result : session.getAuthenticationResults()) {
assertion.getAuthenticationStatements().add(newAuthenticationStatement(now, result.getAuthenticationFlowId(), session.getPrincipalName()));
}
final AttributeStatement attrStatement = newSAMLObject(AttributeStatement.class, AttributeStatement.DEFAULT_ELEMENT_NAME);
attrStatement.setSubject(newSubject(session.getPrincipalName()));
for (final String attrName : ticketResponse.getAttributes().keySet()) {
final Attribute attribute = newSAMLObject(Attribute.class, Attribute.DEFAULT_ELEMENT_NAME);
attribute.setAttributeName(attrName);
attribute.setAttributeNamespace(NAMESPACE);
for (String value : ticketResponse.getAttributes().get(attrName)) {
attribute.getAttributeValues().add(newAttributeValue(value));
}
attrStatement.getAttributes().add(attribute);
}
assertion.getAttributeStatements().add(attrStatement);
response.getAssertions().add(assertion);
return response;
}Example 10
| Project: syncope-master File: SAML2SPLogic.java View source code |
@PreAuthorize("hasRole('" + StandardEntitlement.ANONYMOUS + "')")
public SAML2LoginResponseTO validateLoginResponse(final SAML2ReceivedResponseTO response) {
check();
// 1. first checks for the provided relay state
JwsJwtCompactConsumer relayState = new JwsJwtCompactConsumer(response.getRelayState());
if (!relayState.verifySignatureWith(jwsSignatureCerifier)) {
throw new IllegalArgumentException("Invalid signature found in Relay State");
}
Boolean useDeflateEncoding = Boolean.valueOf(relayState.getJwtClaims().getClaim(JWT_CLAIM_IDP_DEFLATE).toString());
// 2. parse the provided SAML response
Response samlResponse;
try {
XMLObject responseObject = saml2rw.read(useDeflateEncoding, response.getSamlResponse());
if (!(responseObject instanceof Response)) {
throw new IllegalArgumentException("Expected " + Response.class.getName() + ", got " + responseObject.getClass().getName());
}
samlResponse = (Response) responseObject;
} catch (Exception e) {
LOG.error("While parsing AuthnResponse", e);
SyncopeClientException sce = SyncopeClientException.build(ClientExceptionType.Unknown);
sce.getElements().add(e.getMessage());
throw sce;
}
// 3a. the SAML Reponse's InResponseTo
if (!relayState.getJwtClaims().getSubject().equals(samlResponse.getInResponseTo())) {
throw new IllegalArgumentException("Unmatching request ID: " + samlResponse.getInResponseTo());
}
// 3b. the SAML Response status
if (!StatusCode.SUCCESS.equals(samlResponse.getStatus().getStatusCode().getValue())) {
throw new BadCredentialsException("The SAML IdP replied with " + samlResponse.getStatus().getStatusCode().getValue());
}
// 4. validate the SAML response and, if needed, decrypt the provided assertion(s)
SAML2IdPEntity idp = getIdP(samlResponse.getIssuer().getValue());
if (idp.getConnObjectKeyItem() == null) {
throw new IllegalArgumentException("No mapping provided for SAML 2.0 IdP '" + idp.getId() + "'");
}
try {
saml2rw.validate(samlResponse, idp.getTrustStore());
} catch (Exception e) {
LOG.error("While validating AuthnResponse", e);
SyncopeClientException sce = SyncopeClientException.build(ClientExceptionType.Unknown);
sce.getElements().add(e.getMessage());
throw sce;
}
// 5. prepare the result: find matching user (if any) and return the received attributes
SAML2LoginResponseTO responseTO = new SAML2LoginResponseTO();
responseTO.setIdp(idp.getId());
responseTO.setSloSupported(idp.getSLOLocation(idp.getBindingType()) != null);
NameID nameID = null;
String keyValue = null;
for (Assertion assertion : samlResponse.getAssertions()) {
nameID = assertion.getSubject().getNameID();
if (StringUtils.isNotBlank(nameID.getValue()) && idp.getConnObjectKeyItem().getExtAttrName().equals("NameID")) {
keyValue = nameID.getValue();
}
if (assertion.getConditions().getNotOnOrAfter() != null) {
responseTO.setNotOnOrAfter(assertion.getConditions().getNotOnOrAfter().toDate());
}
for (AuthnStatement authnStmt : assertion.getAuthnStatements()) {
responseTO.setSessionIndex(authnStmt.getSessionIndex());
responseTO.setAuthInstant(authnStmt.getAuthnInstant().toDate());
if (authnStmt.getSessionNotOnOrAfter() != null) {
responseTO.setNotOnOrAfter(authnStmt.getSessionNotOnOrAfter().toDate());
}
}
for (AttributeStatement attrStmt : assertion.getAttributeStatements()) {
for (Attribute attr : attrStmt.getAttributes()) {
if (!attr.getAttributeValues().isEmpty()) {
String attrName = attr.getFriendlyName() == null ? attr.getName() : attr.getFriendlyName();
if (attrName.equals(idp.getConnObjectKeyItem().getExtAttrName()) && attr.getAttributeValues().get(0) instanceof XSString) {
keyValue = ((XSString) attr.getAttributeValues().get(0)).getValue();
}
AttrTO attrTO = new AttrTO();
attrTO.setSchema(attrName);
for (XMLObject value : attr.getAttributeValues()) {
if (value.getDOM() != null) {
attrTO.getValues().add(value.getDOM().getTextContent());
}
}
responseTO.getAttrs().add(attrTO);
}
}
}
}
if (nameID == null) {
throw new IllegalArgumentException("NameID not found");
}
List<String> matchingUsers = keyValue == null ? Collections.<String>emptyList() : findMatchingUser(keyValue, idp.getConnObjectKeyItem());
LOG.debug("Found {} matching users for NameID {}", matchingUsers.size(), nameID.getValue());
if (matchingUsers.isEmpty()) {
throw new NotFoundException("User matching the provided NameID value " + nameID.getValue());
} else if (matchingUsers.size() > 1) {
throw new IllegalArgumentException("Several users match the provided NameID value " + nameID.getValue());
}
responseTO.setUsername(userDAO.find(matchingUsers.get(0)).getUsername());
responseTO.setNameID(nameID.getValue());
// 6. generate JWT for further access
Map<String, Object> claims = new HashMap<>();
claims.put(JWT_CLAIM_IDP_ENTITYID, idp.getId());
claims.put(JWT_CLAIM_NAMEID_FORMAT, nameID.getFormat());
claims.put(JWT_CLAIM_NAMEID_VALUE, nameID.getValue());
claims.put(JWT_CLAIM_SESSIONINDEX, responseTO.getSessionIndex());
responseTO.setAccessToken(accessTokenDataBinder.create(responseTO.getUsername(), claims, true));
return responseTO;
}