List of usage examples for org.joda.time DateTime DateTime
public DateTime()
ISOChronology
in the default time zone. From source file:at.gv.egovernment.moa.id.protocols.pvp2x.builder.AttributQueryBuilder.java
License:EUPL
public static AttributeQuery buildAttributQueryRequest(String nameID, String endpoint, List<Attribute> requestedAttributes) throws AttributQueryException { try {//from www . j a v a 2s . c o m AttributeQuery query = new AttributeQueryBuilder().buildObject(); //set user nameID Subject subject = SAML2Utils.createSAMLObject(Subject.class); NameID subjectNameID = SAML2Utils.createSAMLObject(NameID.class); subjectNameID.setValue(nameID); subjectNameID.setFormat(NameID.TRANSIENT); subject.setNameID(subjectNameID); query.setSubject(subject); //set attributes query.getAttributes().addAll(requestedAttributes); //set general request parameters DateTime now = new DateTime(); query.setIssueInstant(now); Issuer nissuer = SAML2Utils.createSAMLObject(Issuer.class); nissuer.setValue(PVPConfiguration.getInstance().getIDPPublicPath()); nissuer.setFormat(NameID.ENTITY); query.setIssuer(nissuer); String sessionID = SAML2Utils.getSecureIdentifier(); query.setID(sessionID); query.setDestination(endpoint); X509Credential idpSigningCredential = CredentialProvider.getIDPAssertionSigningCredential(); 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(idpSigningCredential); query.setSignature(signer); DocumentBuilder builder; DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); builder = factory.newDocumentBuilder(); Document document = builder.newDocument(); Marshaller out = Configuration.getMarshallerFactory().getMarshaller(query); out.marshall(query, document); Signer.signObject(signer); return query; } catch (ConfigurationException e) { Logger.error("Build AttributQuery Request FAILED.", e); throw new AttributQueryException("Build AttributQuery Request FAILED.", null, e); } catch (CredentialsNotAvailableException e) { Logger.error("Build AttributQuery Request FAILED.", e); throw new AttributQueryException("Build AttributQuery Request FAILED.", null, e); } catch (ParserConfigurationException e) { Logger.error("Build AttributQuery Request FAILED.", e); throw new AttributQueryException("Build AttributQuery Request FAILED.", null, e); } catch (MarshallingException e) { Logger.error("Build AttributQuery Request FAILED.", e); throw new AttributQueryException("Build AttributQuery Request FAILED.", null, e); } catch (SignatureException e) { Logger.error("Build AttributQuery Request FAILED.", e); throw new AttributQueryException("Build AttributQuery Request FAILED.", null, e); } }
From source file:at.gv.egovernment.moa.id.protocols.pvp2x.builder.SingleLogOutBuilder.java
License:EUPL
public static LogoutRequest buildSLORequestMessage(SLOInformationImpl sloInfo) throws ConfigurationException, MOAIDException { LogoutRequest sloReq = SAML2Utils.createSAMLObject(LogoutRequest.class); SecureRandomIdentifierGenerator gen; try {/*from w w w . ja v a2s . c o m*/ gen = new SecureRandomIdentifierGenerator(); sloReq.setID(gen.generateIdentifier()); } catch (NoSuchAlgorithmException e) { Logger.error("Internal server error", e); throw new AuthenticationException("pvp2.13", new Object[] {}); } DateTime now = new DateTime(); Issuer issuer = SAML2Utils.createSAMLObject(Issuer.class); issuer.setValue(PVPConfiguration.getInstance().getIDPPublicPath()); issuer.setFormat(NameID.ENTITY); sloReq.setIssuer(issuer); sloReq.setIssueInstant(now); sloReq.setNotOnOrAfter(now.plusMinutes(5)); sloReq.setDestination(sloInfo.getServiceURL()); NameID nameID = SAML2Utils.createSAMLObject(NameID.class); nameID.setFormat(sloInfo.getUserNameIDFormat()); nameID.setValue(sloInfo.getUserNameIdentifier()); sloReq.setNameID(nameID); return sloReq; }
From source file:at.gv.egovernment.moa.id.protocols.pvp2x.builder.SingleLogOutBuilder.java
License:EUPL
private static LogoutResponse buildBasicResponse(SingleLogoutService sloService, PVPTargetConfiguration spRequest) throws ConfigurationException, MOAIDException { LogoutResponse sloResp = SAML2Utils.createSAMLObject(LogoutResponse.class); Issuer issuer = SAML2Utils.createSAMLObject(Issuer.class); issuer.setValue(PVPConfiguration.getInstance().getIDPPublicPath()); issuer.setFormat(NameID.ENTITY);// ww w . ja va 2 s .c om sloResp.setIssuer(issuer); sloResp.setIssueInstant(new DateTime()); sloResp.setDestination(sloService.getLocation()); SecureRandomIdentifierGenerator gen; try { gen = new SecureRandomIdentifierGenerator(); sloResp.setID(gen.generateIdentifier()); } catch (NoSuchAlgorithmException e) { Logger.error("Internal server error", e); throw new AuthenticationException("pvp2.13", new Object[] {}); } if (spRequest.getRequest() instanceof MOARequest && ((MOARequest) spRequest.getRequest()).getSamlRequest() instanceof LogoutRequest) { LogoutRequest sloReq = (LogoutRequest) ((MOARequest) spRequest.getRequest()).getSamlRequest(); sloResp.setInResponseTo(sloReq.getID()); } return sloResp; }
From source file:at.gv.egovernment.moa.id.protocols.pvp2x.MetadataAction.java
License:EUPL
public SLOInformationInterface processRequest(IRequest req, HttpServletRequest httpReq, HttpServletResponse httpResp, IAuthData authData) throws MOAIDException { try {/*ww w .j a v a 2 s .c om*/ EntitiesDescriptor idpEntitiesDescriptor = SAML2Utils.createSAMLObject(EntitiesDescriptor.class); idpEntitiesDescriptor.setName(PVPConfiguration.getInstance().getIDPIssuerName()); idpEntitiesDescriptor.setID(SAML2Utils.getSecureIdentifier()); DateTime date = new DateTime(); idpEntitiesDescriptor.setValidUntil(date.plusHours(VALIDUNTIL_IN_HOURS)); EntityDescriptor idpEntityDescriptor = SAML2Utils.createSAMLObject(EntityDescriptor.class); idpEntitiesDescriptor.getEntityDescriptors().add(idpEntityDescriptor); //TODO: maybe change EntityID to Metadata URL //idpEntityDescriptor // .setEntityID(PVPConfiguration.getInstance().getIDPSSOMetadataService()); idpEntityDescriptor.setEntityID(PVPConfiguration.getInstance().getIDPPublicPath()); idpEntityDescriptor.setValidUntil(date.plusDays(VALIDUNTIL_IN_HOURS)); List<ContactPerson> persons = PVPConfiguration.getInstance().getIDPContacts(); idpEntityDescriptor.getContactPersons().addAll(persons); idpEntityDescriptor.setOrganization(PVPConfiguration.getInstance().getIDPOrganisation()); X509KeyInfoGeneratorFactory keyInfoFactory = new X509KeyInfoGeneratorFactory(); //keyInfoFactory.setEmitPublicKeyValue(true); keyInfoFactory.setEmitEntityIDAsKeyName(true); keyInfoFactory.setEmitEntityCertificate(true); KeyInfoGenerator keyInfoGenerator = keyInfoFactory.newInstance(); Credential metadataSigningCredential = CredentialProvider.getIDPMetaDataSigningCredential(); Signature signature = CredentialProvider.getIDPSignature(metadataSigningCredential); //set KeyInfo Element SecurityHelper.prepareSignatureParams(signature, metadataSigningCredential, null, null); idpEntitiesDescriptor.setSignature(signature); //set IDP metadata idpEntityDescriptor.getRoleDescriptors().add(generateIDPMetadata(keyInfoGenerator)); //set SP metadata for interfederation idpEntityDescriptor.getRoleDescriptors().add(generateSPMetadata(keyInfoGenerator)); DocumentBuilder builder; DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); builder = factory.newDocumentBuilder(); Document document = builder.newDocument(); Marshaller out = Configuration.getMarshallerFactory().getMarshaller(idpEntitiesDescriptor); out.marshall(idpEntitiesDescriptor, document); Signer.signObject(signature); 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(); Logger.debug("METADATA: " + metadataXML); httpResp.setContentType("text/xml"); httpResp.getOutputStream().write(metadataXML.getBytes("UTF-8")); httpResp.getOutputStream().close(); return null; } catch (Exception e) { Logger.error("Failed to generate metadata", e); throw new MOAIDException("pvp2.13", null); } }
From source file:at.gv.egovernment.moa.id.protocols.pvp2x.PVP2XProtocol.java
License:EUPL
public boolean generateErrorMessage(Throwable e, HttpServletRequest request, HttpServletResponse response, IRequest protocolRequest) throws Throwable { if (protocolRequest == null) { throw e;//w ww .ja v a2 s. c om } if (!(protocolRequest instanceof PVPTargetConfiguration)) { throw e; } PVPTargetConfiguration pvpRequest = (PVPTargetConfiguration) protocolRequest; Response samlResponse = SAML2Utils.createSAMLObject(Response.class); Status status = SAML2Utils.createSAMLObject(Status.class); StatusCode statusCode = SAML2Utils.createSAMLObject(StatusCode.class); StatusMessage statusMessage = SAML2Utils.createSAMLObject(StatusMessage.class); ErrorResponseUtils errorUtils = ErrorResponseUtils.getInstance(); String moaError = null; if (e instanceof NoPassivAuthenticationException) { statusCode.setValue(StatusCode.NO_PASSIVE_URI); statusMessage.setMessage(StringEscapeUtils.escapeXml(e.getLocalizedMessage())); } else if (e instanceof NameIDFormatNotSupportedException) { statusCode.setValue(StatusCode.INVALID_NAMEID_POLICY_URI); statusMessage.setMessage(StringEscapeUtils.escapeXml(e.getLocalizedMessage())); } else if (e instanceof SLOException) { //SLOExecpetions only occurs if session information is lost return false; } else if (e instanceof PVP2Exception) { PVP2Exception ex = (PVP2Exception) e; statusCode.setValue(ex.getStatusCodeValue()); String statusMessageValue = ex.getStatusMessageValue(); if (statusMessageValue != null) { statusMessage.setMessage(StringEscapeUtils.escapeXml(statusMessageValue)); } moaError = errorUtils.mapInternalErrorToExternalError(ex.getMessageId()); } else { statusCode.setValue(StatusCode.RESPONDER_URI); statusMessage.setMessage(StringEscapeUtils.escapeXml(e.getLocalizedMessage())); moaError = errorUtils.getResponseErrorCode(e); } if (MiscUtil.isNotEmpty(moaError)) { StatusCode moaStatusCode = SAML2Utils.createSAMLObject(StatusCode.class); moaStatusCode.setValue(moaError); statusCode.setStatusCode(moaStatusCode); } status.setStatusCode(statusCode); if (statusMessage.getMessage() != null) { status.setStatusMessage(statusMessage); } samlResponse.setStatus(status); String remoteSessionID = SAML2Utils.getSecureIdentifier(); samlResponse.setID(remoteSessionID); samlResponse.setIssueInstant(new DateTime()); Issuer nissuer = SAML2Utils.createSAMLObject(Issuer.class); nissuer.setValue(PVPConfiguration.getInstance().getIDPPublicPath()); nissuer.setFormat(NameID.ENTITY); samlResponse.setIssuer(nissuer); IEncoder encoder = null; if (pvpRequest.getBinding().equals(SAMLConstants.SAML2_REDIRECT_BINDING_URI)) { encoder = new RedirectBinding(); } else if (pvpRequest.getBinding().equals(SAMLConstants.SAML2_ARTIFACT_BINDING_URI)) { // TODO: not supported YET!! //binding = new ArtifactBinding(); } else if (pvpRequest.getBinding().equals(SAMLConstants.SAML2_POST_BINDING_URI)) { encoder = new PostBinding(); } else if (pvpRequest.getBinding().equals(SAMLConstants.SAML2_SOAP11_BINDING_URI)) { encoder = new SoapBinding(); } if (encoder == null) { // default to redirect binding encoder = new RedirectBinding(); } String relayState = null; if (pvpRequest.getRequest() != null) relayState = pvpRequest.getRequest().getRelayState(); encoder.encodeRespone(request, response, samlResponse, pvpRequest.getConsumerURL(), relayState); return true; }
From source file:at.gv.egovernment.moa.id.protocols.pvp2x.requestHandler.ArtifactResolution.java
License:EUPL
public SLOInformationInterface process(PVPTargetConfiguration obj, HttpServletRequest req, HttpServletResponse resp, IAuthData authData) throws MOAIDException { if (!handleObject(obj.getRequest())) { throw new MOAIDException("pvp2.13", null); }//from w w w. j av a 2 s .co m ArtifactResolve artifactResolve = (ArtifactResolve) ((MOARequest) obj.getRequest()).getSamlRequest(); String artifactID = artifactResolve.getArtifact().getArtifact(); PVPAssertionStorage pvpAssertion = PVPAssertionStorage.getInstance(); if (!pvpAssertion.contains(artifactID)) { throw new RequestDeniedException(); } else { try { SAMLArtifactMapEntry assertion = pvpAssertion.get(artifactID); ArtifactResponse response = SAML2Utils.createSAMLObject(ArtifactResponse.class); response.setMessage(assertion.getSamlMessage()); response.setIssueInstant(new DateTime()); SoapBinding encoder = new SoapBinding(); encoder.encodeRespone(req, resp, response, null, null); } catch (Exception e) { Logger.error("Failed to resolve artifact", e); } } return null; }
From source file:at.gv.egovernment.moa.id.protocols.pvp2x.requestHandler.AuthnRequestHandler.java
License:EUPL
public SLOInformationInterface process(PVPTargetConfiguration obj, HttpServletRequest req, HttpServletResponse resp, IAuthData authData) throws MOAIDException { if (!handleObject(obj.getRequest())) { throw new MOAIDException("pvp2.13", null); }//from w ww . ja va 2 s . co m //get basic information MOARequest moaRequest = (MOARequest) obj.getRequest(); AuthnRequest authnRequest = (AuthnRequest) moaRequest.getSamlRequest(); EntityDescriptor peerEntity = moaRequest.getEntityMetadata(); AssertionConsumerService consumerService = SAML2Utils.createSAMLObject(AssertionConsumerService.class); consumerService.setBinding(obj.getBinding()); consumerService.setLocation(obj.getConsumerURL()); DateTime date = new DateTime(); SLOInformationImpl sloInformation = new SLOInformationImpl(); //build Assertion Assertion assertion = PVP2AssertionBuilder.buildAssertion(authnRequest, authData, peerEntity, date, consumerService, sloInformation); Response authResponse = AuthResponseBuilder.buildResponse(authnRequest, date, assertion); IEncoder binding = null; if (consumerService.getBinding().equals(SAMLConstants.SAML2_REDIRECT_BINDING_URI)) { binding = new RedirectBinding(); } else if (consumerService.getBinding().equals(SAMLConstants.SAML2_ARTIFACT_BINDING_URI)) { // TODO: not supported YET!! binding = new ArtifactBinding(); } else if (consumerService.getBinding().equals(SAMLConstants.SAML2_POST_BINDING_URI)) { binding = new PostBinding(); } if (binding == null) { throw new BindingNotSupportedException(consumerService.getBinding()); } try { binding.encodeRespone(req, resp, authResponse, consumerService.getLocation(), moaRequest.getRelayState()); return sloInformation; } 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); } }
From source file:at.gv.egovernment.moa.id.protocols.pvp2x.utils.StoredAssertion.java
License:EUPL
public StoredAssertion(String artifact, String relyingPartyId, String issuerId, SAMLObject samlMessage) { this.artifact = artifact; this.relyingPartyId = relyingPartyId; this.issuerId = issuerId; this.samlMessage = samlMessage; this.expirationTime = new DateTime(); this.expirationTime.plusMinutes(5); }
From source file:at.gv.egovernment.moa.id.protocols.pvp2x.verification.SAMLVerificationEngine.java
License:EUPL
public static void validateAssertion(Response samlResp, boolean validateDestination) throws AssertionValidationExeption { try {//from www . j a v a 2 s .co m if (samlResp.getStatus().getStatusCode().getValue().equals(StatusCode.SUCCESS_URI)) { List<org.opensaml.saml2.core.Assertion> saml2assertions = new ArrayList<org.opensaml.saml2.core.Assertion>(); if (validateDestination && !samlResp.getDestination() .startsWith(PVPConfiguration.getInstance().getIDPPublicPath())) { Logger.warn("PVP 2.1 assertion destination does not match to IDP URL"); throw new AssertionValidationExeption("PVP 2.1 assertion destination does not match to IDP URL", null); } //check encrypted Assertion List<EncryptedAssertion> encryAssertionList = samlResp.getEncryptedAssertions(); if (encryAssertionList != null && encryAssertionList.size() > 0) { //decrypt assertions Logger.debug("Found encryped assertion. Start decryption ..."); X509Credential authDecCredential = CredentialProvider.getIDPAssertionEncryptionCredential(); StaticKeyInfoCredentialResolver skicr = new StaticKeyInfoCredentialResolver(authDecCredential); ChainingEncryptedKeyResolver encryptedKeyResolver = new ChainingEncryptedKeyResolver(); encryptedKeyResolver.getResolverChain().add(new InlineEncryptedKeyResolver()); encryptedKeyResolver.getResolverChain().add(new EncryptedElementTypeEncryptedKeyResolver()); encryptedKeyResolver.getResolverChain().add(new SimpleRetrievalMethodEncryptedKeyResolver()); Decrypter samlDecrypter = new Decrypter(null, skicr, encryptedKeyResolver); for (EncryptedAssertion encAssertion : encryAssertionList) { saml2assertions.add(samlDecrypter.decrypt(encAssertion)); } Logger.debug("Assertion decryption finished. "); } else { saml2assertions.addAll(samlResp.getAssertions()); } List<org.opensaml.saml2.core.Assertion> validatedassertions = new ArrayList<org.opensaml.saml2.core.Assertion>(); for (org.opensaml.saml2.core.Assertion saml2assertion : saml2assertions) { try { performSchemaValidation(saml2assertion.getDOM()); Conditions conditions = saml2assertion.getConditions(); DateTime notbefore = conditions.getNotBefore().minusMinutes(5); DateTime notafter = conditions.getNotOnOrAfter(); if (notbefore.isAfterNow() || notafter.isBeforeNow()) { Logger.warn("PVP2 Assertion is out of Date. " + "{ Current : " + new DateTime() + " NotBefore: " + notbefore + " NotAfter : " + notafter + " }"); ; } else { validatedassertions.add(saml2assertion); } } catch (SchemaValidationException e) { } } if (validatedassertions.isEmpty()) { Logger.info("No valid PVP 2.1 assertion received."); throw new AssertionValidationExeption("No valid PVP 2.1 assertion received.", null); } samlResp.getAssertions().clear(); samlResp.getEncryptedAssertions().clear(); samlResp.getAssertions().addAll(validatedassertions); } else { Logger.info("PVP 2.1 assertion includes an error. Receive errorcode " + samlResp.getStatus().getStatusCode().getValue()); throw new AssertionValidationExeption("PVP 2.1 assertion includes an error. Receive errorcode " + samlResp.getStatus().getStatusCode().getValue(), null); } } catch (CredentialsNotAvailableException e) { Logger.warn("Assertion decrypt FAILED - No Credentials", e); throw new AssertionValidationExeption("Assertion decrypt FAILED - No Credentials", null, e); } catch (DecryptionException e) { Logger.warn("Assertion decrypt FAILED.", e); throw new AssertionValidationExeption("Assertion decrypt FAILED.", null, e); } catch (ConfigurationException e) { throw new AssertionValidationExeption("pvp.12", null, e); } }
From source file:at.tfr.securefs.client.SecurefsClient.java
License:Open Source License
public void run() { DateTime start = new DateTime(); try (FileSystem fs = FileSystems.newFileSystem(new URI(baseDir), null)) { for (Path path : files) { Path sec = fs.getPath(path.toString() + (asyncTest ? "." + Thread.currentThread().getId() : "")); if (write) { if (!path.toFile().exists()) { System.err.println(Thread.currentThread() + ": NoSuchFile: " + path + " currentWorkdir=" + Paths.get("./").toAbsolutePath()); continue; }//from www . ja v a 2s . c o m if (path.getParent() != null) { fs.provider().createDirectory(fs.getPath(path.getParent().toString())); } final OutputStream secOs = Files.newOutputStream(sec); System.out.println(Thread.currentThread() + ": Sending file: " + start + " : " + sec); IOUtils.copyLarge(Files.newInputStream(path), secOs, new byte[128 * 1024]); secOs.close(); } Path out = path.resolveSibling( path.getFileName() + (asyncTest ? "." + Thread.currentThread().getId() : "") + ".out"); if (read) { System.out.println(Thread.currentThread() + ": Reading file: " + new DateTime() + " : " + out); if (out.getParent() != null) { Files.createDirectories(out.getParent()); } final InputStream secIs = Files.newInputStream(sec); IOUtils.copyLarge(secIs, Files.newOutputStream(out), new byte[128 * 1024]); secIs.close(); } if (write && read) { long inputChk = FileUtils.checksumCRC32(path.toFile()); long outputChk = FileUtils.checksumCRC32(out.toFile()); if (inputChk != outputChk) { throw new IOException(Thread.currentThread() + ": Checksum Failed: failure to write/read: in=" + path + ", out=" + out); } System.out.println(Thread.currentThread() + ": Checked Checksums: " + new DateTime() + " : " + inputChk + " / " + outputChk); } if (delete) { boolean deleted = fs.provider().deleteIfExists(sec); if (!deleted) { throw new IOException( Thread.currentThread() + ": Delete Failed: failure to delete: in=" + path); } else { System.out.println(Thread.currentThread() + ": Deleted File: in=" + path); } } } } catch (Throwable t) { t.printStackTrace(); throw new RuntimeException(t); } }