use of org.opensaml.saml.saml2.core.NameIDPolicy in project cas by apereo.
the class IdPInitiatedProfileHandlerController method handleIdPInitiatedSsoRequest.
/**
* Handle idp initiated sso requests.
*
* @param response the response
* @param request the request
* @throws Exception the exception
*/
@GetMapping(path = SamlIdPConstants.ENDPOINT_SAML2_IDP_INIT_PROFILE_SSO)
protected void handleIdPInitiatedSsoRequest(final HttpServletResponse response, final HttpServletRequest request) throws Exception {
// The name (i.e., the entity ID) of the service provider.
final String providerId = CommonUtils.safeGetParameter(request, SamlIdPConstants.PROVIDER_ID);
if (StringUtils.isBlank(providerId)) {
LOGGER.warn("No providerId parameter given in unsolicited SSO authentication request.");
throw new MessageDecodingException("No providerId parameter given in unsolicited SSO authentication request.");
}
final SamlRegisteredService registeredService = verifySamlRegisteredService(providerId);
final Optional<SamlRegisteredServiceServiceProviderMetadataFacade> adaptor = getSamlMetadataFacadeFor(registeredService, providerId);
if (!adaptor.isPresent()) {
throw new UnauthorizedServiceException(UnauthorizedServiceException.CODE_UNAUTHZ_SERVICE, "Cannot find metadata linked to " + providerId);
}
// The URL of the response location at the SP (called the "Assertion Consumer Service")
// but can be omitted in favor of the IdP picking the default endpoint location from metadata.
String shire = CommonUtils.safeGetParameter(request, SamlIdPConstants.SHIRE);
final SamlRegisteredServiceServiceProviderMetadataFacade facade = adaptor.get();
if (StringUtils.isBlank(shire)) {
LOGGER.warn("Resolving service provider assertion consumer service URL for [{}] and binding [{}]", providerId, SAMLConstants.SAML2_POST_BINDING_URI);
@NonNull final AssertionConsumerService acs = facade.getAssertionConsumerService(SAMLConstants.SAML2_POST_BINDING_URI);
shire = acs.getLocation();
}
if (StringUtils.isBlank(shire)) {
LOGGER.warn("Unable to resolve service provider assertion consumer service URL for AuthnRequest construction for entityID: [{}]", providerId);
throw new MessageDecodingException("Unable to resolve SP ACS URL for AuthnRequest construction");
}
// The target resource at the SP, or a state token generated by an SP to represent the resource.
final String target = CommonUtils.safeGetParameter(request, SamlIdPConstants.TARGET);
// A timestamp to help with stale request detection.
final String time = CommonUtils.safeGetParameter(request, SamlIdPConstants.TIME);
final SAMLObjectBuilder builder = (SAMLObjectBuilder) configBean.getBuilderFactory().getBuilder(AuthnRequest.DEFAULT_ELEMENT_NAME);
final AuthnRequest authnRequest = (AuthnRequest) builder.buildObject();
authnRequest.setAssertionConsumerServiceURL(shire);
final SAMLObjectBuilder isBuilder = (SAMLObjectBuilder) configBean.getBuilderFactory().getBuilder(Issuer.DEFAULT_ELEMENT_NAME);
final Issuer issuer = (Issuer) isBuilder.buildObject();
issuer.setValue(providerId);
authnRequest.setIssuer(issuer);
authnRequest.setProtocolBinding(SAMLConstants.SAML2_POST_BINDING_URI);
final SAMLObjectBuilder pBuilder = (SAMLObjectBuilder) configBean.getBuilderFactory().getBuilder(NameIDPolicy.DEFAULT_ELEMENT_NAME);
final NameIDPolicy nameIDPolicy = (NameIDPolicy) pBuilder.buildObject();
nameIDPolicy.setAllowCreate(Boolean.TRUE);
authnRequest.setNameIDPolicy(nameIDPolicy);
if (NumberUtils.isCreatable(time)) {
authnRequest.setIssueInstant(new DateTime(TimeUnit.SECONDS.convert(Long.parseLong(time), TimeUnit.MILLISECONDS), ISOChronology.getInstanceUTC()));
} else {
authnRequest.setIssueInstant(new DateTime(DateTime.now(), ISOChronology.getInstanceUTC()));
}
authnRequest.setForceAuthn(Boolean.FALSE);
if (StringUtils.isNotBlank(target)) {
request.setAttribute(SamlProtocolConstants.PARAMETER_SAML_RELAY_STATE, target);
}
final MessageContext ctx = new MessageContext();
ctx.setAutoCreateSubcontexts(true);
if (facade.isAuthnRequestsSigned()) {
samlObjectSigner.encode(authnRequest, registeredService, facade, response, request, SAMLConstants.SAML2_POST_BINDING_URI);
}
ctx.setMessage(authnRequest);
ctx.getSubcontext(SAMLBindingContext.class, true).setHasBindingSignature(false);
final Pair<SignableSAMLObject, MessageContext> pair = Pair.of(authnRequest, ctx);
initiateAuthenticationRequest(pair, response, request);
}
use of org.opensaml.saml.saml2.core.NameIDPolicy in project syncope by apache.
the class SAML2SPLogic method createLoginRequest.
@PreAuthorize("hasRole('" + StandardEntitlement.ANONYMOUS + "')")
public SAML2RequestTO createLoginRequest(final String spEntityID, final String idpEntityID) {
check();
// 1. look for IdP
SAML2IdPEntity idp = StringUtils.isBlank(idpEntityID) ? cache.getFirst() : cache.get(idpEntityID);
if (idp == null) {
if (StringUtils.isBlank(idpEntityID)) {
List<SAML2IdP> all = saml2IdPDAO.findAll();
if (!all.isEmpty()) {
idp = getIdP(all.get(0).getKey());
}
} else {
idp = getIdP(idpEntityID);
}
}
if (idp == null) {
throw new NotFoundException(StringUtils.isBlank(idpEntityID) ? "Any SAML 2.0 IdP" : "SAML 2.0 IdP '" + idpEntityID + "'");
}
if (idp.getSSOLocation(idp.getBindingType()) == null) {
throw new IllegalArgumentException("No SingleSignOnService available for " + idp.getId());
}
// 2. create AuthnRequest
Issuer issuer = new IssuerBuilder().buildObject();
issuer.setValue(spEntityID);
NameIDPolicy nameIDPolicy = new NameIDPolicyBuilder().buildObject();
if (idp.supportsNameIDFormat(NameIDType.TRANSIENT)) {
nameIDPolicy.setFormat(NameIDType.TRANSIENT);
} else if (idp.supportsNameIDFormat(NameIDType.PERSISTENT)) {
nameIDPolicy.setFormat(NameIDType.PERSISTENT);
} else {
throw new IllegalArgumentException("Could not find supported NameIDFormat for IdP " + idpEntityID);
}
nameIDPolicy.setAllowCreate(true);
nameIDPolicy.setSPNameQualifier(spEntityID);
AuthnContextClassRef authnContextClassRef = new AuthnContextClassRefBuilder().buildObject();
authnContextClassRef.setAuthnContextClassRef(AuthnContext.PPT_AUTHN_CTX);
RequestedAuthnContext requestedAuthnContext = new RequestedAuthnContextBuilder().buildObject();
requestedAuthnContext.setComparison(AuthnContextComparisonTypeEnumeration.EXACT);
requestedAuthnContext.getAuthnContextClassRefs().add(authnContextClassRef);
AuthnRequest authnRequest = new AuthnRequestBuilder().buildObject();
authnRequest.setID("_" + UUID_GENERATOR.generate().toString());
authnRequest.setForceAuthn(false);
authnRequest.setIsPassive(false);
authnRequest.setVersion(SAMLVersion.VERSION_20);
authnRequest.setProtocolBinding(idp.getBindingType().getUri());
authnRequest.setIssueInstant(new DateTime());
authnRequest.setIssuer(issuer);
authnRequest.setNameIDPolicy(nameIDPolicy);
authnRequest.setRequestedAuthnContext(requestedAuthnContext);
authnRequest.setDestination(idp.getSSOLocation(idp.getBindingType()).getLocation());
SAML2RequestTO requestTO = new SAML2RequestTO();
requestTO.setIdpServiceAddress(authnRequest.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.isUseDeflateEncoding());
Triple<String, String, Date> relayState = accessTokenDataBinder.generateJWT(authnRequest.getID(), JWT_RELAY_STATE_DURATION, claims);
// 4. sign and encode AuthnRequest
switch(idp.getBindingType()) {
case REDIRECT:
requestTO.setRelayState(URLEncoder.encode(relayState.getMiddle(), StandardCharsets.UTF_8.name()));
requestTO.setContent(URLEncoder.encode(saml2rw.encode(authnRequest, true), StandardCharsets.UTF_8.name()));
requestTO.setSignAlg(URLEncoder.encode(saml2rw.getSigAlgo(), StandardCharsets.UTF_8.name()));
requestTO.setSignature(URLEncoder.encode(saml2rw.sign(requestTO.getContent(), requestTO.getRelayState()), StandardCharsets.UTF_8.name()));
break;
case POST:
default:
requestTO.setRelayState(relayState.getMiddle());
saml2rw.sign(authnRequest);
requestTO.setContent(saml2rw.encode(authnRequest, idp.isUseDeflateEncoding()));
}
} catch (Exception e) {
LOG.error("While generating AuthnRequest", e);
SyncopeClientException sce = SyncopeClientException.build(ClientExceptionType.Unknown);
sce.getElements().add(e.getMessage());
throw sce;
}
return requestTO;
}
use of org.opensaml.saml.saml2.core.NameIDPolicy in project spring-security by spring-projects.
the class OpenSaml4AuthenticationRequestFactory method setNameIdPolicy.
private void setNameIdPolicy(AuthnRequest authnRequest, RelyingPartyRegistration registration) {
if (!StringUtils.hasText(registration.getNameIdFormat())) {
return;
}
NameIDPolicy nameIdPolicy = this.nameIdPolicyBuilder.buildObject();
nameIdPolicy.setFormat(registration.getNameIdFormat());
authnRequest.setNameIDPolicy(nameIdPolicy);
}
use of org.opensaml.saml.saml2.core.NameIDPolicy in project verify-hub by alphagov.
the class IdaAuthnRequestFromHubToAuthnRequestTransformerTest method shouldSetAllowCreateToTrue.
@Test
public void shouldSetAllowCreateToTrue() {
IdaAuthnRequestFromHub originalRequestFromHub = anIdaAuthnRequest().buildFromHub();
AuthnRequest transformedRequest = transformer.apply(originalRequestFromHub);
NameIDPolicy nameIDPolicy = transformedRequest.getNameIDPolicy();
assertThat(nameIDPolicy.getAllowCreate()).isEqualTo(true);
}
use of org.opensaml.saml.saml2.core.NameIDPolicy in project verify-hub by alphagov.
the class NameIdPolicyBuilder method build.
public NameIDPolicy build() {
NameIDPolicy nameIdPolicy = openSamlXmlObjectFactory.createNameIdPolicy();
format.ifPresent(nameIdPolicy::setFormat);
return nameIdPolicy;
}
Aggregations