use of org.opensaml.saml.saml2.core.SessionIndex in project cas by apereo.
the class GoogleAccountsServiceResponseBuilder method constructSamlResponse.
/**
* Construct SAML response.
* <a href="http://bit.ly/1uI8Ggu">See this reference for more info.</a>
*
* @param service the service
* @return the SAML response
*/
protected String constructSamlResponse(final GoogleAccountsService service) {
final ZonedDateTime currentDateTime = ZonedDateTime.now(ZoneOffset.UTC);
final ZonedDateTime notBeforeIssueInstant = ZonedDateTime.parse("2003-04-17T00:46:02Z");
final RegisteredService registeredService = servicesManager.findServiceBy(service);
if (registeredService == null || !registeredService.getAccessStrategy().isServiceAccessAllowed()) {
throw new UnauthorizedServiceException(UnauthorizedServiceException.CODE_UNAUTHZ_SERVICE);
}
final String userId = registeredService.getUsernameAttributeProvider().resolveUsername(service.getPrincipal(), service);
final org.opensaml.saml.saml2.core.Response response = this.samlObjectBuilder.newResponse(this.samlObjectBuilder.generateSecureRandomId(), currentDateTime, service.getId(), service);
response.setStatus(this.samlObjectBuilder.newStatus(StatusCode.SUCCESS, null));
final String sessionIndex = '_' + String.valueOf(Math.abs(new SecureRandom().nextLong()));
final AuthnStatement authnStatement = this.samlObjectBuilder.newAuthnStatement(AuthnContext.PASSWORD_AUTHN_CTX, currentDateTime, sessionIndex);
final Assertion assertion = this.samlObjectBuilder.newAssertion(authnStatement, casServerPrefix, notBeforeIssueInstant, this.samlObjectBuilder.generateSecureRandomId());
final Conditions conditions = this.samlObjectBuilder.newConditions(notBeforeIssueInstant, currentDateTime.plusSeconds(this.skewAllowance), service.getId());
assertion.setConditions(conditions);
final Subject subject = this.samlObjectBuilder.newSubject(NameID.EMAIL, userId, service.getId(), currentDateTime.plusSeconds(this.skewAllowance), service.getRequestId());
assertion.setSubject(subject);
response.getAssertions().add(assertion);
final StringWriter writer = new StringWriter();
this.samlObjectBuilder.marshalSamlXmlObject(response, writer);
final String result = writer.toString();
LOGGER.debug("Generated Google SAML response: [{}]", result);
return result;
}
use of org.opensaml.saml.saml2.core.SessionIndex in project syncope by apache.
the class SAML2SPLogic method createLogoutRequest.
@PreAuthorize("isAuthenticated() and not(hasRole('" + StandardEntitlement.ANONYMOUS + "'))")
public SAML2RequestTO createLogoutRequest(final String accessToken, final String spEntityID) {
check();
// 1. fetch the current JWT used for Syncope authentication
JwsJwtCompactConsumer consumer = new JwsJwtCompactConsumer(accessToken);
if (!consumer.verifySignatureWith(jwsSignatureVerifier)) {
throw new IllegalArgumentException("Invalid signature found in Access Token");
}
// 2. look for IdP
String idpEntityID = (String) consumer.getJwtClaims().getClaim(JWT_CLAIM_IDP_ENTITYID);
if (idpEntityID == null) {
throw new NotFoundException("No SAML 2.0 IdP information found in the access token");
}
SAML2IdPEntity idp = cache.get(idpEntityID);
if (idp == null) {
throw new NotFoundException("SAML 2.0 IdP '" + idpEntityID + "'");
}
if (idp.getSLOLocation(idp.getBindingType()) == null) {
throw new IllegalArgumentException("No SingleLogoutService available for " + idp.getId());
}
// 3. create LogoutRequest
LogoutRequest logoutRequest = new LogoutRequestBuilder().buildObject();
logoutRequest.setID("_" + UUID_GENERATOR.generate().toString());
logoutRequest.setDestination(idp.getSLOLocation(idp.getBindingType()).getLocation());
DateTime now = new DateTime();
logoutRequest.setIssueInstant(now);
logoutRequest.setNotOnOrAfter(now.plusMinutes(5));
Issuer issuer = new IssuerBuilder().buildObject();
issuer.setValue(spEntityID);
logoutRequest.setIssuer(issuer);
NameID nameID = new NameIDBuilder().buildObject();
nameID.setFormat((String) consumer.getJwtClaims().getClaim(JWT_CLAIM_NAMEID_FORMAT));
nameID.setValue((String) consumer.getJwtClaims().getClaim(JWT_CLAIM_NAMEID_VALUE));
logoutRequest.setNameID(nameID);
SessionIndex sessionIndex = new SessionIndexBuilder().buildObject();
sessionIndex.setSessionIndex((String) consumer.getJwtClaims().getClaim(JWT_CLAIM_SESSIONINDEX));
logoutRequest.getSessionIndexes().add(sessionIndex);
SAML2RequestTO requestTO = new SAML2RequestTO();
requestTO.setIdpServiceAddress(logoutRequest.getDestination());
requestTO.setBindingType(idp.getBindingType());
try {
// 3. generate relay state as JWT
Map<String, Object> claims = new HashMap<>();
claims.put(JWT_CLAIM_IDP_DEFLATE, idp.getBindingType() == SAML2BindingType.REDIRECT ? true : idp.isUseDeflateEncoding());
Triple<String, String, Date> relayState = accessTokenDataBinder.generateJWT(logoutRequest.getID(), JWT_RELAY_STATE_DURATION, claims);
requestTO.setRelayState(relayState.getMiddle());
// 4. sign and encode AuthnRequest
switch(idp.getBindingType()) {
case REDIRECT:
requestTO.setContent(saml2rw.encode(logoutRequest, true));
requestTO.setSignAlg(saml2rw.getSigAlgo());
requestTO.setSignature(saml2rw.sign(requestTO.getContent(), requestTO.getRelayState()));
break;
case POST:
default:
saml2rw.sign(logoutRequest);
requestTO.setContent(saml2rw.encode(logoutRequest, idp.isUseDeflateEncoding()));
}
} catch (Exception e) {
LOG.error("While generating LogoutRequest", e);
SyncopeClientException sce = SyncopeClientException.build(ClientExceptionType.Unknown);
sce.getElements().add(e.getMessage());
throw sce;
}
return requestTO;
}
use of org.opensaml.saml.saml2.core.SessionIndex in project pac4j by pac4j.
the class SAML2LogoutRequestBuilder method buildLogoutRequest.
@SuppressWarnings("unchecked")
protected final LogoutRequest buildLogoutRequest(final SAML2MessageContext context, final AssertionConsumerService assertionConsumerService, final SingleLogoutService ssoService) {
final SAMLObjectBuilder<LogoutRequest> builder = (SAMLObjectBuilder<LogoutRequest>) this.builderFactory.getBuilder(LogoutRequest.DEFAULT_ELEMENT_NAME);
final LogoutRequest request = builder.buildObject();
final SAMLSelfEntityContext selfContext = context.getSAMLSelfEntityContext();
request.setID(generateID());
request.setIssuer(getIssuer(selfContext.getEntityId()));
request.setIssueInstant(DateTime.now(DateTimeZone.UTC).plusSeconds(this.issueInstantSkewSeconds));
request.setVersion(SAMLVersion.VERSION_20);
request.setDestination(ssoService.getLocation());
// very very bad...
ProfileManager manager = new ProfileManager(context.getWebContext());
Optional<UserProfile> p = manager.get(true);
if (p.isPresent() && p.get() instanceof SAML2Profile) {
final SAML2Profile samlP = (SAML2Profile) p.get();
// name id added (id of profile)
final SAMLObjectBuilder<NameID> nameIdBuilder = (SAMLObjectBuilder<NameID>) this.builderFactory.getBuilder(NameID.DEFAULT_ELEMENT_NAME);
final NameID nameId = nameIdBuilder.buildObject();
nameId.setValue(samlP.getId());
nameId.setFormat(samlP.getSamlNameIdFormat());
nameId.setNameQualifier(samlP.getSamlNameIdNameQualifier());
nameId.setSPNameQualifier(samlP.getSamlNameIdSpNameQualifier());
nameId.setSPProvidedID(samlP.getSamlNameIdSpProviderId());
request.setNameID(nameId);
// session index added
final String sessIdx = (String) samlP.getAttribute("sessionindex");
final SAMLObjectBuilder<SessionIndex> sessionIndexBuilder = (SAMLObjectBuilder<SessionIndex>) this.builderFactory.getBuilder(SessionIndex.DEFAULT_ELEMENT_NAME);
final SessionIndex sessionIdx = sessionIndexBuilder.buildObject();
sessionIdx.setSessionIndex(sessIdx);
request.getSessionIndexes().add(sessionIdx);
}
return request;
}
use of org.opensaml.saml.saml2.core.SessionIndex in project ddf by codice.
the class LogoutRequestServiceTest method testPostLogoutRequestNotParsable.
@Test
public void testPostLogoutRequestNotParsable() throws Exception {
String encodedSamlRequest = "encodedSamlRequest";
LogoutRequest logoutRequest = mock(LogoutRequest.class);
when(logoutRequest.getIssueInstant()).thenReturn(DateTime.now());
SessionIndex sessionIndex = mock(SessionIndex.class);
when(sessionIndex.getSessionIndex()).thenReturn(SESSION_INDEX);
when(logoutRequest.getSessionIndexes()).thenReturn(Collections.singletonList(sessionIndex));
insertLogoutRequest();
logoutRequestService.setLogoutMessage(logoutMessage);
Response response = logoutRequestService.postLogoutRequest(encodedSamlRequest, null, relayState);
assertEquals(Response.Status.SEE_OTHER.getStatusCode(), response.getStatus());
String msg = UNABLE_TO_PARSE_LOGOUT_REQUEST.replaceAll(" ", "+");
assertTrue("Expected message containing " + msg, response.getLocation().getQuery().contains(msg));
}
use of org.opensaml.saml.saml2.core.SessionIndex in project ddf by codice.
the class LogoutRequestServiceTest method testSendLogoutRequestInvalidNumberOfParams.
@Test
public void testSendLogoutRequestInvalidNumberOfParams() throws Exception {
String encryptedNameIdWithTime = nameId + "\n" + time;
when(encryptionService.decrypt(any(String.class))).thenReturn(nameId);
LogoutRequest logoutRequest = mock(LogoutRequest.class);
when(logoutRequest.getIssueInstant()).thenReturn(DateTime.now());
SessionIndex sessionIndex = mock(SessionIndex.class);
when(sessionIndex.getSessionIndex()).thenReturn(SESSION_INDEX);
when(logoutRequest.getSessionIndexes()).thenReturn(Collections.singletonList(sessionIndex));
logoutRequestService.setLogoutMessage(logoutMessage);
Response response = logoutRequestService.sendLogoutRequest(encryptedNameIdWithTime);
assertEquals(Response.Status.SEE_OTHER.getStatusCode(), response.getStatus());
insertLogoutRequest();
String msg = LogoutRequestService.UNABLE_TO_DECRYPT_LOGOUT_REQUEST.replaceAll(" ", "+");
assertTrue("Expected message containing " + msg, response.getLocation().getQuery().contains(msg));
}
Aggregations