<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:security="http://www.springframework.org/schema/security"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:util="http://www.springframework.org/schema/util"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
              http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.1.xsd">

    <!-- Enable auto-wiring -->
    <context:annotation-config/>

    <!-- Scan for auto-wiring classes in spring saml packages -->
    <context:component-scan base-package="org.springframework.security.saml"/>

    <util:properties id="properties" location="/WEB-INF/sp.properties" />

    <context:property-placeholder properties-ref="properties" />

    <!-- Unsecured pages -->
    <security:http security="none" pattern="/favicon.ico"/>
    <security:http security="none" pattern="/images/**"/>
    <security:http security="none" pattern="/css/**"/>
    <security:http security="none" pattern="/logout.jsp"/>

    <!-- Security for the administration UI -->
    <security:http pattern="/saml/web/**" access-denied-page="/saml/web/metadata/login">
        <security:form-login login-processing-url="/saml/web/login" login-page="/saml/web/metadata/login"
                             default-target-url="/saml/web/metadata"/>
        <security:intercept-url pattern="/saml/web/metadata/login" access="IS_AUTHENTICATED_ANONYMOUSLY"/>
        <security:intercept-url pattern="/saml/web/**" access="ROLE_ADMIN"/>
        <security:custom-filter before="FIRST" ref="metadataGeneratorFilter"/>
    </security:http>

    <!-- Secured pages with SAML as entry point -->
    <security:http entry-point-ref="samlEntryPoint">
        <security:intercept-url pattern="/**" access="IS_AUTHENTICATED_FULLY"/>
        <security:custom-filter before="FIRST" ref="metadataGeneratorFilter"/>
        <security:custom-filter after="BASIC_AUTH_FILTER" ref="samlFilter"/>
    </security:http>

    <!-- Filters for processing of SAML messages -->
    <bean id="samlFilter" class="org.springframework.security.web.FilterChainProxy">
        <security:filter-chain-map request-matcher="ant">
            <security:filter-chain pattern="/saml/login/**" filters="samlEntryPoint"/>
            <security:filter-chain pattern="/saml/logout/**" filters="samlLogoutFilter"/>
            <security:filter-chain pattern="/saml/metadata/**" filters="metadataDisplayFilter"/>
            <security:filter-chain pattern="/saml/SSO/**" filters="samlWebSSOProcessingFilter"/>
            <security:filter-chain pattern="/saml/SSOHoK/**" filters="samlWebSSOHoKProcessingFilter"/>
            <security:filter-chain pattern="/saml/SingleLogout/**" filters="samlLogoutProcessingFilter"/>
            <security:filter-chain pattern="/saml/discovery/**" filters="samlIDPDiscovery"/>
        </security:filter-chain-map>
    </bean>

    <!-- Handler deciding where to redirect user after successful login -->
    <bean id="successRedirectHandler"
          class="org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler">
        <property name="defaultTargetUrl" value="/"/>
    </bean>
    <!--
    Use the following for interpreting RelayState coming from unsolicited response as redirect URL:
    <bean id="successRedirectHandler" class="org.springframework.security.saml.SAMLRelayStateSuccessHandler">
       <property name="defaultTargetUrl" value="/" />
    </bean>
    -->

    <!-- Handler deciding where to redirect user after failed login -->
    <bean id="failureRedirectHandler"
          class="org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler">
        <property name="useForward" value="true"/>
        <property name="defaultFailureUrl" value="/error.jsp"/>
    </bean>

    <!-- Handler for successful logout -->
    <bean id="successLogoutHandler"
          class="org.springframework.security.web.authentication.logout.SimpleUrlLogoutSuccessHandler">
        <property name="defaultTargetUrl" value="/logout.jsp"/>
    </bean>

    <security:authentication-manager alias="authenticationManager">
        <!-- Register authentication manager for SAML provider -->
        <security:authentication-provider ref="samlAuthenticationProvider"/>
        <!-- Register authentication manager for administration UI -->
        <security:authentication-provider>
            <security:user-service id="adminInterfaceService">
                <security:user name="admin" password="admin" authorities="ROLE_ADMIN"/>
            </security:user-service>
        </security:authentication-provider>
    </security:authentication-manager>


    <!-- Logger for SAML messages and events -->
    <bean id="samlLogger" class="org.springframework.security.saml.log.SAMLDefaultLogger"/>

    <!-- Central storage of cryptographic keys -->
    <bean id="keyManager" class="org.springframework.security.saml.key.JKSKeyManager">
        <constructor-arg value="classpath:security/samlKeystore.jks"/>
        <constructor-arg type="java.lang.String" value="nalle123"/>
        <constructor-arg>
            <map>
                <entry key="apollo" value="nalle123"/>
            </map>
        </constructor-arg>
        <constructor-arg type="java.lang.String" value="apollo"/>
    </bean>

    <!-- Entry point to initialize authentication, default values taken from properties file -->
    <bean id="samlEntryPoint" class="org.springframework.security.saml.SAMLEntryPoint">
        <property name="defaultProfileOptions">
            <bean class="org.springframework.security.saml.websso.WebSSOProfileOptions">
                <property name="includeScoping" value="false"/>

                <!--
                <property name="forceAuthN" value="true" />
                <property name="assertionConsumerIndex" value="0" />
                -->

                
                <property name="authnContexts">
                    <list>
                        <value>https://refeds.org/profile/mfa</value>
                    </list>
                </property>
                
                <property name="allowCreate" value="true" />
                <property name="authnContextComparison" value="EXACT" />
            </bean>
        </property>
    </bean>

    <!-- IDP Discovery Service -->
    <bean id="samlIDPDiscovery" class="org.springframework.security.saml.SAMLDiscovery">
        <property name="idpSelectionPath" value="/WEB-INF/security/idpSelection.jsp"/>
    </bean>

    <!-- Filter automatically generates default SP metadata -->
    <bean id="metadataGeneratorFilter" class="org.springframework.security.saml.metadata.MetadataGeneratorFilter">
        <constructor-arg>
            <bean class="org.springframework.security.saml.metadata.MetadataGenerator">
                <property name="extendedMetadata">
                    <bean class="org.springframework.security.saml.metadata.ExtendedMetadata">
                        <property name="idpDiscoveryEnabled" value="true"/>
                    </bean>
                </property>
            </bean>
        </constructor-arg>
    </bean>

    <!-- The filter is waiting for connections on URL suffixed with filterSuffix and presents SP metadata there -->
    <bean id="metadataDisplayFilter" class="org.springframework.security.saml.metadata.MetadataDisplayFilter"/>

    <!-- Configure HTTP Client to accept certificates from the keystore for HTTPS verification -->

    <bean class="org.springframework.security.saml.trust.httpclient.TLSProtocolConfigurer">
        <property name="sslHostnameVerification" value="allowAll"/>
    </bean>


    <!-- IDP Metadata configuration - paths to metadata of IDPs in circle of trust is here -->
    <bean id="metadata" class="org.springframework.security.saml.metadata.CachingMetadataManager">
        <constructor-arg>
            <list>
                <!-- Example of classpath metadata with Extended Metadata -->
                <bean class="org.springframework.security.saml.metadata.ExtendedMetadataDelegate">
                    <constructor-arg>
                        <bean class="org.opensaml.saml2.metadata.provider.ResourceBackedMetadataProvider">
                            <constructor-arg>
                                <bean class="java.util.Timer"/>
                            </constructor-arg>
                            <constructor-arg>
                                <bean class="org.opensaml.util.resource.FilesystemResource">
                                    <constructor-arg value="${idp.metadata}"/>
                                </bean>
                            </constructor-arg>
                            <property name="parserPool" ref="parserPool"/>
                        </bean>
                    </constructor-arg>
                    <constructor-arg>
                        <bean class="org.springframework.security.saml.metadata.ExtendedMetadata">
                        </bean>
                    </constructor-arg>
                </bean>
                <bean class="org.springframework.security.saml.metadata.ExtendedMetadataDelegate">
                    <constructor-arg>
                        <bean class="org.opensaml.saml2.metadata.provider.ResourceBackedMetadataProvider">
                            <constructor-arg>
                                <bean class="java.util.Timer"/>
                            </constructor-arg>
                            <constructor-arg>
                                <bean class="org.opensaml.util.resource.ClasspathResource">
                                    <constructor-arg value="${sp.metadata}"/>
                                </bean>
                            </constructor-arg>
                            <property name="parserPool" ref="parserPool"/>
                        </bean>
                    </constructor-arg>
                    <constructor-arg>
                        <bean class="org.springframework.security.saml.metadata.ExtendedMetadata">
                            <property name="local" value="true"/>
                            <property name="securityProfile" value="metaiop"/>
                            <property name="sslSecurityProfile" value="pkix"/>
                            <property name="sslHostnameVerification" value="allowAll"/>
                            <property name="signMetadata" value="false"/>
                            <property name="signingKey" value="apollo"/>
                            <property name="encryptionKey" value="apollo"/>
                            <property name="requireArtifactResolveSigned" value="true"/>
                            <property name="requireLogoutRequestSigned" value="true"/>
                            <property name="requireLogoutResponseSigned" value="false"/>
                            <property name="idpDiscoveryEnabled" value="true"/>
                            <property name="idpDiscoveryURL" value="${host.name}/sp/saml/discovery"/>
                            <property name="idpDiscoveryResponseURL" value="${host.name}/sp/saml/login?disco=true"/>
                            <property name="ecpEnabled" value="true" />
                        </bean>
                    </constructor-arg>
                </bean>
            </list>
        </constructor-arg>
        <!-- OPTIONAL used when one of the metadata files contains information about this service provider -->
        <!-- <property name="hostedSPName" value=""/> -->
        <!-- OPTIONAL property: can tell the system which IDP should be used for authenticating user by default. -->
        <!-- <property name="defaultIDP" value="http://localhost:8080/opensso"/> -->
    </bean>

    <!-- SAML Authentication Provider responsible for validating of received SAML messages -->
    <bean id="samlAuthenticationProvider" class="org.springframework.security.saml.SAMLAuthenticationProvider">
        <!-- OPTIONAL property: can be used to store/load user data after login -->
        <!--
        <property name="userDetails" ref="bean" />
        -->
    </bean>

    <!-- Provider of default SAML Context -->

    <bean id="contextProvider" class="org.springframework.security.saml.context.SAMLContextProviderImpl">
        <property name="storageFactory">
            <bean class="org.springframework.security.saml.storage.EmptyStorageFactory" />
        </property>
    </bean>

    <!-- Processing filter for WebSSO profile messages -->
    <bean id="samlWebSSOProcessingFilter" class="org.springframework.security.saml.SAMLProcessingFilter">
        <property name="authenticationManager" ref="authenticationManager"/>
        <property name="authenticationSuccessHandler" ref="successRedirectHandler"/>
        <property name="authenticationFailureHandler" ref="failureRedirectHandler"/>
    </bean>

    <!-- Processing filter for WebSSO Holder-of-Key profile -->
    <bean id="samlWebSSOHoKProcessingFilter" class="org.springframework.security.saml.SAMLWebSSOHoKProcessingFilter">
        <property name="authenticationManager" ref="authenticationManager"/>
        <property name="authenticationSuccessHandler" ref="successRedirectHandler"/>
        <property name="authenticationFailureHandler" ref="failureRedirectHandler"/>
    </bean>

    <!-- Logout handler terminating local session -->
    <bean id="logoutHandler"
          class="org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler">
        <property name="invalidateHttpSession" value="false"/>
    </bean>

    <!-- Override default logout processing filter with the one processing SAML messages -->
    <bean id="samlLogoutFilter" class="org.springframework.security.saml.SAMLLogoutFilter">
        <constructor-arg index="0" ref="successLogoutHandler"/>
        <constructor-arg index="1" ref="logoutHandler"/>
        <constructor-arg index="2" ref="logoutHandler"/>
    </bean>

    <!-- Filter processing incoming logout messages -->
    <!-- First argument determines URL user will be redirected to after successful global logout -->
    <bean id="samlLogoutProcessingFilter" class="org.springframework.security.saml.SAMLLogoutProcessingFilter">
        <constructor-arg index="0" ref="successLogoutHandler"/>
        <constructor-arg index="1" ref="logoutHandler"/>
    </bean>

    <!-- Class loading incoming SAML messages from httpRequest stream -->
    <bean id="processor" class="org.springframework.security.saml.processor.SAMLProcessorImpl">
        <constructor-arg>
            <list>
                <ref bean="redirectBinding"/>
                <ref bean="postBinding"/>
                <ref bean="artifactBinding"/>
                <ref bean="soapBinding"/>
                <ref bean="paosBinding"/>
            </list>
        </constructor-arg>
    </bean>

     <!-- SAML 2.0 WebSSO Assertion Consumer -->
    <bean id="webSSOprofileConsumer" class="org.springframework.security.saml.websso.WebSSOProfileConsumerImpl">
        <property name="responseSkew" value="180"/>
    </bean>

    <!-- SAML 2.0 Holder-of-Key WebSSO Assertion Consumer -->
    <bean id="hokWebSSOprofileConsumer" class="org.springframework.security.saml.websso.WebSSOProfileConsumerHoKImpl"/>

    <!-- SAML 2.0 Web SSO profile -->
    <bean id="webSSOprofile" class="org.springframework.security.saml.websso.WebSSOProfileImpl"/>

    <!-- SAML 2.0 Holder-of-Key Web SSO profile -->
    <bean id="hokWebSSOProfile" class="org.springframework.security.saml.websso.WebSSOProfileConsumerHoKImpl"/>

    <!-- SAML 2.0 ECP profile -->
    <bean id="ecpprofile" class="org.springframework.security.saml.websso.WebSSOProfileECPImpl"/>

    <!-- SAML 2.0 Logout Profile -->
    <bean id="logoutprofile" class="org.springframework.security.saml.websso.SingleLogoutProfileImpl"/>

    <!-- Bindings, encoders and decoders used for creating and parsing messages -->
    <bean id="postBinding" class="org.springframework.security.saml.processor.HTTPPostBinding">
        <constructor-arg ref="parserPool"/>
        <constructor-arg ref="velocityEngine"/>
    </bean>

    <bean id="redirectBinding" class="org.springframework.security.saml.processor.HTTPRedirectDeflateBinding">
        <constructor-arg ref="parserPool"/>
    </bean>

    <bean id="artifactBinding" class="org.springframework.security.saml.processor.HTTPArtifactBinding">
        <constructor-arg ref="parserPool"/>
        <constructor-arg ref="velocityEngine"/>
        <constructor-arg>
            <bean class="org.springframework.security.saml.websso.ArtifactResolutionProfileImpl">
                <constructor-arg>
                    <bean class="org.apache.commons.httpclient.HttpClient">
                        <constructor-arg>
                            <bean class="org.apache.commons.httpclient.MultiThreadedHttpConnectionManager"/>
                        </constructor-arg>
                    </bean>
                </constructor-arg>
                <property name="processor">
                    <bean class="org.springframework.security.saml.processor.SAMLProcessorImpl">
                        <constructor-arg ref="soapBinding"/>
                    </bean>
                </property>
            </bean>
        </constructor-arg>
    </bean>

    <bean id="soapBinding" class="org.springframework.security.saml.processor.HTTPSOAP11Binding">
        <constructor-arg ref="parserPool"/>
    </bean>

    <bean id="paosBinding" class="org.springframework.security.saml.processor.HTTPPAOS11Binding">
        <constructor-arg ref="parserPool"/>
    </bean>

    <!-- Initialization of OpenSAML library-->
    <bean class="org.springframework.security.saml.SAMLBootstrap"/>

    <!-- Initialization of the velocity engine -->
    <bean id="velocityEngine" class="org.springframework.security.saml.util.VelocityFactory"
          factory-method="getEngine"/>

    <!-- XML parser pool needed for OpenSAML parsing -->
    <bean id="parserPool" class="org.opensaml.xml.parse.StaticBasicParserPool" init-method="initialize">
        <property name="builderFeatures">
            <map>
                <entry key="http://apache.org/xml/features/dom/defer-node-expansion" value="false"/>
            </map>
        </property>
    </bean>

    <bean id="parserPoolHolder" class="org.springframework.security.saml.parser.ParserPoolHolder"/>

</beans>
