Example usage for org.joda.time DateTime DateTime

List of usage examples for org.joda.time DateTime DateTime

Introduction

In this page you can find the example usage for org.joda.time DateTime DateTime.

Prototype

public DateTime() 

Source Link

Document

Constructs an instance set to the current system millisecond time using ISOChronology in the default time zone.

Usage

From source file:at.gv.egovernment.moa.id.configuration.auth.pvp2.servlets.Authenticate.java

License:EUPL

protected void process(HttpServletRequest request, HttpServletResponse response,
        Map<String, String> legacyParameter) throws ServletException, IOException {
    try {/*from  w  ww  .  j a v a  2  s  .c o m*/

        ConfigurationProvider config = ConfigurationProvider.getInstance();
        config.initializePVP2Login();

        AuthnRequest authReq = SAML2Utils.createSAMLObject(AuthnRequest.class);
        SecureRandomIdentifierGenerator gen = new SecureRandomIdentifierGenerator();
        authReq.setID(gen.generateIdentifier());

        HttpSession session = request.getSession();
        if (session != null) {
            session.setAttribute(Constants.SESSION_PVP2REQUESTID, authReq.getID());
        }

        authReq.setAssertionConsumerServiceIndex(0);
        authReq.setAttributeConsumingServiceIndex(0);
        authReq.setIssueInstant(new DateTime());
        Subject subject = SAML2Utils.createSAMLObject(Subject.class);
        NameID name = SAML2Utils.createSAMLObject(NameID.class);
        Issuer issuer = SAML2Utils.createSAMLObject(Issuer.class);

        String serviceURL = config.getPublicUrlPreFix(request);
        if (!serviceURL.endsWith("/"))
            serviceURL = serviceURL + "/";
        name.setValue(serviceURL);
        issuer.setValue(serviceURL);

        subject.setNameID(name);
        authReq.setSubject(subject);
        issuer.setFormat(NameIDType.ENTITY);
        authReq.setIssuer(issuer);
        NameIDPolicy policy = SAML2Utils.createSAMLObject(NameIDPolicy.class);
        policy.setAllowCreate(true);
        policy.setFormat(NameID.PERSISTENT);
        authReq.setNameIDPolicy(policy);

        String entityname = config.getPVP2IDPMetadataEntityName();
        if (MiscUtil.isEmpty(entityname)) {
            log.info("No IDP EntityName configurated");
            throw new ConfigurationException("No IDP EntityName configurated");
        }

        HTTPMetadataProvider idpmetadata = config.getMetaDataProvier();
        EntityDescriptor idpEntity = idpmetadata.getEntityDescriptor(entityname);
        if (idpEntity == null) {
            log.info("IDP EntityName is not found in IDP Metadata");
            throw new ConfigurationException("IDP EntityName is not found in IDP Metadata");
        }

        SingleSignOnService redirectEndpoint = null;
        for (SingleSignOnService sss : idpEntity.getIDPSSODescriptor(SAMLConstants.SAML20P_NS)
                .getSingleSignOnServices()) {

            //Get the service address for the binding you wish to use
            if (sss.getBinding().equals(SAMLConstants.SAML2_POST_BINDING_URI)) {
                redirectEndpoint = sss;
            }
        }

        authReq.setDestination(redirectEndpoint.getLocation());

        RequestedAuthnContext reqAuthContext = SAML2Utils.createSAMLObject(RequestedAuthnContext.class);

        AuthnContextClassRef authnClassRef = SAML2Utils.createSAMLObject(AuthnContextClassRef.class);

        authnClassRef.setAuthnContextClassRef("http://www.stork.gov.eu/1.0/citizenQAALevel/4");

        reqAuthContext.setComparison(AuthnContextComparisonTypeEnumeration.MINIMUM);

        reqAuthContext.getAuthnContextClassRefs().add(authnClassRef);

        authReq.setRequestedAuthnContext(reqAuthContext);

        //sign Message
        X509Credential authcredential = PVP2Utils.signMessage((AbstractSignableXMLObject) authReq, config);

        //encode message
        PVP2Utils.postBindingEncoder(request, response, authReq, authcredential, redirectEndpoint.getLocation(),
                null);

    } catch (Exception e) {
        log.warn("Authentication Request can not be generated", e);
        throw new ServletException("Authentication Request can not be generated.", e);
    }
}

From source file:at.gv.egovernment.moa.id.configuration.auth.pvp2.servlets.BuildMetadata.java

License:EUPL

/**
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
 *      response)//from  w  w w . j ava 2  s .  com
 */
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {
        ConfigurationProvider config = ConfigurationProvider.getInstance();

        //config.initializePVP2Login();

        SecureRandomIdentifierGenerator idGen = new SecureRandomIdentifierGenerator();

        EntitiesDescriptor spEntitiesDescriptor = SAML2Utils.createSAMLObject(EntitiesDescriptor.class);

        DateTime date = new DateTime();
        spEntitiesDescriptor.setValidUntil(date.plusHours(VALIDUNTIL_IN_HOURS));

        String name = config.getPVP2MetadataEntitiesName();
        if (MiscUtil.isEmpty(name)) {
            log.info("NO Metadata EntitiesName configurated");
            throw new ConfigurationException("NO Metadata EntitiesName configurated");
        }

        spEntitiesDescriptor.setName(name);
        spEntitiesDescriptor.setID(idGen.generateIdentifier());

        EntityDescriptor spEntityDescriptor = SAML2Utils.createSAMLObject(EntityDescriptor.class);

        spEntityDescriptor.setValidUntil(date.plusDays(VALIDUNTIL_IN_HOURS));

        spEntitiesDescriptor.getEntityDescriptors().add(spEntityDescriptor);

        String serviceURL = config.getPublicUrlPreFix(request);
        if (!serviceURL.endsWith("/"))
            serviceURL = serviceURL + "/";

        log.debug("Set OnlineApplicationURL to " + serviceURL);
        spEntityDescriptor.setEntityID(serviceURL);

        SPSSODescriptor spSSODescriptor = SAML2Utils.createSAMLObject(SPSSODescriptor.class);

        spSSODescriptor.setAuthnRequestsSigned(true);
        spSSODescriptor.setWantAssertionsSigned(true);

        X509KeyInfoGeneratorFactory keyInfoFactory = new X509KeyInfoGeneratorFactory();
        keyInfoFactory.setEmitEntityCertificate(true);
        KeyInfoGenerator keyInfoGenerator = keyInfoFactory.newInstance();

        KeyStore keyStore = config.getPVP2KeyStore();

        X509Credential signingcredential = new KeyStoreX509CredentialAdapter(keyStore,
                config.getPVP2KeystoreMetadataKeyAlias(),
                config.getPVP2KeystoreMetadataKeyPassword().toCharArray());

        log.debug("Set Metadata key information");
        //Set MetaData Signing key
        KeyDescriptor entitiesSignKeyDescriptor = SAML2Utils.createSAMLObject(KeyDescriptor.class);
        entitiesSignKeyDescriptor.setUse(UsageType.SIGNING);
        entitiesSignKeyDescriptor.setKeyInfo(keyInfoGenerator.generate(signingcredential));
        Signature entitiesSignature = getSignature(signingcredential);
        spEntitiesDescriptor.setSignature(entitiesSignature);

        //Set AuthRequest Signing certificate
        X509Credential authcredential = new KeyStoreX509CredentialAdapter(keyStore,
                config.getPVP2KeystoreAuthRequestKeyAlias(),
                config.getPVP2KeystoreAuthRequestKeyPassword().toCharArray());
        KeyDescriptor signKeyDescriptor = SAML2Utils.createSAMLObject(KeyDescriptor.class);
        signKeyDescriptor.setUse(UsageType.SIGNING);
        signKeyDescriptor.setKeyInfo(keyInfoGenerator.generate(authcredential));
        spSSODescriptor.getKeyDescriptors().add(signKeyDescriptor);

        //set AuthRequest encryption certificate
        if (MiscUtil.isNotEmpty(config.getPVP2KeystoreAuthRequestEncryptionKeyAlias())) {
            X509Credential authEncCredential = new KeyStoreX509CredentialAdapter(keyStore,
                    config.getPVP2KeystoreAuthRequestEncryptionKeyAlias(),
                    config.getPVP2KeystoreAuthRequestEncryptionKeyPassword().toCharArray());
            KeyDescriptor encryKeyDescriptor = SAML2Utils.createSAMLObject(KeyDescriptor.class);
            encryKeyDescriptor.setUse(UsageType.ENCRYPTION);
            encryKeyDescriptor.setKeyInfo(keyInfoGenerator.generate(authEncCredential));
            spSSODescriptor.getKeyDescriptors().add(encryKeyDescriptor);

        } else {
            log.warn("No Assertion Encryption-Key defined. This setting is not recommended!");

        }

        NameIDFormat persistentnameIDFormat = SAML2Utils.createSAMLObject(NameIDFormat.class);
        persistentnameIDFormat.setFormat(NameIDType.PERSISTENT);

        spSSODescriptor.getNameIDFormats().add(persistentnameIDFormat);

        NameIDFormat transientnameIDFormat = SAML2Utils.createSAMLObject(NameIDFormat.class);
        transientnameIDFormat.setFormat(NameIDType.TRANSIENT);

        spSSODescriptor.getNameIDFormats().add(transientnameIDFormat);

        NameIDFormat unspecifiednameIDFormat = SAML2Utils.createSAMLObject(NameIDFormat.class);
        unspecifiednameIDFormat.setFormat(NameIDType.UNSPECIFIED);

        spSSODescriptor.getNameIDFormats().add(unspecifiednameIDFormat);

        AssertionConsumerService postassertionConsumerService = SAML2Utils
                .createSAMLObject(AssertionConsumerService.class);

        postassertionConsumerService.setIndex(0);
        postassertionConsumerService.setBinding(SAMLConstants.SAML2_POST_BINDING_URI);
        postassertionConsumerService.setLocation(serviceURL + Constants.SERVLET_PVP2ASSERTION);

        spSSODescriptor.getAssertionConsumerServices().add(postassertionConsumerService);

        //add SLO services
        SingleLogoutService postBindingService = SAML2Utils.createSAMLObject(SingleLogoutService.class);
        postBindingService.setBinding(SAMLConstants.SAML2_POST_BINDING_URI);
        postBindingService.setLocation(serviceURL + Constants.SERVLET_SLO_FRONT);
        spSSODescriptor.getSingleLogoutServices().add(postBindingService);

        SingleLogoutService redirectBindingService = SAML2Utils.createSAMLObject(SingleLogoutService.class);
        redirectBindingService.setBinding(SAMLConstants.SAML2_REDIRECT_BINDING_URI);
        redirectBindingService.setLocation(serviceURL + Constants.SERVLET_SLO_FRONT);
        spSSODescriptor.getSingleLogoutServices().add(redirectBindingService);

        SingleLogoutService soapBindingService = SAML2Utils.createSAMLObject(SingleLogoutService.class);
        soapBindingService.setBinding(SAMLConstants.SAML2_SOAP11_BINDING_URI);
        soapBindingService.setLocation(serviceURL + Constants.SERVLET_SLO_BACK);
        spSSODescriptor.getSingleLogoutServices().add(soapBindingService);

        spSSODescriptor.addSupportedProtocol(SAMLConstants.SAML20P_NS);

        spEntityDescriptor.getRoleDescriptors().add(spSSODescriptor);

        spSSODescriptor.setWantAssertionsSigned(true);
        spSSODescriptor.setAuthnRequestsSigned(true);

        AttributeConsumingService attributeService = SAML2Utils
                .createSAMLObject(AttributeConsumingService.class);

        attributeService.setIndex(0);
        attributeService.setIsDefault(true);
        ServiceName serviceName = SAML2Utils.createSAMLObject(ServiceName.class);
        serviceName.setName(new LocalizedString("Default Service", "de"));
        attributeService.getNames().add(serviceName);

        attributeService.getRequestAttributes().addAll(AttributeListBuilder.getRequestedAttributes());

        spSSODescriptor.getAttributeConsumingServices().add(attributeService);

        DocumentBuilder builder;
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

        builder = factory.newDocumentBuilder();
        Document document = builder.newDocument();
        Marshaller out = Configuration.getMarshallerFactory().getMarshaller(spEntitiesDescriptor);
        out.marshall(spEntitiesDescriptor, document);

        Signer.signObject(entitiesSignature);

        Transformer transformer = TransformerFactory.newInstance().newTransformer();

        StringWriter sw = new StringWriter();
        StreamResult sr = new StreamResult(sw);
        DOMSource source = new DOMSource(document);
        transformer.transform(source, sr);
        sw.close();

        String metadataXML = sw.toString();

        response.setContentType("text/xml");
        response.getOutputStream().write(metadataXML.getBytes());

        response.getOutputStream().close();

    } catch (ConfigurationException e) {
        log.warn("Configuration can not be loaded.", e);
        throw new ServletException("MetaData can not be created. Look into LogFiles for more details.");

    } catch (NoSuchAlgorithmException e) {
        log.warn("Requested Algorithm could not found.", e);
        throw new ServletException("MetaData can not be created. Look into LogFiles for more details.");

    } catch (KeyStoreException e) {
        log.warn("Requested KeyStoreType is not implemented.", e);
        throw new ServletException("MetaData can not be created. Look into LogFiles for more details.");

    } catch (CertificateException e) {
        log.warn("KeyStore can not be opend or userd.", e);
        throw new ServletException("MetaData can not be created. Look into LogFiles for more details.");

    } catch (SecurityException e) {
        log.warn("KeyStore can not be opend or used", e);
        throw new ServletException("MetaData can not be created. Look into LogFiles for more details.");

    } catch (ParserConfigurationException e) {
        log.warn("PVP2 Metadata createn error", e);
        throw new ServletException("MetaData can not be created. Look into LogFiles for more details.");

    } catch (MarshallingException e) {
        log.warn("PVP2 Metadata createn error", e);
        throw new ServletException("MetaData can not be created. Look into LogFiles for more details.");

    } catch (SignatureException e) {
        log.warn("PVP2 Metadata can not be signed", e);
        throw new ServletException("MetaData can not be created. Look into LogFiles for more details.");

    } catch (TransformerConfigurationException e) {
        log.warn("PVP2 Metadata createn error", e);
        throw new ServletException("MetaData can not be created. Look into LogFiles for more details.");

    } catch (TransformerFactoryConfigurationError e) {
        log.warn("PVP2 Metadata createn error", e);
        throw new ServletException("MetaData can not be created. Look into LogFiles for more details.");

    } catch (TransformerException e) {
        log.warn("PVP2 Metadata createn error", e);
        throw new ServletException("MetaData can not be created. Look into LogFiles for more details.");
    }

    catch (Exception e) {
        log.warn("Unspecific PVP2 Metadata createn error", e);
        throw new ServletException("MetaData can not be created. Look into LogFiles for more details.");
    }

}

From source file:at.gv.egovernment.moa.id.configuration.auth.pvp2.servlets.SLOBasicServlet.java

License:EUPL

protected LogoutRequest createLogOutRequest(String nameID, String nameIDFormat, HttpServletRequest request)
        throws SLOException {
    try {/*from  w ww .j  a v  a 2s .  c o  m*/
        LogoutRequest sloReq = SAML2Utils.createSAMLObject(LogoutRequest.class);
        SecureRandomIdentifierGenerator gen = new SecureRandomIdentifierGenerator();
        sloReq.setID(gen.generateIdentifier());
        sloReq.setIssueInstant(new DateTime());
        NameID name = SAML2Utils.createSAMLObject(NameID.class);
        Issuer issuer = SAML2Utils.createSAMLObject(Issuer.class);

        String serviceURL = config.getPublicUrlPreFix(request);
        if (!serviceURL.endsWith("/"))
            serviceURL = serviceURL + "/";
        name.setValue(serviceURL);
        issuer.setValue(serviceURL);
        issuer.setFormat(NameIDType.ENTITY);
        sloReq.setIssuer(issuer);

        NameID userNameID = SAML2Utils.createSAMLObject(NameID.class);
        sloReq.setNameID(userNameID);
        userNameID.setFormat(nameIDFormat);
        userNameID.setValue(nameID);

        return sloReq;

    } catch (NoSuchAlgorithmException e) {
        log.warn("Single LogOut request createn FAILED. ", e);
        throw new SLOException();

    }

}

From source file:at.gv.egovernment.moa.id.configuration.auth.pvp2.servlets.SLOBasicServlet.java

License:EUPL

private LogoutResponse createSLOResponse(LogoutRequest sloReq, String statusCodeURI, HttpServletRequest request)
        throws NoSuchAlgorithmException {
    LogoutResponse sloResp = SAML2Utils.createSAMLObject(LogoutResponse.class);
    SecureRandomIdentifierGenerator gen = new SecureRandomIdentifierGenerator();
    sloResp.setID(gen.generateIdentifier());
    sloResp.setInResponseTo(sloReq.getID());
    sloResp.setIssueInstant(new DateTime());
    NameID name = SAML2Utils.createSAMLObject(NameID.class);
    Issuer issuer = SAML2Utils.createSAMLObject(Issuer.class);

    String serviceURL = config.getPublicUrlPreFix(request);
    if (!serviceURL.endsWith("/"))
        serviceURL = serviceURL + "/";
    name.setValue(serviceURL);/*  w ww .  j ava2 s . c  o m*/
    issuer.setValue(serviceURL);
    issuer.setFormat(NameIDType.ENTITY);
    sloResp.setIssuer(issuer);

    Status status = SAML2Utils.createSAMLObject(Status.class);
    sloResp.setStatus(status);
    StatusCode statusCode = SAML2Utils.createSAMLObject(StatusCode.class);
    statusCode.setValue(statusCodeURI);
    status.setStatusCode(statusCode);

    return sloResp;
}

From source file:at.gv.egovernment.moa.id.demoOA.servlet.pvp2.Authenticate.java

License:EUPL

protected void process(HttpServletRequest request, HttpServletResponse response,
        Map<String, String> legacyParameter) throws ServletException, IOException {
    try {/*from  w  ww . ja  v  a  2s.  c  o  m*/

        Configuration config = Configuration.getInstance();
        config.initializePVP2Login();

        AuthnRequest authReq = SAML2Utils.createSAMLObject(AuthnRequest.class);
        SecureRandomIdentifierGenerator gen = new SecureRandomIdentifierGenerator();
        authReq.setID(gen.generateIdentifier());

        authReq.setAssertionConsumerServiceIndex(0);
        authReq.setAttributeConsumingServiceIndex(0);

        authReq.setIssueInstant(new DateTime());
        Subject subject = SAML2Utils.createSAMLObject(Subject.class);
        NameID name = SAML2Utils.createSAMLObject(NameID.class);
        Issuer issuer = SAML2Utils.createSAMLObject(Issuer.class);

        String serviceURL = config.getPublicUrlPreFix(request);
        if (!serviceURL.endsWith("/"))
            serviceURL = serviceURL + "/";
        name.setValue(serviceURL);
        issuer.setValue(serviceURL);

        subject.setNameID(name);
        authReq.setSubject(subject);
        issuer.setFormat(NameIDType.ENTITY);
        authReq.setIssuer(issuer);

        NameIDPolicy policy = SAML2Utils.createSAMLObject(NameIDPolicy.class);
        policy.setAllowCreate(true);
        policy.setFormat(NameID.PERSISTENT);
        authReq.setNameIDPolicy(policy);

        String entityname = config.getPVP2IDPMetadataEntityName();
        if (MiscUtil.isEmpty(entityname)) {
            log.info("No IDP EntityName configurated");
            throw new ConfigurationException("No IDP EntityName configurated");
        }

        //get IDP metadata from metadataprovider
        HTTPMetadataProvider idpmetadata = config.getMetaDataProvier();
        EntityDescriptor idpEntity = idpmetadata.getEntityDescriptor(entityname);
        if (idpEntity == null) {
            log.info("IDP EntityName is not found in IDP Metadata");
            throw new ConfigurationException("IDP EntityName is not found in IDP Metadata");
        }

        //select authentication-service url from metadata
        SingleSignOnService redirectEndpoint = null;
        for (SingleSignOnService sss : idpEntity.getIDPSSODescriptor(SAMLConstants.SAML20P_NS)
                .getSingleSignOnServices()) {

            //Get the service address for the binding you wish to use
            if (sss.getBinding().equals(SAMLConstants.SAML2_POST_BINDING_URI)) {
                redirectEndpoint = sss;
            }
        }
        authReq.setDestination(redirectEndpoint.getLocation());

        RequestedAuthnContext reqAuthContext = SAML2Utils.createSAMLObject(RequestedAuthnContext.class);

        AuthnContextClassRef authnClassRef = SAML2Utils.createSAMLObject(AuthnContextClassRef.class);

        authnClassRef.setAuthnContextClassRef("http://www.stork.gov.eu/1.0/citizenQAALevel/4");

        reqAuthContext.setComparison(AuthnContextComparisonTypeEnumeration.MINIMUM);

        reqAuthContext.getAuthnContextClassRefs().add(authnClassRef);

        authReq.setRequestedAuthnContext(reqAuthContext);

        //sign authentication request
        KeyStore keyStore = config.getPVP2KeyStore();
        X509Credential authcredential = new KeyStoreX509CredentialAdapter(keyStore,
                config.getPVP2KeystoreAuthRequestKeyAlias(),
                config.getPVP2KeystoreAuthRequestKeyPassword().toCharArray());

        Signature signer = SAML2Utils.createSAMLObject(Signature.class);
        signer.setSignatureAlgorithm(SignatureConstants.ALGO_ID_SIGNATURE_RSA_SHA1);
        signer.setCanonicalizationAlgorithm(SignatureConstants.ALGO_ID_C14N_EXCL_OMIT_COMMENTS);
        signer.setSigningCredential(authcredential);
        authReq.setSignature(signer);

        //generate Http-POST Binding message
        VelocityEngine engine = new VelocityEngine();
        engine.setProperty(RuntimeConstants.ENCODING_DEFAULT, "UTF-8");
        engine.setProperty(RuntimeConstants.OUTPUT_ENCODING, "UTF-8");
        engine.setProperty(RuntimeConstants.ENCODING_DEFAULT, "UTF-8");
        engine.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
        engine.setProperty("classpath.resource.loader.class",
                "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
        engine.setProperty(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM_CLASS,
                "org.apache.velocity.runtime.log.SimpleLog4JLogSystem");
        engine.init();

        HTTPPostEncoder encoder = new HTTPPostEncoder(engine, "templates/pvp_postbinding_template.html");
        HttpServletResponseAdapter responseAdapter = new HttpServletResponseAdapter(response, true);
        BasicSAMLMessageContext<SAMLObject, SAMLObject, SAMLObject> context = new BasicSAMLMessageContext<SAMLObject, SAMLObject, SAMLObject>();
        SingleSignOnService service = new SingleSignOnServiceBuilder().buildObject();
        service.setBinding("urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST");
        service.setLocation(redirectEndpoint.getLocation());
        ;

        context.setOutboundSAMLMessageSigningCredential(authcredential);
        context.setPeerEntityEndpoint(service);
        context.setOutboundSAMLMessage(authReq);
        context.setOutboundMessageTransport(responseAdapter);

        encoder.encode(context);

    } catch (Exception e) {
        log.warn("Authentication Request can not be generated", e);
        throw new ServletException("Authentication Request can not be generated.", e);
    }
}

From source file:at.gv.egovernment.moa.id.demoOA.servlet.pvp2.BuildMetadata.java

License:EUPL

/**
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
 *      response)//from   w  w  w . j av a  2 s .  c o m
 */
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {
        Configuration config = Configuration.getInstance();

        SecureRandomIdentifierGenerator idGen = new SecureRandomIdentifierGenerator();

        EntitiesDescriptor spEntitiesDescriptor = SAML2Utils.createSAMLObject(EntitiesDescriptor.class);

        DateTime date = new DateTime();
        spEntitiesDescriptor.setValidUntil(date.plusHours(VALIDUNTIL_IN_HOURS));

        String name = config.getPVP2MetadataEntitiesName();
        if (MiscUtil.isEmpty(name)) {
            Logger.info("NO Metadata EntitiesName configurated");
            throw new ConfigurationException("NO Metadata EntitiesName configurated");
        }

        spEntitiesDescriptor.setName(name);
        spEntitiesDescriptor.setID(idGen.generateIdentifier());

        //set period of validity for metadata information
        DateTime validUntil = new DateTime();
        spEntitiesDescriptor.setValidUntil(validUntil.plusDays(7));

        EntityDescriptor spEntityDescriptor = SAML2Utils.createSAMLObject(EntityDescriptor.class);

        spEntityDescriptor.setValidUntil(date.plusDays(VALIDUNTIL_IN_HOURS));

        spEntitiesDescriptor.getEntityDescriptors().add(spEntityDescriptor);

        //set OA-ID (PublicURL Prefix) as identifier
        String serviceURL = config.getPublicUrlPreFix(request);
        if (!serviceURL.endsWith("/"))
            serviceURL = serviceURL + "/";

        Logger.debug("Set OnlineApplicationURL to " + serviceURL);
        spEntityDescriptor.setEntityID(serviceURL);

        SPSSODescriptor spSSODescriptor = SAML2Utils.createSAMLObject(SPSSODescriptor.class);

        spSSODescriptor.setAuthnRequestsSigned(true);
        spSSODescriptor.setWantAssertionsSigned(true);

        X509KeyInfoGeneratorFactory keyInfoFactory = new X509KeyInfoGeneratorFactory();
        keyInfoFactory.setEmitEntityCertificate(true);
        KeyInfoGenerator keyInfoGenerator = keyInfoFactory.newInstance();

        KeyStore keyStore = config.getPVP2KeyStore();

        X509Credential signingcredential = new KeyStoreX509CredentialAdapter(keyStore,
                config.getPVP2KeystoreMetadataKeyAlias(),
                config.getPVP2KeystoreMetadataKeyPassword().toCharArray());

        Logger.debug("Set Metadata key information");
        //Set MetaData Signing key
        KeyDescriptor entitiesSignKeyDescriptor = SAML2Utils.createSAMLObject(KeyDescriptor.class);
        entitiesSignKeyDescriptor.setUse(UsageType.SIGNING);
        entitiesSignKeyDescriptor.setKeyInfo(keyInfoGenerator.generate(signingcredential));
        Signature entitiesSignature = getSignature(signingcredential);
        spEntitiesDescriptor.setSignature(entitiesSignature);

        //Set AuthRequest Signing certificate
        X509Credential authcredential = new KeyStoreX509CredentialAdapter(keyStore,
                config.getPVP2KeystoreAuthRequestKeyAlias(),
                config.getPVP2KeystoreAuthRequestKeyPassword().toCharArray());
        KeyDescriptor signKeyDescriptor = SAML2Utils.createSAMLObject(KeyDescriptor.class);

        signKeyDescriptor.setUse(UsageType.SIGNING);
        signKeyDescriptor.setKeyInfo(keyInfoGenerator.generate(authcredential));

        spSSODescriptor.getKeyDescriptors().add(signKeyDescriptor);

        //set AuthRequest encryption certificate
        if (MiscUtil.isNotEmpty(config.getPVP2KeystoreAuthRequestEncryptionKeyAlias())
                || MiscUtil.isNotEmpty(config.getPVP2KeystoreAuthRequestEncryptionKeyPassword())) {
            X509Credential authEncCredential = new KeyStoreX509CredentialAdapter(keyStore,
                    config.getPVP2KeystoreAuthRequestEncryptionKeyAlias(),
                    config.getPVP2KeystoreAuthRequestEncryptionKeyPassword().toCharArray());
            KeyDescriptor encryKeyDescriptor = SAML2Utils.createSAMLObject(KeyDescriptor.class);
            encryKeyDescriptor.setUse(UsageType.ENCRYPTION);
            encryKeyDescriptor.setKeyInfo(keyInfoGenerator.generate(authEncCredential));

            //set encryption methode
            //            EncryptionMethod encMethode = SAML2Utils.createSAMLObject(EncryptionMethod.class);
            //            encMethode.setAlgorithm(EncryptionConstants.ALGO_ID_BLOCKCIPHER_AES128_GCM);            
            //            encryKeyDescriptor.getEncryptionMethods().add(encMethode);
            //            
            //            EncryptionMethod keyencMethode = SAML2Utils.createSAMLObject(EncryptionMethod.class);
            //            keyencMethode.setAlgorithm(EncryptionConstants.ALGO_ID_KEYTRANSPORT_RSAOAEP);            
            //            encryKeyDescriptor.getEncryptionMethods().add(keyencMethode);

            spSSODescriptor.getKeyDescriptors().add(encryKeyDescriptor);

        } else {
            Logger.warn("No Assertion Encryption-Key defined. This setting is not recommended!");

        }

        NameIDFormat persistentnameIDFormat = SAML2Utils.createSAMLObject(NameIDFormat.class);
        persistentnameIDFormat.setFormat(NameIDType.PERSISTENT);

        spSSODescriptor.getNameIDFormats().add(persistentnameIDFormat);

        NameIDFormat transientnameIDFormat = SAML2Utils.createSAMLObject(NameIDFormat.class);
        transientnameIDFormat.setFormat(NameIDType.TRANSIENT);

        spSSODescriptor.getNameIDFormats().add(transientnameIDFormat);

        NameIDFormat unspecifiednameIDFormat = SAML2Utils.createSAMLObject(NameIDFormat.class);
        unspecifiednameIDFormat.setFormat(NameIDType.UNSPECIFIED);

        spSSODescriptor.getNameIDFormats().add(unspecifiednameIDFormat);

        //set HTTP-POST Binding assertion consumer service
        AssertionConsumerService postassertionConsumerService = SAML2Utils
                .createSAMLObject(AssertionConsumerService.class);

        postassertionConsumerService.setIndex(0);
        postassertionConsumerService.setBinding(SAMLConstants.SAML2_POST_BINDING_URI);
        postassertionConsumerService.setLocation(serviceURL + Constants.SERVLET_PVP2ASSERTION);
        spSSODescriptor.getAssertionConsumerServices().add(postassertionConsumerService);

        //set Single Log-Out service
        SingleLogoutService sloService = SAML2Utils.createSAMLObject(SingleLogoutService.class);
        sloService.setBinding(SAMLConstants.SAML2_REDIRECT_BINDING_URI);
        sloService.setLocation(serviceURL + Constants.SERVLET_PVPSINGLELOGOUT);
        spSSODescriptor.getSingleLogoutServices().add(sloService);

        spSSODescriptor.addSupportedProtocol(SAMLConstants.SAML20P_NS);

        spEntityDescriptor.getRoleDescriptors().add(spSSODescriptor);

        AttributeConsumingService attributeService = SAML2Utils
                .createSAMLObject(AttributeConsumingService.class);

        attributeService.setIndex(0);
        attributeService.setIsDefault(true);
        ServiceName serviceName = SAML2Utils.createSAMLObject(ServiceName.class);
        serviceName.setName(new LocalizedString("Default Service", "de"));
        attributeService.getNames().add(serviceName);

        //set attributes which are requested
        attributeService.getRequestAttributes().addAll(AttributeListBuilder.getRequestedAttributes());
        spSSODescriptor.getAttributeConsumingServices().add(attributeService);

        //build metadata
        DocumentBuilder builder;
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

        builder = factory.newDocumentBuilder();
        Document document = builder.newDocument();
        Marshaller out = org.opensaml.Configuration.getMarshallerFactory().getMarshaller(spEntitiesDescriptor);
        out.marshall(spEntitiesDescriptor, document);

        Signer.signObject(entitiesSignature);

        Transformer transformer = TransformerFactory.newInstance().newTransformer();

        StringWriter sw = new StringWriter();
        StreamResult sr = new StreamResult(sw);
        DOMSource source = new DOMSource(document);
        transformer.transform(source, sr);
        sw.close();

        String metadataXML = sw.toString();

        response.setContentType("text/xml");
        response.getOutputStream().write(metadataXML.getBytes());

        response.getOutputStream().close();

    } catch (ConfigurationException e) {
        Logger.warn("Configuration can not be loaded.", e);
        throw new ServletException("MetaData can not be created. Look into LogFiles for more details.");

    } catch (NoSuchAlgorithmException e) {
        Logger.warn("Requested Algorithm could not found.", e);
        throw new ServletException("MetaData can not be created. Look into LogFiles for more details.");

    } catch (ParserConfigurationException e) {
        Logger.warn("PVP2 Metadata createn error", e);
        throw new ServletException("MetaData can not be created. Look into LogFiles for more details.");

    } catch (TransformerConfigurationException e) {
        Logger.warn("PVP2 Metadata createn error", e);
        throw new ServletException("MetaData can not be created. Look into LogFiles for more details.");

    } catch (TransformerFactoryConfigurationError e) {
        Logger.warn("PVP2 Metadata createn error", e);
        throw new ServletException("MetaData can not be created. Look into LogFiles for more details.");

    } catch (TransformerException e) {
        Logger.warn("PVP2 Metadata createn error", e);
        throw new ServletException("MetaData can not be created. Look into LogFiles for more details.");
    }

    catch (Exception e) {
        Logger.warn("Unspecific PVP2 Metadata createn error", e);
        throw new ServletException("MetaData can not be created. Look into LogFiles for more details.");
    }

}

From source file:at.gv.egovernment.moa.id.demoOA.servlet.pvp2.Index.java

License:EUPL

private void process(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    ApplicationBean bean = new ApplicationBean();

    String method = request.getMethod();
    HttpSession session = request.getSession();
    if (session == null) {
        log.info("NO HTTP Session");
        bean.setErrorMessage("NO HTTP session");
        setAnser(request, response, bean);
        return;//  w  w w. java  2 s .c om
    }

    if (method.equals("GET")) {
        try {
            Configuration config = Configuration.getInstance();

            //Decode with HttpPost Binding
            HTTPRedirectDeflateDecoder decode = new HTTPRedirectDeflateDecoder(new BasicParserPool());
            BasicSAMLMessageContext<SAMLObject, ?, ?> messageContext = new BasicSAMLMessageContext<SAMLObject, SAMLObject, SAMLObject>();
            messageContext.setInboundMessageTransport(new HttpServletRequestAdapter(request));

            decode.decode(messageContext);

            messageContext.setMetadataProvider(config.getMetaDataProvier());
            CriteriaSet criteriaSet = new CriteriaSet();
            criteriaSet
                    .add(new MetadataCriteria(IDPSSODescriptor.DEFAULT_ELEMENT_NAME, SAMLConstants.SAML20P_NS));
            criteriaSet.add(new EntityIDCriteria(config.getPVP2IDPMetadataEntityName()));
            criteriaSet.add(new UsageCriteria(UsageType.SIGNING));

            MetadataCredentialResolverFactory credentialResolverFactory = MetadataCredentialResolverFactory
                    .getFactory();
            MetadataCredentialResolver credentialResolver = credentialResolverFactory
                    .getInstance(config.getMetaDataProvier());

            //Verify Signature
            List<KeyInfoProvider> keyInfoProvider = new ArrayList<KeyInfoProvider>();
            keyInfoProvider.add(new DSAKeyValueProvider());
            keyInfoProvider.add(new RSAKeyValueProvider());
            keyInfoProvider.add(new InlineX509DataProvider());

            KeyInfoCredentialResolver keyInfoResolver = new BasicProviderKeyInfoCredentialResolver(
                    keyInfoProvider);

            ExplicitKeySignatureTrustEngine trustEngine = new ExplicitKeySignatureTrustEngine(
                    credentialResolver, keyInfoResolver);

            SAML2HTTPRedirectDeflateSignatureRule signatureRule = new SAML2HTTPRedirectDeflateSignatureRule(
                    trustEngine);
            SAML2AuthnRequestsSignedRule signedRole = new SAML2AuthnRequestsSignedRule();
            BasicSecurityPolicy policy = new BasicSecurityPolicy();
            policy.getPolicyRules().add(signatureRule);
            policy.getPolicyRules().add(signedRole);
            SecurityPolicyResolver resolver = new StaticSecurityPolicyResolver(policy);
            messageContext.setSecurityPolicyResolver(resolver);

            messageContext.setPeerEntityRole(IDPSSODescriptor.DEFAULT_ELEMENT_NAME);

            signatureRule.evaluate(messageContext);

            SignableXMLObject samlResponse = (SignableXMLObject) messageContext.getInboundMessage();

            log.info("PVP2 statusrequest or statusresponse is valid");

            if (samlResponse instanceof LogoutResponse) {

                LogoutResponse sloResp = (LogoutResponse) samlResponse;

                //set assertion
                org.w3c.dom.Document doc = SAML2Utils.asDOMDocument(samlResponse);
                String assertion = DOMUtils.serializeNode(doc);
                bean.setAssertion(assertion);

                if (sloResp.getStatus().getStatusCode().getValue().equals(StatusCode.SUCCESS_URI)) {

                    bean.setSuccessMessage(
                            "Der Single Log-Out Vorgang konnte erfolgreich durchgefhrt werden.");

                    setAnser(request, response, bean);
                    return;

                } else {
                    bean.setErrorMessage(
                            "Der Single Log-Out Vorgang war nicht erfolgreich.<br>Bitte schlieen Sie aus sicherheitsgrnden den Browser!");
                    setAnser(request, response, bean);
                    return;

                }

            } else if (samlResponse instanceof LogoutRequest) {
                //invalidate user session
                request.getSession().invalidate();

                //build LogOutResponse
                LogoutResponse sloResp = SAML2Utils.createSAMLObject(LogoutResponse.class);
                SecureRandomIdentifierGenerator gen = new SecureRandomIdentifierGenerator();
                sloResp.setID(gen.generateIdentifier());
                sloResp.setIssueInstant(new DateTime());
                NameID name = SAML2Utils.createSAMLObject(NameID.class);
                Issuer issuer = SAML2Utils.createSAMLObject(Issuer.class);

                String serviceURL = config.getPublicUrlPreFix(request);
                if (!serviceURL.endsWith("/"))
                    serviceURL = serviceURL + "/";
                name.setValue(serviceURL);
                issuer.setValue(serviceURL);
                issuer.setFormat(NameIDType.ENTITY);
                sloResp.setIssuer(issuer);

                Status status = SAML2Utils.createSAMLObject(Status.class);
                sloResp.setStatus(status);
                StatusCode statusCode = SAML2Utils.createSAMLObject(StatusCode.class);
                statusCode.setValue(StatusCode.SUCCESS_URI);
                status.setStatusCode(statusCode);

                String entityname = config.getPVP2IDPMetadataEntityName();
                if (MiscUtil.isEmpty(entityname)) {
                    log.info("No IDP EntityName configurated");
                    throw new ConfigurationException("No IDP EntityName configurated");
                }

                //get IDP metadata from metadataprovider
                HTTPMetadataProvider idpmetadata = config.getMetaDataProvier();
                EntityDescriptor idpEntity = idpmetadata.getEntityDescriptor(entityname);
                if (idpEntity == null) {
                    log.info("IDP EntityName is not found in IDP Metadata");
                    throw new ConfigurationException("IDP EntityName is not found in IDP Metadata");
                }

                //select authentication-service url from metadata
                SingleLogoutService redirectEndpoint = null;
                for (SingleLogoutService sss : idpEntity.getIDPSSODescriptor(SAMLConstants.SAML20P_NS)
                        .getSingleLogoutServices()) {

                    //Get the service address for the binding you wish to use
                    if (sss.getBinding().equals(SAMLConstants.SAML2_REDIRECT_BINDING_URI)) {
                        redirectEndpoint = sss;
                    }
                }
                sloResp.setDestination(redirectEndpoint.getLocation());

                //sign authentication request
                KeyStore keyStore = config.getPVP2KeyStore();
                X509Credential authcredential = new KeyStoreX509CredentialAdapter(keyStore,
                        config.getPVP2KeystoreAuthRequestKeyAlias(),
                        config.getPVP2KeystoreAuthRequestKeyPassword().toCharArray());

                Signature signer = SAML2Utils.createSAMLObject(Signature.class);
                signer.setSignatureAlgorithm(SignatureConstants.ALGO_ID_SIGNATURE_RSA_SHA1);
                signer.setCanonicalizationAlgorithm(SignatureConstants.ALGO_ID_C14N_EXCL_OMIT_COMMENTS);
                signer.setSigningCredential(authcredential);
                sloResp.setSignature(signer);

                HTTPRedirectDeflateEncoder encoder = new HTTPRedirectDeflateEncoder();
                HttpServletResponseAdapter responseAdapter = new HttpServletResponseAdapter(response, true);
                BasicSAMLMessageContext<SAMLObject, SAMLObject, SAMLObject> context = new BasicSAMLMessageContext<SAMLObject, SAMLObject, SAMLObject>();
                SingleSignOnService service = new SingleSignOnServiceBuilder().buildObject();
                service.setBinding("urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST");
                service.setLocation(redirectEndpoint.getLocation());
                ;

                context.setOutboundSAMLMessageSigningCredential(authcredential);
                context.setPeerEntityEndpoint(service);
                context.setOutboundSAMLMessage(sloResp);
                context.setOutboundMessageTransport(responseAdapter);
                context.setRelayState(messageContext.getRelayState());

                encoder.encode(context);

            } else {
                bean.setErrorMessage("Kein gltiger LogOut Request oder LogOut Response");
                setAnser(request, response, bean);
                return;

            }

        } catch (Exception e) {
            log.warn("Internal error", e);
            bean.setErrorMessage("Internal Error: " + e.getMessage());
            setAnser(request, response, bean);
            return;
        }

    } else {
        bean.setErrorMessage("Die Demoapplikation untersttzt nur SAML2 POST-Binding.");
        setAnser(request, response, bean);
        return;

    }
}

From source file:at.gv.egovernment.moa.id.demoOA.servlet.pvp2.SingleLogOut.java

License:EUPL

protected void process(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {//from   w w  w.  j av  a2 s  .  c o m

        Configuration config = Configuration.getInstance();
        config.initializePVP2Login();

        String nameIDFormat = (String) request.getSession().getAttribute(Constants.SESSION_NAMEIDFORMAT);
        String nameID = (String) request.getSession().getAttribute(Constants.SESSION_NAMEID);

        if (MiscUtil.isEmpty(nameID) || MiscUtil.isEmpty(nameIDFormat)) {
            log.warn("No user information found. Single Log-Out not possible");
            throw new ServletException("No user information found. Single Log-Out not possible");

        } else
            log.info("Fount user information for user nameID: " + nameID + " , nameIDFormat: " + nameIDFormat
                    + ". Build Single Log-Out request ...");

        //invalidate local session
        request.getSession().invalidate();

        //build Single LogOut request
        LogoutRequest sloReq = SAML2Utils.createSAMLObject(LogoutRequest.class);
        SecureRandomIdentifierGenerator gen = new SecureRandomIdentifierGenerator();
        sloReq.setID(gen.generateIdentifier());
        sloReq.setIssueInstant(new DateTime());
        NameID name = SAML2Utils.createSAMLObject(NameID.class);
        Issuer issuer = SAML2Utils.createSAMLObject(Issuer.class);

        String serviceURL = config.getPublicUrlPreFix(request);
        if (!serviceURL.endsWith("/"))
            serviceURL = serviceURL + "/";
        name.setValue(serviceURL);
        issuer.setValue(serviceURL);
        issuer.setFormat(NameIDType.ENTITY);
        sloReq.setIssuer(issuer);

        NameID userNameID = SAML2Utils.createSAMLObject(NameID.class);
        sloReq.setNameID(userNameID);
        userNameID.setFormat(nameIDFormat);
        userNameID.setValue(nameID);

        String entityname = config.getPVP2IDPMetadataEntityName();
        if (MiscUtil.isEmpty(entityname)) {
            log.info("No IDP EntityName configurated");
            throw new ConfigurationException("No IDP EntityName configurated");
        }

        //get IDP metadata from metadataprovider
        HTTPMetadataProvider idpmetadata = config.getMetaDataProvier();
        EntityDescriptor idpEntity = idpmetadata.getEntityDescriptor(entityname);
        if (idpEntity == null) {
            log.info("IDP EntityName is not found in IDP Metadata");
            throw new ConfigurationException("IDP EntityName is not found in IDP Metadata");
        }

        //select authentication-service url from metadata
        SingleLogoutService redirectEndpoint = null;
        for (SingleLogoutService sss : idpEntity.getIDPSSODescriptor(SAMLConstants.SAML20P_NS)
                .getSingleLogoutServices()) {

            //Get the service address for the binding you wish to use
            if (sss.getBinding().equals(SAMLConstants.SAML2_REDIRECT_BINDING_URI)) {
                redirectEndpoint = sss;
            }
        }
        sloReq.setDestination(redirectEndpoint.getLocation());

        //sign authentication request
        KeyStore keyStore = config.getPVP2KeyStore();
        X509Credential authcredential = new KeyStoreX509CredentialAdapter(keyStore,
                config.getPVP2KeystoreAuthRequestKeyAlias(),
                config.getPVP2KeystoreAuthRequestKeyPassword().toCharArray());

        Signature signer = SAML2Utils.createSAMLObject(Signature.class);
        signer.setSignatureAlgorithm(SignatureConstants.ALGO_ID_SIGNATURE_RSA_SHA1);
        signer.setCanonicalizationAlgorithm(SignatureConstants.ALGO_ID_C14N_EXCL_OMIT_COMMENTS);
        signer.setSigningCredential(authcredential);
        sloReq.setSignature(signer);

        HTTPRedirectDeflateEncoder encoder = new HTTPRedirectDeflateEncoder();
        HttpServletResponseAdapter responseAdapter = new HttpServletResponseAdapter(response, true);
        BasicSAMLMessageContext<SAMLObject, SAMLObject, SAMLObject> context = new BasicSAMLMessageContext<SAMLObject, SAMLObject, SAMLObject>();
        SingleSignOnService service = new SingleSignOnServiceBuilder().buildObject();
        service.setBinding(SAMLConstants.SAML2_REDIRECT_BINDING_URI);
        service.setLocation(redirectEndpoint.getLocation());
        context.setOutboundSAMLMessageSigningCredential(authcredential);
        context.setPeerEntityEndpoint(service);
        context.setOutboundSAMLMessage(sloReq);
        context.setOutboundMessageTransport(responseAdapter);

        encoder.encode(context);

    } catch (Exception e) {
        log.warn("Authentication Request can not be generated", e);
        throw new ServletException("Authentication Request can not be generated.", e);
    }
}

From source file:at.gv.egovernment.moa.id.moduls.AuthenticationManager.java

License:EUPL

private void buildPVP21AuthenticationRequest(HttpServletRequest request, HttpServletResponse response,
        IRequest target) throws ServletException, IOException, MOAIDException {

    boolean requiredLocalAuthentication = true;

    Logger.debug("Build PVP 2.1 authentication request");

    //get IDP metadata
    try {//from w  ww. j ava  2  s  .c o  m
        OAAuthParameter idp = AuthConfigurationProvider.getInstance()
                .getOnlineApplicationParameter(target.getRequestedIDP());
        OAAuthParameter sp = AuthConfigurationProvider.getInstance()
                .getOnlineApplicationParameter(target.getOAURL());

        if (!idp.isInderfederationIDP() || !idp.isInboundSSOInterfederationAllowed()) {
            Logger.info("Requested interfederation IDP " + target.getRequestedIDP()
                    + " is not valid for interfederation.");
            Logger.info("Switch to local authentication on this IDP ... ");
            perfomLocalAuthentication(request, response, target);
            return;

        }

        EntityDescriptor idpEntity = MOAMetadataProvider.getInstance()
                .getEntityDescriptor(target.getRequestedIDP());

        if (idpEntity != null) {

            //fetch endpoint from IDP metadata
            SingleSignOnService redirectEndpoint = null;
            for (SingleSignOnService sss : idpEntity.getIDPSSODescriptor(SAMLConstants.SAML20P_NS)
                    .getSingleSignOnServices()) {

                // use POST binding as default if it exists 
                //TODO: maybe use RedirectBinding as default 
                if (sss.getBinding().equals(SAMLConstants.SAML2_POST_BINDING_URI)) {
                    redirectEndpoint = sss;

                } else if (sss.getBinding().equals(SAMLConstants.SAML2_REDIRECT_BINDING_URI)
                        && redirectEndpoint == null)
                    redirectEndpoint = sss;
            }

            if (redirectEndpoint != null) {

                AuthnRequest authReq = SAML2Utils.createSAMLObject(AuthnRequest.class);
                SecureRandomIdentifierGenerator gen = new SecureRandomIdentifierGenerator();
                authReq.setID(gen.generateIdentifier());

                //send passive AuthnRequest
                authReq.setIsPassive(idp.isPassivRequestUsedForInterfederation());

                authReq.setAssertionConsumerServiceIndex(0);
                authReq.setIssueInstant(new DateTime());
                Issuer issuer = SAML2Utils.createSAMLObject(Issuer.class);
                String serviceURL = PVPConfiguration.getInstance().getIDPPublicPath();
                issuer.setValue(serviceURL);

                issuer.setFormat(NameIDType.ENTITY);
                authReq.setIssuer(issuer);
                NameIDPolicy policy = SAML2Utils.createSAMLObject(NameIDPolicy.class);
                policy.setAllowCreate(true);
                policy.setFormat(NameID.TRANSIENT);
                authReq.setNameIDPolicy(policy);

                authReq.setDestination(redirectEndpoint.getLocation());

                RequestedAuthnContext reqAuthContext = SAML2Utils.createSAMLObject(RequestedAuthnContext.class);

                AuthnContextClassRef authnClassRef = SAML2Utils.createSAMLObject(AuthnContextClassRef.class);

                if (sp != null && sp.isSTORKPVPGateway()) {
                    //use PVP SecClass instead of STORK QAA level
                    String secClass = null;
                    if (target instanceof MOASTORKRequest) {

                        try {
                            MOASTORKRequest storkReq = (MOASTORKRequest) target;
                            secClass = PVPtoSTORKMapper.getInstance().mapToSecClass(
                                    PVPConstants.STORK_QAA_PREFIX + storkReq.getStorkAuthnRequest().getQaa());

                        } catch (Exception e) {
                            Logger.warn("STORK-QAA level can not read from STORK request. Use default QAA 4",
                                    e);

                        }
                    }

                    if (MiscUtil.isNotEmpty(secClass))
                        authnClassRef.setAuthnContextClassRef(secClass);
                    else
                        authnClassRef
                                .setAuthnContextClassRef("http://www.ref.gv.at/ns/names/agiz/pvp/secclass/0-3");

                } else {
                    if (target instanceof MOASTORKRequest) {
                        //use requested QAA level from STORK request
                        try {
                            MOASTORKRequest storkReq = (MOASTORKRequest) target;
                            authnClassRef.setAuthnContextClassRef(
                                    PVPConstants.STORK_QAA_PREFIX + storkReq.getStorkAuthnRequest().getQaa());
                            Logger.debug("Use STORK-QAA level " + authnClassRef.getAuthnContextClassRef()
                                    + " from STORK request");

                        } catch (Exception e) {
                            Logger.warn("STORK-QAA level can not read from STORK request. Use default QAA 4",
                                    e);

                        }

                    }

                    if (MiscUtil.isEmpty(authnClassRef.getAuthnContextClassRef()))
                        authnClassRef.setAuthnContextClassRef("http://www.stork.gov.eu/1.0/citizenQAALevel/4");

                }

                reqAuthContext.setComparison(AuthnContextComparisonTypeEnumeration.MINIMUM);
                reqAuthContext.getAuthnContextClassRefs().add(authnClassRef);
                authReq.setRequestedAuthnContext(reqAuthContext);

                IEncoder binding = null;
                if (redirectEndpoint.getBinding().equals(SAMLConstants.SAML2_REDIRECT_BINDING_URI)) {
                    binding = new RedirectBinding();

                } else if (redirectEndpoint.getBinding().equals(SAMLConstants.SAML2_POST_BINDING_URI)) {
                    binding = new PostBinding();

                }

                binding.encodeRequest(request, response, authReq, redirectEndpoint.getLocation(),
                        target.getRequestID());

                //build and send request without an error
                requiredLocalAuthentication = false;

            } else {
                Logger.warn("Requested IDP " + target.getRequestedIDP()
                        + " does not support POST or Redirect Binding.");

            }

        } else {
            Logger.warn("Requested IDP " + target.getRequestedIDP()
                    + " is not found in InterFederation configuration");

        }

    } catch (MetadataProviderException e) {
        Logger.error("IDP metadata error.", e);

    } catch (NoSuchAlgorithmException e) {
        Logger.error("Build IDP authentication request FAILED.", e);

    } catch (MessageEncodingException e) {
        Logger.error("Build IDP authentication request FAILED.", e);

    } catch (SecurityException e) {
        Logger.error("Build IDP authentication request FAILED.", e);

    }

    if (requiredLocalAuthentication) {
        Logger.info("Switch to local authentication on this IDP ... ");
        perfomLocalAuthentication(request, response, target);
    }
}

From source file:at.gv.egovernment.moa.id.protocols.pvp2x.AttributQueryAction.java

License:EUPL

@Override
public SLOInformationInterface processRequest(IRequest req, HttpServletRequest httpReq,
        HttpServletResponse httpResp, IAuthData authData) throws MOAIDException {

    if (req instanceof PVPTargetConfiguration
            && ((PVPTargetConfiguration) req).getRequest() instanceof MOARequest
            && ((MOARequest) ((PVPTargetConfiguration) req).getRequest())
                    .getSamlRequest() instanceof AttributeQuery) {

        AttributeQuery attrQuery = (AttributeQuery) ((MOARequest) ((PVPTargetConfiguration) req).getRequest())
                .getSamlRequest();/*from   w w w .  j  av  a2 s .com*/

        //load moaSession
        String nameID = attrQuery.getSubject().getNameID().getValue();

        AuthenticationSession session = AuthenticationSessionStoreage.getSessionWithUserNameID(nameID);
        if (session == null) {
            Logger.warn("AttributeQuery nameID does not match to an active single sign-on session.");
            throw new AttributQueryException(
                    "AttributeQuery nameID does not match to an active single sign-on session.", null);

        }

        DateTime date = new DateTime();

        //generate authData
        authData = AuthenticationDataBuilder.buildAuthenticationData(req, session, attrQuery.getAttributes());

        //add default attributes in case of mandates or STORK is in use
        List<String> attrList = addDefaultAttributes(attrQuery, authData);

        //build PVP 2.1 assertion
        Assertion assertion = PVP2AssertionBuilder.buildAssertion(attrQuery, attrList, authData, date,
                authData.getSessionIndex());

        //build PVP 2.1 response
        Response authResponse = AuthResponseBuilder.buildResponse(attrQuery, date, assertion);

        try {
            SoapBinding decoder = new SoapBinding();
            decoder.encodeRespone(httpReq, httpResp, authResponse, null, null);
            return null;

        } catch (MessageEncodingException e) {
            Logger.error("Message Encoding exception", e);
            throw new MOAIDException("pvp2.01", null, e);

        } catch (SecurityException e) {
            Logger.error("Security exception", e);
            throw new MOAIDException("pvp2.01", null, e);

        }

    } else {
        Logger.error("Process AttributeQueryAction but request is NOT of type AttributQuery.");
        throw new MOAIDException("pvp2.13", null);

    }
}