Search in sources :

Example 16 with Endpoint

use of org.opensaml.saml.saml2.metadata.Endpoint in project MaxKey by dromara.

the class AssertionEndpoint method assertion.

@RequestMapping(value = "/authz/saml20/assertion")
public ModelAndView assertion(HttpServletRequest request, HttpServletResponse response) throws Exception {
    logger.debug("saml20 assertion start.");
    bindingAdapter = (BindingAdapter) request.getSession().getAttribute(WebConstants.AUTHORIZE_SIGN_ON_APP_SAMLV20_ADAPTER);
    logger.debug("saml20 assertion get session samlv20Adapter " + bindingAdapter);
    AppsSAML20Details saml20Details = bindingAdapter.getSaml20Details();
    logger.debug("saml20Details " + saml20Details.getExtendAttr());
    AuthnRequestInfo authnRequestInfo = bindingAdapter.getAuthnRequestInfo();
    if (authnRequestInfo == null) {
        logger.warn("Could not find AuthnRequest on the request.  Responding with SC_FORBIDDEN.");
        throw new Exception();
    }
    logger.debug("AuthnRequestInfo: {}", authnRequestInfo);
    HashMap<String, String> attributeMap = new HashMap<String, String>();
    attributeMap.put(WebConstants.ONLINE_TICKET_NAME, ((SigninPrincipal) WebContext.getAuthentication().getPrincipal()).getOnlineTicket().getTicketId());
    // saml20Details
    Response authResponse = authnResponseGenerator.generateAuthnResponse(saml20Details, authnRequestInfo, attributeMap, bindingAdapter);
    Endpoint endpoint = endpointGenerator.generateEndpoint(saml20Details.getSpAcsUrl());
    request.getSession().removeAttribute(AuthnRequestInfo.class.getName());
    // request issuer...
    try {
        bindingAdapter.sendSAMLMessage(authResponse, endpoint, request, response);
    } catch (MessageEncodingException mee) {
        logger.error("Exception encoding SAML message", mee);
        throw new Exception(mee);
    }
    return null;
}
Also used : HttpServletResponse(javax.servlet.http.HttpServletResponse) Response(org.opensaml.saml2.core.Response) AppsSAML20Details(org.maxkey.entity.apps.AppsSAML20Details) Endpoint(org.opensaml.saml2.metadata.Endpoint) HashMap(java.util.HashMap) AuthnRequestInfo(org.maxkey.authz.saml.common.AuthnRequestInfo) SigninPrincipal(org.maxkey.authn.SigninPrincipal) MessageEncodingException(org.opensaml.ws.message.encoder.MessageEncodingException) MessageEncodingException(org.opensaml.ws.message.encoder.MessageEncodingException) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 17 with Endpoint

use of org.opensaml.saml.saml2.metadata.Endpoint in project MaxKey by dromara.

the class EndpointGenerator method generateEndpoint.

public Endpoint generateEndpoint(String location) {
    logger.debug("end point location: {}", location);
    Endpoint samlEndpoint = new AssertionConsumerServiceBuilder().buildObject();
    samlEndpoint.setLocation(location);
    return samlEndpoint;
}
Also used : Endpoint(org.opensaml.saml2.metadata.Endpoint) AssertionConsumerServiceBuilder(org.opensaml.saml2.metadata.impl.AssertionConsumerServiceBuilder)

Example 18 with Endpoint

use of org.opensaml.saml.saml2.metadata.Endpoint in project identity-inbound-auth-oauth by wso2-extensions.

the class SAML2BearerGrantHandlerTest method validateGrantExceptionDataProvider.

@DataProvider(name = "validateGrantExceptionDataProvider")
public Object[][] validateGrantExceptionDataProvider() throws Exception {
    NameID nameId1 = (new NameIDBuilder()).buildObject();
    nameId1.setValue("nameIdValue");
    Subject subject1 = (new SubjectBuilder()).buildObject();
    subject1.setNameID(nameId1);
    NameID nameId2 = (new NameIDBuilder()).buildObject();
    nameId2.setValue(null);
    Subject subject2 = (new SubjectBuilder()).buildObject();
    subject2.setNameID(nameId2);
    DateTime validOnOrAfter = new DateTime(System.currentTimeMillis() + 10000000L);
    DateTime expiredOnOrAfter = new DateTime(System.currentTimeMillis() - 10000000L);
    return new Object[][] { { validOnOrAfter, "LOCAL", true, true, TestConstants.OAUTH2_TOKEN_EP, TestConstants.LOACALHOST_DOMAIN, new IdentityUnmarshallingException("Error"), "Error while unmashalling" }, { validOnOrAfter, "FED", true, true, TestConstants.OAUTH2_TOKEN_EP, TestConstants.LOACALHOST_DOMAIN, new IdentityProviderManagementException("Error"), "Error while retrieving identity provider" }, { validOnOrAfter, "FED", true, true, TestConstants.OAUTH2_TOKEN_EP, TestConstants.LOACALHOST_DOMAIN, new SignatureException(), "Error while validating the signature" }, { validOnOrAfter, "LOCAL", true, true, TestConstants.OAUTH2_TOKEN_EP, TestConstants.LOACALHOST_DOMAIN, new IdentityApplicationManagementException("Error"), "Error while retrieving service provider" }, { validOnOrAfter, "LOCAL", true, true, TestConstants.OAUTH2_TOKEN_EP, TestConstants.LOACALHOST_DOMAIN, new UserStoreException(), "Error while building local user" }, { validOnOrAfter, "FED", true, true, TestConstants.OAUTH2_TOKEN_EP, TestConstants.LOACALHOST_DOMAIN, new CertificateException(), "Error occurred while decoding public certificate" }, { validOnOrAfter, "LOCAL", true, false, TestConstants.OAUTH2_TOKEN_EP, TestConstants.LOACALHOST_DOMAIN, null, "User not found" }, { validOnOrAfter, "LOCAL", false, true, TestConstants.OAUTH2_TOKEN_EP, TestConstants.LOACALHOST_DOMAIN, null, "Non SaaS app" }, { validOnOrAfter, "LOCAL", true, true, "invalidAudience", TestConstants.LOACALHOST_DOMAIN, null, "Audience Restriction validation failed" }, { validOnOrAfter, "LOCAL", true, true, "", TestConstants.LOACALHOST_DOMAIN, null, "Token Endpoint alias has not been configured" }, { validOnOrAfter, "FED", true, true, "invalidAudience", TestConstants.LOACALHOST_DOMAIN, null, "Audience Restriction validation failed" }, { validOnOrAfter, null, true, true, TestConstants.OAUTH2_TOKEN_EP, TestConstants.LOACALHOST_DOMAIN, null, "Identity provider is null" }, { expiredOnOrAfter, "LOCAL", true, true, TestConstants.OAUTH2_TOKEN_EP, TestConstants.LOACALHOST_DOMAIN, null, "Assertion is not valid" }, { null, "LOCAL", true, true, TestConstants.OAUTH2_TOKEN_EP, TestConstants.LOACALHOST_DOMAIN, null, "Cannot find valid NotOnOrAfter" } };
}
Also used : NameIDBuilder(org.opensaml.saml.saml2.core.impl.NameIDBuilder) NameID(org.opensaml.saml.saml2.core.NameID) IdentityApplicationManagementException(org.wso2.carbon.identity.application.common.IdentityApplicationManagementException) UserStoreException(org.wso2.carbon.user.api.UserStoreException) CertificateException(java.security.cert.CertificateException) IdentityUnmarshallingException(org.wso2.carbon.identity.saml.common.util.exception.IdentityUnmarshallingException) SignatureException(org.opensaml.xmlsec.signature.support.SignatureException) SubjectBuilder(org.opensaml.saml.saml2.core.impl.SubjectBuilder) IdentityProviderManagementException(org.wso2.carbon.idp.mgt.IdentityProviderManagementException) Subject(org.opensaml.saml.saml2.core.Subject) DateTime(org.joda.time.DateTime) DataProvider(org.testng.annotations.DataProvider)

Example 19 with Endpoint

use of org.opensaml.saml.saml2.metadata.Endpoint in project identity-inbound-auth-oauth by wso2-extensions.

the class SAML2BearerGrantHandler method validateConditions.

/**
 * The Assertion MUST contain <Conditions> element with an <AudienceRestriction> element with an <Audience> element
 * containing a URI reference that identifies the authorization server, or the service provider SAML entity of its
 * controlling domain, as an intended audience.  The token endpoint URL of the authorization server MAY be used as
 * an acceptable value for an <Audience> element.  The authorization server MUST verify that
 * it is an intended audience for the Assertion.
 * @param tokReqMsgCtx
 * @param assertion
 * @param identityProvider
 * @param tenantDomain
 * @return
 * @throws IdentityOAuth2Exception
 */
private void validateConditions(OAuthTokenReqMessageContext tokReqMsgCtx, Assertion assertion, IdentityProvider identityProvider, String tenantDomain) throws IdentityOAuth2Exception {
    Conditions conditions = assertion.getConditions();
    if (conditions != null) {
        String tokenEndpointAlias = getTokenEPAlias(assertion, identityProvider, tenantDomain);
        validateAudience(identityProvider, conditions, tokenEndpointAlias, tenantDomain);
    } else {
        throw new IdentityOAuth2Exception("SAML Assertion doesn't contain Conditions");
    }
}
Also used : IdentityOAuth2Exception(org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception) Conditions(org.opensaml.saml.saml2.core.Conditions)

Example 20 with Endpoint

use of org.opensaml.saml.saml2.metadata.Endpoint in project cas by apereo.

the class SamlIdPInitiatedProfileHandlerController method handleIdPInitiatedSsoRequest.

/**
 * Handle idp initiated sso requests.
 * 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.
 *
 * @param response the response
 * @param request  the request
 * @return the model and view
 * @throws Exception the exception
 */
@GetMapping(path = SamlIdPConstants.ENDPOINT_SAML2_IDP_INIT_PROFILE_SSO)
protected ModelAndView handleIdPInitiatedSsoRequest(final HttpServletResponse response, final HttpServletRequest request) throws Exception {
    val providerId = request.getParameter(SamlIdPConstants.PROVIDER_ID);
    if (StringUtils.isBlank(providerId)) {
        LOGGER.warn("No providerId parameter given in unsolicited SSO authentication request.");
        throw new MessageDecodingException("Missing providerId");
    }
    val registeredService = verifySamlRegisteredService(providerId);
    val adaptor = getSamlMetadataFacadeFor(registeredService, providerId);
    if (adaptor.isEmpty()) {
        throw new UnauthorizedServiceException(UnauthorizedServiceException.CODE_UNAUTHZ_SERVICE, "Cannot find metadata linked to " + providerId);
    }
    var shire = request.getParameter(SamlIdPConstants.SHIRE);
    val facade = adaptor.get();
    if (StringUtils.isBlank(shire)) {
        LOGGER.info("Resolving service provider assertion consumer service URL for [{}] and binding [{}]", providerId, SAMLConstants.SAML2_POST_BINDING_URI);
        val acs = facade.getAssertionConsumerService(SAMLConstants.SAML2_POST_BINDING_URI);
        shire = acs != null ? StringUtils.isBlank(acs.getResponseLocation()) ? acs.getLocation() : acs.getResponseLocation() : null;
    }
    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");
    }
    val target = request.getParameter(SamlIdPConstants.TARGET);
    val time = request.getParameter(SamlIdPConstants.TIME);
    val builder = (SAMLObjectBuilder) getConfigurationContext().getOpenSamlConfigBean().getBuilderFactory().getBuilder(AuthnRequest.DEFAULT_ELEMENT_NAME);
    val authnRequest = (AuthnRequest) builder.buildObject();
    authnRequest.setAssertionConsumerServiceURL(shire);
    val isBuilder = (SAMLObjectBuilder) getConfigurationContext().getOpenSamlConfigBean().getBuilderFactory().getBuilder(Issuer.DEFAULT_ELEMENT_NAME);
    val issuer = (Issuer) isBuilder.buildObject();
    issuer.setValue(providerId);
    authnRequest.setIssuer(issuer);
    authnRequest.setProtocolBinding(SAMLConstants.SAML2_POST_BINDING_URI);
    val pBuilder = (SAMLObjectBuilder) getConfigurationContext().getOpenSamlConfigBean().getBuilderFactory().getBuilder(NameIDPolicy.DEFAULT_ELEMENT_NAME);
    val nameIDPolicy = (NameIDPolicy) pBuilder.buildObject();
    nameIDPolicy.setAllowCreate(Boolean.TRUE);
    authnRequest.setNameIDPolicy(nameIDPolicy);
    if (NumberUtils.isCreatable(time)) {
        authnRequest.setIssueInstant(Instant.ofEpochMilli(Long.parseLong(time)));
    } else {
        authnRequest.setIssueInstant(ZonedDateTime.now(ZoneOffset.UTC).toInstant());
    }
    authnRequest.setForceAuthn(Boolean.FALSE);
    if (StringUtils.isNotBlank(target)) {
        request.setAttribute(SamlProtocolConstants.PARAMETER_SAML_RELAY_STATE, target);
    }
    val ctx = new MessageContext();
    if (facade.isAuthnRequestsSigned() || registeredService.isSignUnsolicitedAuthnRequest()) {
        getConfigurationContext().getSamlObjectSigner().encode(authnRequest, registeredService, facade, response, request, SAMLConstants.SAML2_POST_BINDING_URI, authnRequest, ctx);
    }
    ctx.setMessage(authnRequest);
    val bindingContext = ctx.getSubcontext(SAMLBindingContext.class, true);
    Objects.requireNonNull(bindingContext).setHasBindingSignature(false);
    SAMLBindingSupport.setRelayState(ctx, target);
    val pair = Pair.<RequestAbstractType, MessageContext>of(authnRequest, ctx);
    val modelAndView = initiateAuthenticationRequest(pair, response, request);
    if (modelAndView != null) {
        val view = (RedirectView) modelAndView.getView();
        val urlBuilder = new URIBuilder(Objects.requireNonNull(view).getUrl());
        val paramNames = request.getParameterNames();
        while (paramNames.hasMoreElements()) {
            val parameterName = paramNames.nextElement();
            if (!parameterName.equalsIgnoreCase(SamlIdPConstants.TARGET) && !parameterName.equalsIgnoreCase(SamlIdPConstants.TIME) && !parameterName.equalsIgnoreCase(SamlIdPConstants.SHIRE) && !parameterName.equalsIgnoreCase(SamlIdPConstants.PROVIDER_ID)) {
                urlBuilder.addParameter(parameterName, request.getParameter(parameterName));
            }
        }
        view.setUrl(urlBuilder.build().toString());
    }
    return modelAndView;
}
Also used : lombok.val(lombok.val) MessageDecodingException(org.opensaml.messaging.decoder.MessageDecodingException) AuthnRequest(org.opensaml.saml.saml2.core.AuthnRequest) SAMLObjectBuilder(org.opensaml.saml.common.SAMLObjectBuilder) Issuer(org.opensaml.saml.saml2.core.Issuer) NameIDPolicy(org.opensaml.saml.saml2.core.NameIDPolicy) RequestAbstractType(org.opensaml.saml.saml2.core.RequestAbstractType) RedirectView(org.springframework.web.servlet.view.RedirectView) UnauthorizedServiceException(org.apereo.cas.services.UnauthorizedServiceException) MessageContext(org.opensaml.messaging.context.MessageContext) URIBuilder(org.apache.http.client.utils.URIBuilder) GetMapping(org.springframework.web.bind.annotation.GetMapping)

Aggregations

Endpoint (org.opensaml.saml.saml2.metadata.Endpoint)6 SAMLObject (org.opensaml.saml.common.SAMLObject)5 AuthnRequest (org.opensaml.saml.saml2.core.AuthnRequest)5 RequestAbstractType (org.opensaml.saml.saml2.core.RequestAbstractType)5 lombok.val (lombok.val)4 MessageDecodingException (org.opensaml.messaging.decoder.MessageDecodingException)4 MessageEncodingException (org.opensaml.messaging.encoder.MessageEncodingException)4 StatusResponseType (org.opensaml.saml.saml2.core.StatusResponseType)4 ArrayList (java.util.ArrayList)3 UnauthorizedServiceException (org.apereo.cas.services.UnauthorizedServiceException)3 DateTime (org.joda.time.DateTime)3 SignableSAMLObject (org.opensaml.saml.common.SignableSAMLObject)3 AssertionConsumerService (org.opensaml.saml.saml2.metadata.AssertionConsumerService)3 IDPSSODescriptor (org.opensaml.saml.saml2.metadata.IDPSSODescriptor)3 Endpoint (org.opensaml.saml2.metadata.Endpoint)3 MalformedURLException (java.net.MalformedURLException)2 URI (java.net.URI)2 URISyntaxException (java.net.URISyntaxException)2 HashMap (java.util.HashMap)2 Nonnull (javax.annotation.Nonnull)2