GestoreTokenValidazioneUtilities.java

  1. /*
  2.  * GovWay - A customizable API Gateway
  3.  * https://govway.org
  4.  *
  5.  * Copyright (c) 2005-2025 Link.it srl (https://link.it).
  6.  *
  7.  * This program is free software: you can redistribute it and/or modify
  8.  * it under the terms of the GNU General Public License version 3, as published by
  9.  * the Free Software Foundation.
  10.  *
  11.  * This program is distributed in the hope that it will be useful,
  12.  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13.  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  14.  * GNU General Public License for more details.
  15.  *
  16.  * You should have received a copy of the GNU General Public License
  17.  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
  18.  *
  19.  */
  20. package org.openspcoop2.pdd.core.token;

  21. import java.io.ByteArrayOutputStream;
  22. import java.io.Serializable;
  23. import java.text.SimpleDateFormat;
  24. import java.util.ArrayList;
  25. import java.util.Date;
  26. import java.util.Enumeration;
  27. import java.util.HashMap;
  28. import java.util.List;
  29. import java.util.Map;
  30. import java.util.Properties;

  31. import org.apache.commons.lang.StringUtils;
  32. import org.apache.cxf.rs.security.jose.jwk.JsonWebKeys;
  33. import org.openspcoop2.core.commons.CoreException;
  34. import org.openspcoop2.core.commons.DBUtils;
  35. import org.openspcoop2.core.config.InvocazioneCredenziali;
  36. import org.openspcoop2.core.config.PortaApplicativa;
  37. import org.openspcoop2.core.config.PortaDelegata;
  38. import org.openspcoop2.core.config.Proprieta;
  39. import org.openspcoop2.core.config.ResponseCachingConfigurazione;
  40. import org.openspcoop2.core.config.constants.StatoFunzionalita;
  41. import org.openspcoop2.core.config.driver.DriverConfigurazioneException;
  42. import org.openspcoop2.core.constants.CostantiConnettori;
  43. import org.openspcoop2.core.constants.CostantiLabel;
  44. import org.openspcoop2.core.constants.TipiConnettore;
  45. import org.openspcoop2.core.constants.TransferLengthModes;
  46. import org.openspcoop2.core.id.IDServizio;
  47. import org.openspcoop2.core.id.IDSoggetto;
  48. import org.openspcoop2.message.OpenSPCoop2Message;
  49. import org.openspcoop2.message.OpenSPCoop2MessageFactory;
  50. import org.openspcoop2.message.OpenSPCoop2MessageParseResult;
  51. import org.openspcoop2.message.constants.MessageType;
  52. import org.openspcoop2.message.rest.OpenSPCoop2Message_binary_impl;
  53. import org.openspcoop2.message.utils.WWWAuthenticateErrorCode;
  54. import org.openspcoop2.message.utils.WWWAuthenticateGenerator;
  55. import org.openspcoop2.pdd.config.ConfigurazionePdDManager;
  56. import org.openspcoop2.pdd.config.CostantiProprieta;
  57. import org.openspcoop2.pdd.config.ForwardProxy;
  58. import org.openspcoop2.pdd.config.OpenSPCoop2Properties;
  59. import org.openspcoop2.pdd.config.PDNDResolver;
  60. import org.openspcoop2.pdd.core.CostantiPdD;
  61. import org.openspcoop2.pdd.core.PdDContext;
  62. import org.openspcoop2.pdd.core.connettori.ConnettoreBaseHTTP;
  63. import org.openspcoop2.pdd.core.connettori.ConnettoreHTTP;
  64. import org.openspcoop2.pdd.core.connettori.ConnettoreHTTPS;
  65. import org.openspcoop2.pdd.core.connettori.ConnettoreMsg;
  66. import org.openspcoop2.pdd.core.controllo_traffico.PolicyTimeoutConfig;
  67. import org.openspcoop2.pdd.core.dynamic.DynamicException;
  68. import org.openspcoop2.pdd.core.dynamic.DynamicUtils;
  69. import org.openspcoop2.pdd.core.token.pa.DatiInvocazionePortaApplicativa;
  70. import org.openspcoop2.pdd.core.token.pa.EsitoDynamicDiscoveryPortaApplicativa;
  71. import org.openspcoop2.pdd.core.token.pa.EsitoGestioneTokenPortaApplicativa;
  72. import org.openspcoop2.pdd.core.token.parser.Claims;
  73. import org.openspcoop2.pdd.core.token.parser.IDynamicDiscoveryParser;
  74. import org.openspcoop2.pdd.core.token.parser.ITokenParser;
  75. import org.openspcoop2.pdd.core.token.pd.DatiInvocazionePortaDelegata;
  76. import org.openspcoop2.pdd.core.token.pd.EsitoDynamicDiscoveryPortaDelegata;
  77. import org.openspcoop2.pdd.core.token.pd.EsitoGestioneTokenPortaDelegata;
  78. import org.openspcoop2.protocol.engine.ProtocolFactoryManager;
  79. import org.openspcoop2.protocol.sdk.Busta;
  80. import org.openspcoop2.protocol.sdk.Context;
  81. import org.openspcoop2.protocol.sdk.IProtocolFactory;
  82. import org.openspcoop2.protocol.sdk.PDNDTokenInfo;
  83. import org.openspcoop2.protocol.sdk.ProtocolException;
  84. import org.openspcoop2.protocol.sdk.RestMessageSecurityToken;
  85. import org.openspcoop2.protocol.sdk.SecurityToken;
  86. import org.openspcoop2.protocol.sdk.state.IState;
  87. import org.openspcoop2.protocol.sdk.state.RequestInfo;
  88. import org.openspcoop2.protocol.utils.ModIUtils;
  89. import org.openspcoop2.security.SecurityException;
  90. import org.openspcoop2.security.keystore.CRLCertstore;
  91. import org.openspcoop2.security.keystore.cache.GestoreKeystoreCache;
  92. import org.openspcoop2.security.keystore.cache.GestoreOCSPResource;
  93. import org.openspcoop2.security.keystore.cache.GestoreOCSPValidator;
  94. import org.openspcoop2.security.message.constants.SecurityConstants;
  95. import org.openspcoop2.utils.BooleanNullable;
  96. import org.openspcoop2.utils.LoggerBuffer;
  97. import org.openspcoop2.utils.UtilsException;
  98. import org.openspcoop2.utils.certificate.CertificateInfo;
  99. import org.openspcoop2.utils.certificate.JWKSet;
  100. import org.openspcoop2.utils.certificate.remote.RemoteStoreConfig;
  101. import org.openspcoop2.utils.date.DateManager;
  102. import org.openspcoop2.utils.date.DateUtils;
  103. import org.openspcoop2.utils.io.Base64Utilities;
  104. import org.openspcoop2.utils.json.JSONUtils;
  105. import org.openspcoop2.utils.security.CertificateValidityCheck;
  106. import org.openspcoop2.utils.security.JOSESerialization;
  107. import org.openspcoop2.utils.security.JWEOptions;
  108. import org.openspcoop2.utils.security.JWSOptions;
  109. import org.openspcoop2.utils.security.JWTOptions;
  110. import org.openspcoop2.utils.security.JsonDecrypt;
  111. import org.openspcoop2.utils.security.JsonEncrypt;
  112. import org.openspcoop2.utils.security.JsonSignature;
  113. import org.openspcoop2.utils.security.JsonVerifySignature;
  114. import org.openspcoop2.utils.transport.TransportRequestContext;
  115. import org.openspcoop2.utils.transport.TransportUtils;
  116. import org.openspcoop2.utils.transport.http.HttpConstants;
  117. import org.openspcoop2.utils.transport.http.HttpRequestMethod;
  118. import org.openspcoop2.utils.transport.http.HttpResponse;
  119. import org.openspcoop2.utils.transport.http.IOCSPValidator;
  120. import org.slf4j.Logger;

  121. import com.fasterxml.jackson.databind.JsonNode;
  122. import com.fasterxml.jackson.databind.node.ArrayNode;
  123. import com.fasterxml.jackson.databind.node.ObjectNode;

  124. /**    
  125.  * GestoreTokenValidazioneUtilities
  126.  *
  127.  * @author Poli Andrea (poli@link.it)
  128.  * @author $Author$
  129.  * @version $Rev$, $Date$
  130.  */
  131. public class GestoreTokenValidazioneUtilities {

  132.     private GestoreTokenValidazioneUtilities() {}
  133.    
  134.     private static final String PREFIX_ERROR_CONNESSIONE = "(Errore di Connessione) ";
  135.    
  136.    
  137.    
  138.     // ********* [VALIDAZIONE-TOKEN] DYNAMIC DISCOVERY ****************** */
  139.        
  140.     static EsitoDynamicDiscovery dynamicDiscoveryEngine(Logger log, AbstractDatiInvocazione datiInvocazione,
  141.             PdDContext pddContext, IProtocolFactory<?> protocolFactory,
  142.             String token, boolean portaDelegata,
  143.             Busta busta, IDSoggetto idDominio, IDServizio idServizio) {
  144.        
  145.        
  146.         EsitoDynamicDiscovery esitoGestioneToken = null;
  147.         if(portaDelegata) {
  148.             esitoGestioneToken = new EsitoDynamicDiscoveryPortaDelegata();
  149.         }
  150.         else {
  151.             esitoGestioneToken = new EsitoDynamicDiscoveryPortaApplicativa();
  152.         }
  153.        
  154.         esitoGestioneToken.setTokenInternalError();
  155.         esitoGestioneToken.setToken(token);
  156.        
  157.         try{
  158.             PolicyGestioneToken policyGestioneToken = datiInvocazione.getPolicyGestioneToken();
  159.            
  160.             String detailsError = null;
  161.             DynamicDiscovery dd = null;
  162.             Exception eProcess = null;
  163.            
  164.             IDynamicDiscoveryParser ddParser = policyGestioneToken.getDynamicDiscoveryParser();
  165.            
  166.             PortaApplicativa pa = null;
  167.             PortaDelegata pd = null;
  168.             if(datiInvocazione instanceof DatiInvocazionePortaApplicativa) {
  169.                 pa = ((DatiInvocazionePortaApplicativa)datiInvocazione).getPa();
  170.             }
  171.             else if(datiInvocazione instanceof DatiInvocazionePortaDelegata) {
  172.                 pd = ((DatiInvocazionePortaDelegata)datiInvocazione).getPd();
  173.             }
  174.            
  175.             HttpResponse httpResponse = null;
  176.             Integer httpResponseCode = null;
  177.             byte[] risposta = null;
  178.             try {
  179.                 httpResponse = GestoreTokenValidazioneUtilities.http(log, policyGestioneToken, HTTP_TYPE.DYNAMIC_DISCOVERY,
  180.                         null, token,
  181.                         pddContext, protocolFactory,
  182.                         datiInvocazione.getState(), portaDelegata, datiInvocazione.getIdModulo(), pa, pd,
  183.                         idDominio, idServizio,
  184.                         busta, datiInvocazione.getRequestInfo());
  185.                 risposta = httpResponse.getContent();
  186.                 httpResponseCode = httpResponse.getResultHTTPOperation();
  187.             }catch(Exception e) {
  188.                 detailsError = PREFIX_ERROR_CONNESSIONE+ e.getMessage();
  189.                 eProcess = e;
  190.             }
  191.            
  192.             if(detailsError==null) {
  193.                 try {
  194.                     dd = new DynamicDiscovery(httpResponseCode, policyGestioneToken.getDynamicDiscoveryType(), new String(risposta),ddParser);
  195.                 }catch(Exception e) {
  196.                     detailsError = "Risposta del servizio 'Dynamic Discovery' non valida: "+e.getMessage();
  197.                     eProcess = e;
  198.                 }
  199.             }
  200.                    
  201.             if(dd!=null && dd.isValid()) {
  202.                 esitoGestioneToken.setTokenValido();
  203.                 esitoGestioneToken.setDynamicDiscovery(dd);
  204.                 esitoGestioneToken.setNoCache(false);
  205.             }
  206.             else {
  207.                 esitoGestioneToken.setTokenValidazioneFallita();
  208.                 esitoGestioneToken.setNoCache(!policyGestioneToken.isIntrospectionSaveErrorInCache());
  209.                 esitoGestioneToken.setEccezioneProcessamento(eProcess);
  210.                 if(detailsError!=null) {
  211.                     esitoGestioneToken.setDetails(detailsError);    
  212.                 }
  213.                 else {
  214.                     esitoGestioneToken.setDetails(GestoreToken.TOKEN_NON_VALIDO);  
  215.                 }
  216.                
  217.                 // comunque lo aggiungo per essere consultabile nei casi di errore se una connessione http è terminata
  218.                 if(OpenSPCoop2Properties.getInstance().isGestioneTokenSaveSourceTokenInfo() && httpResponseCode!=null) {
  219.                     dd = new DynamicDiscovery(esitoGestioneToken.getDetails(), httpResponseCode, risposta, policyGestioneToken.getDynamicDiscoveryType());
  220.                     esitoGestioneToken.setDynamicDiscovery(dd);
  221.                 }
  222.                
  223.                 if(policyGestioneToken.isMessageErrorGenerateEmptyMessage()) {
  224.                     esitoGestioneToken.setErrorMessage(WWWAuthenticateGenerator.buildErrorMessage(WWWAuthenticateErrorCode.invalid_token, policyGestioneToken.getRealm(),
  225.                             policyGestioneToken.isMessageErrorGenerateGenericMessage(), esitoGestioneToken.getDetails()));              
  226.                 }
  227.                 else {
  228.                     esitoGestioneToken.setWwwAuthenticateErrorHeader(WWWAuthenticateGenerator.buildHeaderValue(WWWAuthenticateErrorCode.invalid_token, policyGestioneToken.getRealm(),
  229.                             policyGestioneToken.isMessageErrorGenerateGenericMessage(), esitoGestioneToken.getDetails()));
  230.                 }  
  231.             }
  232.            
  233.         }catch(Exception e){
  234.             esitoGestioneToken.setTokenInternalError();
  235.             esitoGestioneToken.setDetails(e.getMessage());
  236.             esitoGestioneToken.setEccezioneProcessamento(e);
  237.         }
  238.        
  239.         return esitoGestioneToken;
  240.     }
  241.    
  242.    
  243.    
  244.    
  245.    
  246.    
  247.     // ********* [VALIDAZIONE-TOKEN] VALIDAZIONE JWT TOKEN ****************** */
  248.    
  249.     static EsitoGestioneToken validazioneJWTTokenEngine(Logger log, AbstractDatiInvocazione datiInvocazione, EsitoPresenzaToken esitoPresenzaToken, DynamicDiscovery dynamicDiscovery,
  250.             String token, boolean portaDelegata, PdDContext pddContext,
  251.             Busta busta, IDSoggetto idDominio, IDServizio idServizio) {
  252.         EsitoGestioneToken esitoGestioneToken = null;
  253.         if(portaDelegata) {
  254.             esitoGestioneToken = new EsitoGestioneTokenPortaDelegata();
  255.         }
  256.         else {
  257.             esitoGestioneToken = new EsitoGestioneTokenPortaApplicativa();
  258.         }
  259.        
  260.         esitoGestioneToken.setTokenInternalError();
  261.         esitoGestioneToken.setToken(token);
  262.        
  263.         try{
  264.             PolicyGestioneToken policyGestioneToken = datiInvocazione.getPolicyGestioneToken();
  265.             String tokenType = policyGestioneToken.getTipoToken();
  266.            
  267.             String detailsError = null;
  268.             InformazioniToken informazioniToken = null;
  269.             Exception eProcess = null;
  270.             RestMessageSecurityToken restSecurityToken = null;
  271.            
  272.             ITokenParser tokenParser = policyGestioneToken.getValidazioneJWTTokenParser();
  273.            
  274.             if(Costanti.POLICY_TOKEN_TYPE_JWS.equals(tokenType)) {
  275.                 // JWS Compact              
  276.                 JsonVerifySignature jsonCompactVerify = null;
  277.                 try {
  278.                     jsonCompactVerify = getJsonVerifySignatureJWS(log, pddContext, datiInvocazione, policyGestioneToken, dynamicDiscovery,
  279.                             busta, idDominio, idServizio,
  280.                             portaDelegata);
  281.                    
  282.                     if(jsonCompactVerify.verify(token)) {
  283.                         informazioniToken = new InformazioniToken(SorgenteInformazioniToken.JWT,jsonCompactVerify.getDecodedPayload(),tokenParser);
  284.                         if( pddContext!=null ) {
  285.                             restSecurityToken = new RestMessageSecurityToken();
  286.                             if(jsonCompactVerify.getX509Certificate()!=null) {
  287.                                 restSecurityToken.setCertificate(new CertificateInfo(jsonCompactVerify.getX509Certificate(), "access_token"));
  288.                             }
  289.                             if(jsonCompactVerify.getKid()!=null) {
  290.                                 restSecurityToken.setKid(jsonCompactVerify.getKid());
  291.                             }
  292.                             restSecurityToken.setToken(token);
  293.                             if(esitoPresenzaToken!=null) {
  294.                                 restSecurityToken.setHttpHeaderName(esitoPresenzaToken.getHeaderHttp());
  295.                                 restSecurityToken.setQueryParameterName(esitoPresenzaToken.getPropertyUrl());
  296.                                 restSecurityToken.setFormParameterName(esitoPresenzaToken.getPropertyFormBased());
  297.                             }
  298.                         }
  299.                        
  300.                         try {
  301.                             validazioneInformazioniTokenHeader(jsonCompactVerify.getDecodedHeader(), policyGestioneToken);
  302.                         }catch(Exception e) {
  303.                             informazioniToken.setValid(false);
  304.                             log.debug(GestoreToken.getMessageTokenNonValido(e),e);
  305.                             detailsError = GestoreToken.getMessageTokenNonValido(e);
  306.                             eProcess = e;
  307.                         }
  308.                     }
  309.                     else {
  310.                         detailsError = GestoreToken.TOKEN_NON_VALIDO;
  311.                     }
  312.                 }catch(Exception e) {
  313.                     log.debug(GestoreToken.getMessageTokenNonValido(e),e);
  314.                     detailsError = GestoreToken.getMessageTokenNonValido(e);
  315.                     eProcess = e;
  316.                 }
  317.             }
  318.             else {
  319.                 // JWE Compact
  320.                 JsonDecrypt jsonDecrypt = null;
  321.                 try {
  322.                     jsonDecrypt = getJsonDecrypt(log, pddContext, datiInvocazione, policyGestioneToken, dynamicDiscovery,
  323.                             busta, idDominio, idServizio,
  324.                             portaDelegata);
  325.                     jsonDecrypt.decrypt(token);
  326.                     informazioniToken = new InformazioniToken(SorgenteInformazioniToken.JWT,jsonDecrypt.getDecodedPayload(),tokenParser);
  327.                     if( pddContext!=null ) {
  328.                         restSecurityToken = new RestMessageSecurityToken();
  329.                         if(jsonDecrypt.getX509Certificate()!=null) {
  330.                             restSecurityToken.setCertificate(new CertificateInfo(jsonDecrypt.getX509Certificate(), "access_token"));
  331.                         }
  332.                         if(jsonDecrypt.getKid()!=null) {
  333.                             restSecurityToken.setKid(jsonDecrypt.getKid());
  334.                         }
  335.                         restSecurityToken.setJweDecodedPayload(jsonDecrypt.getDecodedPayload());
  336.                         restSecurityToken.setToken(token);
  337.                         if(esitoPresenzaToken!=null) {
  338.                             restSecurityToken.setHttpHeaderName(esitoPresenzaToken.getHeaderHttp());
  339.                             restSecurityToken.setQueryParameterName(esitoPresenzaToken.getPropertyUrl());
  340.                             restSecurityToken.setFormParameterName(esitoPresenzaToken.getPropertyFormBased());
  341.                         }
  342.                     }
  343.                 }catch(Exception e) {
  344.                     log.debug(GestoreToken.getMessageTokenNonValido(e),e);
  345.                     detailsError = GestoreToken.getMessageTokenNonValido(e);
  346.                     eProcess = e;
  347.                 }
  348.             }
  349.                    
  350.             if(informazioniToken!=null && informazioniToken.isValid()) {
  351.                 esitoGestioneToken.setTokenValido();
  352.                 esitoGestioneToken.setInformazioniToken(informazioniToken);
  353.                 esitoGestioneToken.setNoCache(false);
  354.                 esitoGestioneToken.setRestSecurityToken(restSecurityToken);
  355.             }
  356.             else {
  357.                 esitoGestioneToken.setTokenValidazioneFallita();
  358.                 esitoGestioneToken.setNoCache(!policyGestioneToken.isValidazioneJWTSaveErrorInCache());
  359.                 esitoGestioneToken.setEccezioneProcessamento(eProcess);
  360.                 if(detailsError!=null) {
  361.                     esitoGestioneToken.setDetails(detailsError);    
  362.                 }
  363.                 else {
  364.                     esitoGestioneToken.setDetails(GestoreToken.TOKEN_NON_VALIDO);  
  365.                 }
  366.                
  367.                 // comunque lo aggiungo per essere consultabile nei casi di errore
  368.                 if(OpenSPCoop2Properties.getInstance().isGestioneTokenSaveTokenInfoValidationFailed()) {
  369.                     informazioniToken = new InformazioniToken(esitoGestioneToken.getDetails(), SorgenteInformazioniToken.JWT, token);
  370.                     esitoGestioneToken.setInformazioniToken(informazioniToken);
  371.                 }
  372.                
  373.                 if(policyGestioneToken.isMessageErrorGenerateEmptyMessage()) {
  374.                     esitoGestioneToken.setErrorMessage(WWWAuthenticateGenerator.buildErrorMessage(WWWAuthenticateErrorCode.invalid_token, policyGestioneToken.getRealm(),
  375.                             policyGestioneToken.isMessageErrorGenerateGenericMessage(), esitoGestioneToken.getDetails()));              
  376.                 }
  377.                 else {
  378.                     esitoGestioneToken.setWwwAuthenticateErrorHeader(WWWAuthenticateGenerator.buildHeaderValue(WWWAuthenticateErrorCode.invalid_token, policyGestioneToken.getRealm(),
  379.                             policyGestioneToken.isMessageErrorGenerateGenericMessage(), esitoGestioneToken.getDetails()));
  380.                 }
  381.             }
  382.            
  383.         }catch(Exception e){
  384.             esitoGestioneToken.setTokenInternalError();
  385.             esitoGestioneToken.setDetails(e.getMessage());
  386.             esitoGestioneToken.setEccezioneProcessamento(e);
  387.         }
  388.        
  389.         return esitoGestioneToken;
  390.     }
  391.    
  392.     private static JsonVerifySignature getJsonVerifySignatureJWS(Logger log, Context context, AbstractDatiInvocazione datiInvocazione, PolicyGestioneToken policyGestioneToken, DynamicDiscovery dynamicDiscovery,
  393.             Busta busta, IDSoggetto idDominio, IDServizio idServizio,
  394.             boolean portaDelegata) throws TokenException, UtilsException, SecurityException {
  395.         // JWS Compact              
  396.         JsonVerifySignature jsonCompactVerify = null;

  397.         JWTOptions options = new JWTOptions(JOSESerialization.COMPACT);
  398.         Properties p = policyGestioneToken.getProperties().get(Costanti.POLICY_VALIDAZIONE_JWS_VERIFICA_PROP_REF_ID);
  399.         TokenUtilities.injectJOSEConfig(p, policyGestioneToken, dynamicDiscovery,  
  400.                 busta, idDominio, idServizio,
  401.                 context, log,
  402.                 datiInvocazione.getRequestInfo(), datiInvocazione.getState(), portaDelegata);
  403.        
  404.         // serve per leggere il keystore dalla cache
  405.         TokenKeystoreInjectUtilities inject = new TokenKeystoreInjectUtilities(log, datiInvocazione.getRequestInfo() ,
  406.                 datiInvocazione.getRequestInfo()!=null ? datiInvocazione.getRequestInfo().getProtocolFactory() : null,
  407.                 context, datiInvocazione.getState(), busta);
  408.         if(datiInvocazione instanceof DatiInvocazionePortaApplicativa) {
  409.             DatiInvocazionePortaApplicativa dati = (DatiInvocazionePortaApplicativa) datiInvocazione;
  410.             inject.initTokenPolicyValidazioneJwt(policyGestioneToken.getName(), portaDelegata, dati.getPd(), dati.getPa(), p);
  411.         }
  412.         else {
  413.             DatiInvocazionePortaDelegata dati = (DatiInvocazionePortaDelegata) datiInvocazione;
  414.             inject.initTokenPolicyValidazioneJwt(policyGestioneToken.getName(), portaDelegata, dati.getPd(), null, p);
  415.         }
  416.         inject.inject(p);
  417.        
  418.        
  419.         String aliasMode = p.getProperty(SecurityConstants.JOSE_KEYSTORE_KEY_ALIAS+".mode");
  420.         if(aliasMode!=null &&
  421.                 (
  422.                         aliasMode.equals(Costanti.ID_VALIDAZIONE_JWT_TRUSTSTORE_TYPE_SELECT_CERTIFICATE_VALUE_X5C)
  423.                         ||
  424.                         aliasMode.equals(Costanti.ID_VALIDAZIONE_JWT_TRUSTSTORE_TYPE_SELECT_CERTIFICATE_VALUE_X5T256)
  425.                         ||
  426.                         aliasMode.equals(Costanti.ID_VALIDAZIONE_JWT_TRUSTSTORE_TYPE_SELECT_CERTIFICATE_VALUE_X5C_X5T256)
  427.                         ||
  428.                         aliasMode.equals(Costanti.ID_VALIDAZIONE_JWT_TRUSTSTORE_TYPE_SELECT_CERTIFICATE_VALUE_KID)
  429.                         ||
  430.                         aliasMode.equals(Costanti.ID_VALIDAZIONE_JWT_TRUSTSTORE_TYPE_SELECT_CERTIFICATE_VALUE_X5U)
  431.                 )
  432.             ) {
  433.            
  434.             options.setPermitUseHeaderX5C(aliasMode.equals(Costanti.ID_VALIDAZIONE_JWT_TRUSTSTORE_TYPE_SELECT_CERTIFICATE_VALUE_X5C) || aliasMode.equals(Costanti.ID_VALIDAZIONE_JWT_TRUSTSTORE_TYPE_SELECT_CERTIFICATE_VALUE_X5C_X5T256));
  435.             // se lo si vuole usare utilizzare la vecchia modalità alias special case
  436.             /**options.setPermitUseHeaderX5T(aliasMode.equals(Costanti.ID_VALIDAZIONE_JWT_TRUSTSTORE_TYPE_SELECT_CERTIFICATE_VALUE_X5T256) || aliasMode.equals(Costanti.ID_VALIDAZIONE_JWT_TRUSTSTORE_TYPE_SELECT_CERTIFICATE_VALUE_X5C_X5T256));*/
  437.             options.setPermitUseHeaderX5T_256(aliasMode.equals(Costanti.ID_VALIDAZIONE_JWT_TRUSTSTORE_TYPE_SELECT_CERTIFICATE_VALUE_X5T256) || aliasMode.equals(Costanti.ID_VALIDAZIONE_JWT_TRUSTSTORE_TYPE_SELECT_CERTIFICATE_VALUE_X5C_X5T256));
  438.             options.setPermitUseHeaderKID(aliasMode.equals(Costanti.ID_VALIDAZIONE_JWT_TRUSTSTORE_TYPE_SELECT_CERTIFICATE_VALUE_KID));
  439.             options.setPermitUseHeaderX5U(aliasMode.equals(Costanti.ID_VALIDAZIONE_JWT_TRUSTSTORE_TYPE_SELECT_CERTIFICATE_VALUE_X5U));
  440.                                    
  441.             if(p.containsKey(SecurityConstants.JOSE_KEYSTORE)) {
  442.                 Object oKeystore = p.get(SecurityConstants.JOSE_KEYSTORE);
  443.                 if(oKeystore instanceof java.security.KeyStore) {
  444.                     java.security.KeyStore keystore = (java.security.KeyStore) oKeystore;
  445.                     jsonCompactVerify = new JsonVerifySignature(keystore, options);
  446.                    
  447.                     CertificateValidityCheck validityCheck = OpenSPCoop2Properties.getInstance().getGestioneTokenValidityCheck();
  448.                     List<Proprieta> proprieta = null;
  449.                     if(datiInvocazione instanceof DatiInvocazionePortaApplicativa) {
  450.                         DatiInvocazionePortaApplicativa dati = (DatiInvocazionePortaApplicativa)datiInvocazione;
  451.                         if(dati.getPa()!=null) {
  452.                             proprieta = dati.getPa().getProprietaList();
  453.                         }
  454.                         else if(dati.getPd()!=null) {
  455.                             proprieta = dati.getPd().getProprietaList();
  456.                         }
  457.                     }
  458.                     else if(datiInvocazione instanceof DatiInvocazionePortaDelegata) {
  459.                         DatiInvocazionePortaDelegata dati = (DatiInvocazionePortaDelegata)datiInvocazione;
  460.                         if(dati.getPd()!=null) {
  461.                             proprieta = dati.getPd().getProprietaList();
  462.                         }
  463.                     }
  464.                     validityCheck = CostantiProprieta.getTokenValidationCertificateValidityCheck(proprieta, validityCheck);
  465.                     jsonCompactVerify.setValidityCheck(validityCheck);
  466.                    
  467.                     String signatureOCSP = policyGestioneToken.getValidazioneJWTOcspPolicy();
  468.                     String signatureCRL = policyGestioneToken.getValidazioneJWTCrl();
  469.                    
  470.                     boolean crlByOcsp = false;
  471.                     if(signatureOCSP!=null && !"".equals(signatureOCSP)) {
  472.                         LoggerBuffer lb = new LoggerBuffer();
  473.                         lb.setLogDebug(log);
  474.                         lb.setLogError(log);
  475.                         GestoreOCSPResource ocspResourceReader = new GestoreOCSPResource(datiInvocazione.getRequestInfo());
  476.                         IOCSPValidator ocspValidator = null;
  477.                         try {
  478.                             org.openspcoop2.utils.certificate.KeyStore trustStore = new org.openspcoop2.utils.certificate.KeyStore(keystore);
  479.                             ocspValidator = new GestoreOCSPValidator(datiInvocazione.getRequestInfo(), lb,
  480.                                     trustStore,
  481.                                     signatureCRL,
  482.                                     signatureOCSP,
  483.                                     ocspResourceReader);
  484.                         }catch(Exception e){
  485.                             throw new TokenException("ocsp initialization (policy:'"+signatureOCSP+"') failed: "+e.getMessage(),e);
  486.                         }
  487.                         jsonCompactVerify.setOcspValidatorX509(ocspValidator);
  488.                         GestoreOCSPValidator gOcspValidator = (GestoreOCSPValidator) ocspValidator;
  489.                         if(gOcspValidator.getOcspConfig()!=null) {
  490.                             crlByOcsp = gOcspValidator.getOcspConfig().isCrl();
  491.                         }
  492.                     }
  493.                    
  494.                     if(signatureCRL!=null && !"".equals(signatureCRL) && !crlByOcsp) {
  495.                         CRLCertstore crlCertstore = GestoreKeystoreCache.getCRLCertstore(datiInvocazione.getRequestInfo(), signatureCRL);
  496.                         if(crlCertstore==null) {
  497.                             throw new TokenException("Process CRL '"+signatureCRL+"' failed");
  498.                         }
  499.                         jsonCompactVerify.setCrlX509(crlCertstore.getCertStore());
  500.                     }

  501.                 }
  502.             }
  503.             else if(p.containsKey(SecurityConstants.JOSE_KEYSTORE_JWKSET)) {
  504.                 Object oKeystore = p.get(SecurityConstants.JOSE_KEYSTORE_JWKSET);
  505.                 if(oKeystore instanceof String) {
  506.                     String keystore = (String) oKeystore;
  507.                     JsonWebKeys jwksKeystore = new JWKSet(keystore).getJsonWebKeys();
  508.                     jsonCompactVerify = new JsonVerifySignature(jwksKeystore, options);
  509.                 }
  510.             }
  511.         }
  512.                            
  513.         if(jsonCompactVerify==null &&
  514.             p.containsKey(SecurityConstants.JOSE_KEYSTORE_KEY_ALIAS)) {
  515.             String alias = p.getProperty(SecurityConstants.JOSE_KEYSTORE_KEY_ALIAS);
  516.             if(alias!=null &&
  517.                     (
  518.                             alias.equals(Costanti.POLICY_VALIDAZIONE_SPECIAL_CASE_USE_X5C)
  519.                             ||
  520.                             alias.equals(Costanti.POLICY_VALIDAZIONE_SPECIAL_CASE_USE_X5T)
  521.                             ||
  522.                             alias.equals(Costanti.POLICY_VALIDAZIONE_SPECIAL_CASE_USE_X5C_X5T)
  523.                     )
  524.                 &&
  525.                 (p.containsKey(SecurityConstants.JOSE_KEYSTORE)) // backward compatibility
  526.                 ){
  527.                 Object oKeystore = p.get(SecurityConstants.JOSE_KEYSTORE);
  528.                 if(oKeystore instanceof java.security.KeyStore) {
  529.                     java.security.KeyStore keystore = (java.security.KeyStore) oKeystore;
  530.                     options.setPermitUseHeaderX5C(alias.equals(Costanti.POLICY_VALIDAZIONE_SPECIAL_CASE_USE_X5C) || alias.equals(Costanti.POLICY_VALIDAZIONE_SPECIAL_CASE_USE_X5C_X5T));
  531.                     options.setPermitUseHeaderX5T(alias.equals(Costanti.POLICY_VALIDAZIONE_SPECIAL_CASE_USE_X5T) || alias.equals(Costanti.POLICY_VALIDAZIONE_SPECIAL_CASE_USE_X5C_X5T));
  532.                     options.setPermitUseHeaderX5T_256(alias.equals(Costanti.POLICY_VALIDAZIONE_SPECIAL_CASE_USE_X5T) || alias.equals(Costanti.POLICY_VALIDAZIONE_SPECIAL_CASE_USE_X5C_X5T));
  533.                     jsonCompactVerify = new JsonVerifySignature(keystore, options);
  534.                 }
  535.             }  
  536.         }
  537.        
  538.         if(jsonCompactVerify==null) {
  539.             jsonCompactVerify = new JsonVerifySignature(p, options);
  540.         }
  541.        
  542.         jsonCompactVerify.setJksPasswordRequired(DBUtils.isTruststoreJksPasswordRequired());
  543.         jsonCompactVerify.setPkcs12PasswordRequired(DBUtils.isTruststorePkcs12PasswordRequired());
  544.        
  545.         return jsonCompactVerify;
  546.     }
  547.    
  548.     private static JsonDecrypt getJsonDecrypt(Logger log, Context context, AbstractDatiInvocazione datiInvocazione, PolicyGestioneToken policyGestioneToken, DynamicDiscovery dynamicDiscovery,
  549.             Busta busta, IDSoggetto idDominio, IDServizio idServizio,
  550.             boolean portaDelegata) throws TokenException, UtilsException, SecurityException {
  551.         JsonDecrypt jsonDecrypt = null;
  552.         JWTOptions options = new JWTOptions(JOSESerialization.COMPACT);
  553.         Properties p = policyGestioneToken.getProperties().get(Costanti.POLICY_VALIDAZIONE_JWE_DECRYPT_PROP_REF_ID);
  554.         TokenUtilities.injectJOSEConfig(p, policyGestioneToken, dynamicDiscovery,  
  555.                 busta, idDominio, idServizio,
  556.                 context, log,
  557.                 datiInvocazione.getRequestInfo(), datiInvocazione.getState(), portaDelegata);
  558.        
  559.         // serve per leggere il keystore dalla cache
  560.         TokenKeystoreInjectUtilities inject = new TokenKeystoreInjectUtilities(log, datiInvocazione.getRequestInfo() ,
  561.                 datiInvocazione.getRequestInfo()!=null ? datiInvocazione.getRequestInfo().getProtocolFactory() : null,
  562.                 context, datiInvocazione.getState(), busta);
  563.         if(datiInvocazione instanceof DatiInvocazionePortaApplicativa) {
  564.             DatiInvocazionePortaApplicativa dati = (DatiInvocazionePortaApplicativa) datiInvocazione;
  565.             inject.initTokenPolicyValidazioneJwt(policyGestioneToken.getName(), portaDelegata, dati.getPd(), dati.getPa(), p);
  566.         }
  567.         else {
  568.             DatiInvocazionePortaDelegata dati = (DatiInvocazionePortaDelegata) datiInvocazione;
  569.             inject.initTokenPolicyValidazioneJwt(policyGestioneToken.getName(), portaDelegata, dati.getPd(), null, p);
  570.         }
  571.         inject.inject(p);
  572.        
  573.         jsonDecrypt = new JsonDecrypt(p, options,
  574.                 DBUtils.isKeystoreJksPasswordRequired(),
  575.                 DBUtils.isKeystorePkcs12PasswordRequired());
  576.        
  577.         return jsonDecrypt;
  578.     }
  579.    
  580.    
  581.    
  582.    
  583.     // ********* [VALIDAZIONE-TOKEN] INTROSPECTION TOKEN ****************** */
  584.    
  585.     static EsitoGestioneToken introspectionTokenEngine(Logger log, AbstractDatiInvocazione datiInvocazione,  
  586.             PdDContext pddContext, IProtocolFactory<?> protocolFactory,
  587.             DynamicDiscovery dynamicDiscovery,
  588.             String token, boolean portaDelegata,
  589.             Busta busta, IDSoggetto idDominio, IDServizio idServizio) {
  590.         EsitoGestioneToken esitoGestioneToken = null;
  591.         if(portaDelegata) {
  592.             esitoGestioneToken = new EsitoGestioneTokenPortaDelegata();
  593.         }
  594.         else {
  595.             esitoGestioneToken = new EsitoGestioneTokenPortaApplicativa();
  596.         }
  597.        
  598.         esitoGestioneToken.setTokenInternalError();
  599.         esitoGestioneToken.setToken(token);
  600.        
  601.         try{
  602.             PolicyGestioneToken policyGestioneToken = datiInvocazione.getPolicyGestioneToken();
  603.            
  604.             String detailsError = null;
  605.             InformazioniToken informazioniToken = null;
  606.             Exception eProcess = null;
  607.            
  608.             ITokenParser tokenParser = policyGestioneToken.getIntrospectionTokenParser();
  609.            
  610.             PortaApplicativa pa = null;
  611.             PortaDelegata pd = null;
  612.             if(datiInvocazione instanceof DatiInvocazionePortaApplicativa) {
  613.                 pa = ((DatiInvocazionePortaApplicativa)datiInvocazione).getPa();
  614.             }
  615.             else if(datiInvocazione instanceof DatiInvocazionePortaDelegata) {
  616.                 pd = ((DatiInvocazionePortaDelegata)datiInvocazione).getPd();
  617.             }
  618.            
  619.             HttpResponse httpResponse = null;
  620.             Integer httpResponseCode = null;
  621.             byte[] risposta = null;
  622.             try {
  623.                 httpResponse = GestoreTokenValidazioneUtilities.http(log, policyGestioneToken, HTTP_TYPE.INTROSPECTION,
  624.                         dynamicDiscovery, token,
  625.                         pddContext, protocolFactory,
  626.                         datiInvocazione.getState(), portaDelegata, datiInvocazione.getIdModulo(), pa, pd,
  627.                         idDominio, idServizio,
  628.                         busta, datiInvocazione.getRequestInfo());
  629.                 risposta = httpResponse.getContent();
  630.                 httpResponseCode = httpResponse.getResultHTTPOperation();
  631.             }catch(Exception e) {
  632.                 detailsError = PREFIX_ERROR_CONNESSIONE+ e.getMessage();
  633.                 eProcess = e;
  634.             }
  635.            
  636.             if(detailsError==null) {
  637.                 try {
  638.                     informazioniToken = new InformazioniToken(httpResponseCode, SorgenteInformazioniToken.INTROSPECTION, new String(risposta),tokenParser);
  639.                 }catch(Exception e) {
  640.                     detailsError = "Risposta del servizio di Introspection non valida: "+e.getMessage();
  641.                     eProcess = e;
  642.                 }
  643.             }
  644.                    
  645.             if(informazioniToken!=null && informazioniToken.isValid()) {
  646.                 esitoGestioneToken.setTokenValido();
  647.                 esitoGestioneToken.setInformazioniToken(informazioniToken);
  648.                 esitoGestioneToken.setNoCache(false);
  649.             }
  650.             else {
  651.                 esitoGestioneToken.setTokenValidazioneFallita();
  652.                 esitoGestioneToken.setNoCache(!policyGestioneToken.isIntrospectionSaveErrorInCache());
  653.                 esitoGestioneToken.setEccezioneProcessamento(eProcess);
  654.                 if(detailsError!=null) {
  655.                     esitoGestioneToken.setDetails(detailsError);    
  656.                 }
  657.                 else {
  658.                     esitoGestioneToken.setDetails(GestoreToken.TOKEN_NON_VALIDO);  
  659.                 }
  660.                
  661.                 // comunque lo aggiungo per essere consultabile nei casi di errore se una connessione http è terminata
  662.                 if(OpenSPCoop2Properties.getInstance().isGestioneTokenSaveSourceTokenInfo() && httpResponseCode!=null) {
  663.                     informazioniToken = new InformazioniToken(esitoGestioneToken.getDetails(), httpResponseCode, risposta, SorgenteInformazioniToken.INTROSPECTION, token);
  664.                     esitoGestioneToken.setInformazioniToken(informazioniToken);
  665.                 }
  666.                
  667.                 if(policyGestioneToken.isMessageErrorGenerateEmptyMessage()) {
  668.                     esitoGestioneToken.setErrorMessage(WWWAuthenticateGenerator.buildErrorMessage(WWWAuthenticateErrorCode.invalid_token, policyGestioneToken.getRealm(),
  669.                             policyGestioneToken.isMessageErrorGenerateGenericMessage(), esitoGestioneToken.getDetails()));              
  670.                 }
  671.                 else {
  672.                     esitoGestioneToken.setWwwAuthenticateErrorHeader(WWWAuthenticateGenerator.buildHeaderValue(WWWAuthenticateErrorCode.invalid_token, policyGestioneToken.getRealm(),
  673.                             policyGestioneToken.isMessageErrorGenerateGenericMessage(), esitoGestioneToken.getDetails()));
  674.                 }  
  675.             }
  676.            
  677.         }catch(Exception e){
  678.             esitoGestioneToken.setTokenInternalError();
  679.             esitoGestioneToken.setDetails(e.getMessage());
  680.             esitoGestioneToken.setEccezioneProcessamento(e);
  681.         }
  682.        
  683.         return esitoGestioneToken;
  684.     }
  685.    
  686.    
  687.    
  688.    
  689.     // ********* [VALIDAZIONE-TOKEN] USER INFO TOKEN ****************** */
  690.    
  691.     static EsitoGestioneToken userInfoTokenEngine(Logger log, AbstractDatiInvocazione datiInvocazione,
  692.             PdDContext pddContext, IProtocolFactory<?> protocolFactory,
  693.             DynamicDiscovery dynamicDiscovery,
  694.             String token, boolean portaDelegata,
  695.             Busta busta, IDSoggetto idDominio, IDServizio idServizio) {
  696.         EsitoGestioneToken esitoGestioneToken = null;
  697.         if(portaDelegata) {
  698.             esitoGestioneToken = new EsitoGestioneTokenPortaDelegata();
  699.         }
  700.         else {
  701.             esitoGestioneToken = new EsitoGestioneTokenPortaApplicativa();
  702.         }
  703.        
  704.         esitoGestioneToken.setTokenInternalError();
  705.         esitoGestioneToken.setToken(token);
  706.        
  707.         try{
  708.             PolicyGestioneToken policyGestioneToken = datiInvocazione.getPolicyGestioneToken();
  709.            
  710.             String detailsError = null;
  711.             InformazioniToken informazioniToken = null;
  712.             Exception eProcess = null;
  713.            
  714.             ITokenParser tokenParser = policyGestioneToken.getUserInfoTokenParser();
  715.            
  716.             PortaApplicativa pa = null;
  717.             PortaDelegata pd = null;
  718.             if(datiInvocazione instanceof DatiInvocazionePortaApplicativa) {
  719.                 pa = ((DatiInvocazionePortaApplicativa)datiInvocazione).getPa();
  720.             }
  721.             else if(datiInvocazione instanceof DatiInvocazionePortaDelegata) {
  722.                 pd = ((DatiInvocazionePortaDelegata)datiInvocazione).getPd();
  723.             }
  724.            
  725.             HttpResponse httpResponse = null;
  726.             Integer httpResponseCode = null;
  727.             byte[] risposta = null;
  728.             try {
  729.                 httpResponse = http(log, policyGestioneToken, HTTP_TYPE.USER_INFO,
  730.                         dynamicDiscovery, token,
  731.                         pddContext, protocolFactory,
  732.                         datiInvocazione.getState(), portaDelegata, datiInvocazione.getIdModulo(), pa, pd,
  733.                         idDominio, idServizio,
  734.                         busta, datiInvocazione.getRequestInfo());
  735.                 risposta = httpResponse.getContent();
  736.                 httpResponseCode = httpResponse.getResultHTTPOperation();
  737.             }catch(Exception e) {
  738.                 detailsError = PREFIX_ERROR_CONNESSIONE+ e.getMessage();
  739.                 eProcess = e;
  740.             }
  741.            
  742.             if(detailsError==null) {
  743.                 try {
  744.                     informazioniToken = new InformazioniToken(httpResponseCode, SorgenteInformazioniToken.USER_INFO, new String(risposta),tokenParser);
  745.                 }catch(Exception e) {
  746.                     detailsError = "Risposta del servizio di UserInfo non valida: "+e.getMessage();
  747.                     eProcess = e;
  748.                 }
  749.             }
  750.                    
  751.             if(informazioniToken!=null && informazioniToken.isValid()) {
  752.                 esitoGestioneToken.setTokenValido();
  753.                 esitoGestioneToken.setInformazioniToken(informazioniToken);
  754.                 esitoGestioneToken.setNoCache(false);
  755.             }
  756.             else {
  757.                 esitoGestioneToken.setTokenValidazioneFallita();
  758.                 esitoGestioneToken.setNoCache(!policyGestioneToken.isUserInfoSaveErrorInCache());
  759.                 esitoGestioneToken.setEccezioneProcessamento(eProcess);
  760.                 if(detailsError!=null) {
  761.                     esitoGestioneToken.setDetails(detailsError);    
  762.                 }
  763.                 else {
  764.                     esitoGestioneToken.setDetails(GestoreToken.TOKEN_NON_VALIDO);  
  765.                 }
  766.                
  767.                 // comunque lo aggiungo per essere consultabile nei casi di errore se una connessione http è terminata
  768.                 if(OpenSPCoop2Properties.getInstance().isGestioneTokenSaveSourceTokenInfo() && httpResponseCode!=null) {
  769.                     informazioniToken = new InformazioniToken(esitoGestioneToken.getDetails(), httpResponseCode, risposta, SorgenteInformazioniToken.USER_INFO, token);
  770.                     esitoGestioneToken.setInformazioniToken(informazioniToken);
  771.                 }
  772.                
  773.                 if(policyGestioneToken.isMessageErrorGenerateEmptyMessage()) {
  774.                     esitoGestioneToken.setErrorMessage(WWWAuthenticateGenerator.buildErrorMessage(WWWAuthenticateErrorCode.invalid_token, policyGestioneToken.getRealm(),
  775.                             policyGestioneToken.isMessageErrorGenerateGenericMessage(), esitoGestioneToken.getDetails()));              
  776.                 }
  777.                 else {
  778.                     esitoGestioneToken.setWwwAuthenticateErrorHeader(WWWAuthenticateGenerator.buildHeaderValue(WWWAuthenticateErrorCode.invalid_token, policyGestioneToken.getRealm(),
  779.                             policyGestioneToken.isMessageErrorGenerateGenericMessage(), esitoGestioneToken.getDetails()));
  780.                 }      
  781.             }
  782.            
  783.         }catch(Exception e){
  784.             esitoGestioneToken.setTokenInternalError();
  785.             esitoGestioneToken.setDetails(e.getMessage());
  786.             esitoGestioneToken.setEccezioneProcessamento(e);
  787.         }
  788.        
  789.         return esitoGestioneToken;
  790.     }
  791.    
  792.    
  793.    
  794.    
  795.    
  796.     // ********* [VALIDAZIONE-TOKEN] FORWARD TOKEN ****************** */
  797.    
  798.     static boolean deleteTokenReceived(AbstractDatiInvocazione datiInvocazione, EsitoPresenzaToken esitoPresenzaToken,
  799.             boolean trasparente, String forwardTrasparenteModeHeader, String forwardTrasparenteModeUrl) throws TokenException {
  800.        
  801.         PolicyGestioneToken policyGestioneToken = datiInvocazione.getPolicyGestioneToken();
  802.        
  803.         boolean remove = false;
  804.         if(esitoPresenzaToken.getHeaderHttp()!=null) {
  805.             if(
  806.                 (!policyGestioneToken.isForwardToken())
  807.                 ||
  808.                 (!trasparente)
  809.                 ||
  810.                 (!esitoPresenzaToken.getHeaderHttp().equalsIgnoreCase(forwardTrasparenteModeHeader))
  811.             ){
  812.                 remove = true;
  813.             }
  814.             if(remove) {
  815.                 datiInvocazione.getMessage().getTransportRequestContext().removeHeader(esitoPresenzaToken.getHeaderHttp());
  816.             }
  817.         }
  818.         else if(esitoPresenzaToken.getPropertyUrl()!=null) {
  819.             if(
  820.                 (!policyGestioneToken.isForwardToken())
  821.                 ||  
  822.                 (!trasparente)
  823.                 ||
  824.                 (!esitoPresenzaToken.getPropertyUrl().equals(forwardTrasparenteModeUrl))
  825.             ){
  826.                 remove = true;
  827.             }
  828.             if(remove) {
  829.                 datiInvocazione.getMessage().getTransportRequestContext().removeParameter(esitoPresenzaToken.getPropertyUrl());
  830.             }
  831.         }
  832.         else if(esitoPresenzaToken.getPropertyFormBased()!=null) {
  833.             if(
  834.                 (!policyGestioneToken.isForwardToken())
  835.                 ||
  836.                 (!trasparente)
  837.             ){
  838.                 remove = true;
  839.             }
  840.             if(remove) {
  841.                 try {
  842.                     byte[] contenuto = datiInvocazione.getMessage().castAsRestBinary().getContent().getContent(); // dovrebbe essere un binary
  843.                     // MyVariableOne=ValueOne&MyVariableTwo=ValueTwo
  844.                     String contenutoAsString = new String(contenuto);
  845.                     String [] split = contenutoAsString.split("&");
  846.                     StringBuilder bf = new StringBuilder();
  847.                     for (int i = 0; i < split.length; i++) {
  848.                         String nameValue = split[i];
  849.                         if(nameValue.contains("=")) {
  850.                             String [] tmp = nameValue.split("=");
  851.                             String name = tmp[0];
  852.                             String value = tmp[1];
  853.                             if(!esitoPresenzaToken.getPropertyFormBased().equals(name)) {
  854.                                 bf.append(name).append("=").append(value);
  855.                             }
  856.                         }
  857.                         else {
  858.                             if(bf.length()>0) {
  859.                                 bf.append("&");
  860.                             }
  861.                             bf.append(nameValue);
  862.                         }
  863.                     }
  864.                     if(bf.length()>0) {
  865.                         byte [] newContenuto = bf.toString().getBytes();
  866.                         ((OpenSPCoop2Message_binary_impl)datiInvocazione.getMessage().castAsRestBinary()).updateContent(newContenuto);
  867.                     }
  868.                     else {
  869.                         datiInvocazione.getMessage().castAsRestBinary().updateContent(null);
  870.                     }
  871.                 }catch(Exception e) {
  872.                     throw new TokenException(e.getMessage(),e);
  873.                 }
  874.             }
  875.         }
  876.         return remove;
  877.     }
  878.    
  879.     static void forwardTokenTrasparenteEngine(String token, EsitoPresenzaToken esitoPresenzaToken, TokenForward tokenForward,
  880.             String forwardTrasparenteMode, String forwardTrasparenteModeHeader, String forwardTrasparenteModeUrl) throws TokenException {
  881.         if(Costanti.POLICY_TOKEN_FORWARD_TRASPARENTE_MODE_AS_RECEIVED.equals(forwardTrasparenteMode)) {
  882.             if(esitoPresenzaToken.getHeaderHttp()!=null) {
  883.                 if(HttpConstants.AUTHORIZATION.equals(esitoPresenzaToken.getHeaderHttp())) {
  884.                     TransportUtils.setHeader(tokenForward.getTrasporto(),HttpConstants.AUTHORIZATION, HttpConstants.AUTHORIZATION_PREFIX_BEARER+token);
  885.                 }
  886.                 else {
  887.                     TransportUtils.setHeader(tokenForward.getTrasporto(),esitoPresenzaToken.getHeaderHttp(), token);
  888.                 }
  889.             }
  890.             else if(esitoPresenzaToken.getPropertyUrl()!=null) {
  891.                 TransportUtils.setParameter(tokenForward.getUrl(),esitoPresenzaToken.getPropertyUrl(), token);
  892.             }
  893.             else if(esitoPresenzaToken.getPropertyFormBased()!=null) {
  894.                 throw new TokenException("Configurazione non supportata"); // non dovrebbe mai entrare in questo ramo poichè il token non viene eliminato
  895.             }
  896.         }
  897.         else if(Costanti.POLICY_TOKEN_FORWARD_TRASPARENTE_MODE_RFC6750_HEADER.equals(forwardTrasparenteMode)) {
  898.             TransportUtils.setHeader(tokenForward.getTrasporto(),HttpConstants.AUTHORIZATION, HttpConstants.AUTHORIZATION_PREFIX_BEARER+token);
  899.         }
  900.         else if(Costanti.POLICY_TOKEN_FORWARD_TRASPARENTE_MODE_RFC6750_URL.equals(forwardTrasparenteMode)) {
  901.             TransportUtils.setParameter(tokenForward.getUrl(),Costanti.RFC6750_URI_QUERY_PARAMETER_ACCESS_TOKEN, token);
  902.         }
  903.         else if(Costanti.POLICY_TOKEN_FORWARD_TRASPARENTE_MODE_CUSTOM_HEADER.equals(forwardTrasparenteMode)) {
  904.             TransportUtils.setHeader(tokenForward.getTrasporto(),forwardTrasparenteModeHeader, token);
  905.         }
  906.         else if(Costanti.POLICY_TOKEN_FORWARD_TRASPARENTE_MODE_CUSTOM_URL.equals(forwardTrasparenteMode)) {
  907.             TransportUtils.setParameter(tokenForward.getUrl(),forwardTrasparenteModeUrl, token);
  908.         }
  909.     }
  910.    
  911.     static void forwardInfomazioniRaccolteEngine(boolean portaDelegata, String idTransazione, TokenForward tokenForward,
  912.             EsitoGestioneToken esitoValidazioneJWT, EsitoGestioneToken esitoIntrospection, EsitoGestioneToken esitoUserInfo,
  913.             InformazioniToken informazioniTokenNormalizzate,
  914.             String forwardInforRaccolteMode, Properties jwtSecurity, boolean encodeBase64,
  915.             boolean forwardValidazioneJWT, String forwardValidazioneJWTMode, String forwardValidazioneJWTName,
  916.             boolean forwardIntrospection, String forwardIntrospectionMode, String forwardIntrospectionName,
  917.             boolean forwardUserInfo, String forwardUserInfoMode, String forwardUserInfoName) throws CoreException, UtilsException {
  918.        
  919.         if(informazioniTokenNormalizzate==null) {
  920.             return; // può succedere nei casi warning only, significa che non vi sono token validi
  921.         }
  922.        
  923.         if(Costanti.POLICY_TOKEN_FORWARD_INFO_RACCOLTE_MODE_OP2_HEADERS.equals(forwardInforRaccolteMode) ||
  924.                 Costanti.POLICY_TOKEN_FORWARD_INFO_RACCOLTE_MODE_OP2_JSON.equals(forwardInforRaccolteMode) ||
  925.                 Costanti.POLICY_TOKEN_FORWARD_INFO_RACCOLTE_MODE_OP2_JWS.equals(forwardInforRaccolteMode)) {
  926.            
  927.             OpenSPCoop2Properties properties = OpenSPCoop2Properties.getInstance();
  928.             Map<String,String> headerNames = null;
  929.             Map<String, Boolean> set = null;
  930.             JSONUtils jsonUtils = null;
  931.             ObjectNode jsonNode = null;
  932.             boolean op2headers = Costanti.POLICY_TOKEN_FORWARD_INFO_RACCOLTE_MODE_OP2_HEADERS.equals(forwardInforRaccolteMode);
  933.             SimpleDateFormat sdf = null;
  934.             if(op2headers) {
  935.                 headerNames = properties.getKeyValueGestioneTokenHeaderIntegrazioneTrasporto();
  936.                 if(portaDelegata) {
  937.                     set = properties.getKeyPDSetEnabledGestioneTokenHeaderIntegrazioneTrasporto();
  938.                 }
  939.                 else {
  940.                     set = properties.getKeyPASetEnabledGestioneTokenHeaderIntegrazioneTrasporto();
  941.                 }
  942.                 String pattern = properties.getGestioneTokenFormatDate();
  943.                 if(pattern!=null && !"".equals(pattern)) {
  944.                     sdf = DateUtils.getDefaultDateTimeFormatter(pattern);
  945.                 }
  946.             }
  947.             else {
  948.                 if(portaDelegata) {
  949.                     set = properties.getKeyPDSetEnabledGestioneTokenHeaderIntegrazioneJson();
  950.                 }
  951.                 else {
  952.                     set = properties.getKeyPASetEnabledGestioneTokenHeaderIntegrazioneJson();
  953.                 }
  954.                 jsonUtils = JSONUtils.getInstance();
  955.                 jsonNode = jsonUtils.newObjectNode();
  956.                 jsonNode.put("id", idTransazione);
  957.             }
  958.            
  959.             if(informazioniTokenNormalizzate.getIss()!=null &&
  960.                 set.get(CostantiPdD.HEADER_INTEGRAZIONE_TOKEN_ISSUER).booleanValue()) {
  961.                 if(op2headers) {
  962.                     TransportUtils.setHeader(tokenForward.getTrasporto(),headerNames.get(CostantiPdD.HEADER_INTEGRAZIONE_TOKEN_ISSUER), informazioniTokenNormalizzate.getIss());
  963.                 }
  964.                 else {
  965.                     jsonNode.put("issuer", informazioniTokenNormalizzate.getIss());
  966.                 }
  967.             }
  968.             if(informazioniTokenNormalizzate.getSub()!=null &&
  969.                 set.get(CostantiPdD.HEADER_INTEGRAZIONE_TOKEN_SUBJECT).booleanValue()) {
  970.                 if(op2headers) {
  971.                     TransportUtils.setHeader(tokenForward.getTrasporto(),headerNames.get(CostantiPdD.HEADER_INTEGRAZIONE_TOKEN_SUBJECT), informazioniTokenNormalizzate.getSub());
  972.                 }
  973.                 else {
  974.                     jsonNode.put("subject", informazioniTokenNormalizzate.getSub());
  975.                 }
  976.             }
  977.             if(informazioniTokenNormalizzate.getUsername()!=null &&
  978.                 set.get(CostantiPdD.HEADER_INTEGRAZIONE_TOKEN_USERNAME).booleanValue()) {
  979.                 if(op2headers) {
  980.                     TransportUtils.setHeader(tokenForward.getTrasporto(),headerNames.get(CostantiPdD.HEADER_INTEGRAZIONE_TOKEN_USERNAME), informazioniTokenNormalizzate.getUsername());
  981.                 }
  982.                 else {
  983.                     jsonNode.put("username", informazioniTokenNormalizzate.getUsername());
  984.                 }
  985.             }
  986.             if(informazioniTokenNormalizzate.getAud()!=null &&
  987.                 set.get(CostantiPdD.HEADER_INTEGRAZIONE_TOKEN_AUDIENCE).booleanValue()) {
  988.                 ArrayNode array = null;
  989.                 StringBuilder bf = new StringBuilder();
  990.                 if(!op2headers) {
  991.                     array =  jsonUtils.newArrayNode();
  992.                 }
  993.                 for (String role : informazioniTokenNormalizzate.getAud()) {
  994.                     if(op2headers) {
  995.                         if(bf.length()>0) {
  996.                             bf.append(properties.getGestioneTokenHeaderIntegrazioneTrasportoAudienceSeparator());
  997.                         }
  998.                         bf.append(role);
  999.                     }
  1000.                     else {
  1001.                         array.add(role);
  1002.                     }
  1003.                 }
  1004.                 if(op2headers) {
  1005.                     TransportUtils.setHeader(tokenForward.getTrasporto(),headerNames.get(CostantiPdD.HEADER_INTEGRAZIONE_TOKEN_AUDIENCE), bf.toString());
  1006.                 }
  1007.                 else {
  1008.                     jsonNode.set("audience", array);
  1009.                 }
  1010.             }
  1011.             if(informazioniTokenNormalizzate.getClientId()!=null &&
  1012.                 set.get(CostantiPdD.HEADER_INTEGRAZIONE_TOKEN_CLIENT_ID).booleanValue()) {
  1013.                 if(op2headers) {
  1014.                     TransportUtils.setHeader(tokenForward.getTrasporto(),headerNames.get(CostantiPdD.HEADER_INTEGRAZIONE_TOKEN_CLIENT_ID), informazioniTokenNormalizzate.getClientId());
  1015.                 }
  1016.                 else {
  1017.                     jsonNode.put("clientId", informazioniTokenNormalizzate.getClientId());
  1018.                 }
  1019.             }
  1020.             if(informazioniTokenNormalizzate.getIat()!=null &&
  1021.                 set.get(CostantiPdD.HEADER_INTEGRAZIONE_TOKEN_ISSUED_AT).booleanValue()) {
  1022.                 if(op2headers) {
  1023.                     String value = null;
  1024.                     if(sdf!=null) {
  1025.                         value = sdf.format(informazioniTokenNormalizzate.getIat());
  1026.                     }
  1027.                     else {
  1028.                         value = (informazioniTokenNormalizzate.getIat().getTime() / 1000) + "";
  1029.                     }
  1030.                     TransportUtils.setHeader(tokenForward.getTrasporto(),headerNames.get(CostantiPdD.HEADER_INTEGRAZIONE_TOKEN_ISSUED_AT), value);
  1031.                 }
  1032.                 else {
  1033.                     jsonNode.put("iat", jsonUtils.getDateFormat().format(informazioniTokenNormalizzate.getIat()));
  1034.                 }
  1035.             }
  1036.             if(informazioniTokenNormalizzate.getExp()!=null &&
  1037.                 set.get(CostantiPdD.HEADER_INTEGRAZIONE_TOKEN_EXPIRED).booleanValue()) {
  1038.                 if(op2headers) {
  1039.                     String value = null;
  1040.                     if(sdf!=null) {
  1041.                         value = sdf.format(informazioniTokenNormalizzate.getExp());
  1042.                     }
  1043.                     else {
  1044.                         value = (informazioniTokenNormalizzate.getExp().getTime() / 1000) + "";
  1045.                     }
  1046.                     TransportUtils.setHeader(tokenForward.getTrasporto(),headerNames.get(CostantiPdD.HEADER_INTEGRAZIONE_TOKEN_EXPIRED), value);
  1047.                 }
  1048.                 else {
  1049.                     jsonNode.put("expire", jsonUtils.getDateFormat().format(informazioniTokenNormalizzate.getExp()));
  1050.                 }
  1051.             }
  1052.             if(informazioniTokenNormalizzate.getNbf()!=null &&
  1053.                 set.get(CostantiPdD.HEADER_INTEGRAZIONE_TOKEN_NBF).booleanValue()) {
  1054.                 if(op2headers) {
  1055.                     String value = null;
  1056.                     if(sdf!=null) {
  1057.                         value = sdf.format(informazioniTokenNormalizzate.getNbf());
  1058.                     }
  1059.                     else {
  1060.                         value = (informazioniTokenNormalizzate.getNbf().getTime() / 1000) + "";
  1061.                     }
  1062.                     TransportUtils.setHeader(tokenForward.getTrasporto(),headerNames.get(CostantiPdD.HEADER_INTEGRAZIONE_TOKEN_NBF), value);
  1063.                 }
  1064.                 else {
  1065.                     jsonNode.put("nbf", jsonUtils.getDateFormat().format(informazioniTokenNormalizzate.getNbf()));
  1066.                 }
  1067.             }
  1068.             if(informazioniTokenNormalizzate.getRoles()!=null && !informazioniTokenNormalizzate.getRoles().isEmpty() &&
  1069.                 set.get(CostantiPdD.HEADER_INTEGRAZIONE_TOKEN_ROLES).booleanValue()) {
  1070.                 ArrayNode array = null;
  1071.                 StringBuilder bf = new StringBuilder();
  1072.                 if(!op2headers) {
  1073.                     array =  jsonUtils.newArrayNode();
  1074.                 }
  1075.                 for (String role : informazioniTokenNormalizzate.getRoles()) {
  1076.                     if(op2headers) {
  1077.                         if(bf.length()>0) {
  1078.                             bf.append(properties.getGestioneTokenHeaderIntegrazioneTrasportoRoleSeparator());
  1079.                         }
  1080.                         bf.append(role);
  1081.                     }
  1082.                     else {
  1083.                         array.add(role);
  1084.                     }
  1085.                 }
  1086.                 if(op2headers) {
  1087.                     TransportUtils.setHeader(tokenForward.getTrasporto(),headerNames.get(CostantiPdD.HEADER_INTEGRAZIONE_TOKEN_ROLES), bf.toString());
  1088.                 }
  1089.                 else {
  1090.                     jsonNode.set("roles", array);
  1091.                 }
  1092.             }
  1093.             if(informazioniTokenNormalizzate.getScopes()!=null && !informazioniTokenNormalizzate.getScopes().isEmpty() &&
  1094.                 set.get(CostantiPdD.HEADER_INTEGRAZIONE_TOKEN_SCOPES).booleanValue()) {
  1095.                 ArrayNode array = null;
  1096.                 StringBuilder bf = new StringBuilder();
  1097.                 if(!op2headers) {
  1098.                     array =  jsonUtils.newArrayNode();
  1099.                 }
  1100.                 for (String scope : informazioniTokenNormalizzate.getScopes()) {
  1101.                     if(op2headers) {
  1102.                         if(bf.length()>0) {
  1103.                             bf.append(properties.getGestioneTokenHeaderIntegrazioneTrasportoScopeSeparator());
  1104.                         }
  1105.                         bf.append(scope);
  1106.                     }
  1107.                     else {
  1108.                         array.add(scope);
  1109.                     }
  1110.                 }
  1111.                 if(op2headers) {
  1112.                     TransportUtils.setHeader(tokenForward.getTrasporto(),headerNames.get(CostantiPdD.HEADER_INTEGRAZIONE_TOKEN_SCOPES), bf.toString());
  1113.                 }
  1114.                 else {
  1115.                     jsonNode.set("scopes", array);
  1116.                 }
  1117.             }
  1118.             if(informazioniTokenNormalizzate.getUserInfo()!=null) {
  1119.                 ObjectNode userInfoNode = null;
  1120.                 if(!op2headers) {
  1121.                     userInfoNode = jsonUtils.newObjectNode();
  1122.                 }
  1123.                
  1124.                 boolean add = false;
  1125.                
  1126.                 if(informazioniTokenNormalizzate.getUserInfo().getFullName()!=null &&
  1127.                     set.get(CostantiPdD.HEADER_INTEGRAZIONE_TOKEN_FULL_NAME).booleanValue()) {
  1128.                     if(op2headers) {
  1129.                         TransportUtils.setHeader(tokenForward.getTrasporto(),headerNames.get(CostantiPdD.HEADER_INTEGRAZIONE_TOKEN_FULL_NAME), informazioniTokenNormalizzate.getUserInfo().getFullName());
  1130.                     }
  1131.                     else {
  1132.                         userInfoNode.put("fullName", informazioniTokenNormalizzate.getUserInfo().getFullName());
  1133.                         add = true;
  1134.                     }
  1135.                 }
  1136.                 if(informazioniTokenNormalizzate.getUserInfo().getFirstName()!=null &&
  1137.                     set.get(CostantiPdD.HEADER_INTEGRAZIONE_TOKEN_FIRST_NAME).booleanValue()) {
  1138.                     if(op2headers) {
  1139.                         TransportUtils.setHeader(tokenForward.getTrasporto(),headerNames.get(CostantiPdD.HEADER_INTEGRAZIONE_TOKEN_FIRST_NAME), informazioniTokenNormalizzate.getUserInfo().getFirstName());
  1140.                     }
  1141.                     else {
  1142.                         userInfoNode.put("firstName", informazioniTokenNormalizzate.getUserInfo().getFirstName());
  1143.                         add = true;
  1144.                     }
  1145.                 }
  1146.                 if(informazioniTokenNormalizzate.getUserInfo().getMiddleName()!=null &&
  1147.                     set.get(CostantiPdD.HEADER_INTEGRAZIONE_TOKEN_MIDDLE_NAME).booleanValue()) {
  1148.                     if(op2headers) {
  1149.                         TransportUtils.setHeader(tokenForward.getTrasporto(),headerNames.get(CostantiPdD.HEADER_INTEGRAZIONE_TOKEN_MIDDLE_NAME), informazioniTokenNormalizzate.getUserInfo().getMiddleName());
  1150.                     }
  1151.                     else {
  1152.                         userInfoNode.put("middleName", informazioniTokenNormalizzate.getUserInfo().getMiddleName());
  1153.                         add = true;
  1154.                     }
  1155.                 }
  1156.                 if(informazioniTokenNormalizzate.getUserInfo().getFamilyName()!=null &&
  1157.                     set.get(CostantiPdD.HEADER_INTEGRAZIONE_TOKEN_FAMILY_NAME).booleanValue()) {
  1158.                     if(op2headers) {
  1159.                         TransportUtils.setHeader(tokenForward.getTrasporto(),headerNames.get(CostantiPdD.HEADER_INTEGRAZIONE_TOKEN_FAMILY_NAME), informazioniTokenNormalizzate.getUserInfo().getFamilyName());
  1160.                     }
  1161.                     else {
  1162.                         userInfoNode.put("familyName", informazioniTokenNormalizzate.getUserInfo().getFamilyName());
  1163.                         add = true;
  1164.                     }
  1165.                 }
  1166.                 if(informazioniTokenNormalizzate.getUserInfo().getEMail()!=null &&
  1167.                     set.get(CostantiPdD.HEADER_INTEGRAZIONE_TOKEN_EMAIL).booleanValue()) {
  1168.                     if(op2headers) {
  1169.                         TransportUtils.setHeader(tokenForward.getTrasporto(),headerNames.get(CostantiPdD.HEADER_INTEGRAZIONE_TOKEN_EMAIL), informazioniTokenNormalizzate.getUserInfo().getEMail());
  1170.                     }
  1171.                     else {
  1172.                         userInfoNode.put("eMail", informazioniTokenNormalizzate.getUserInfo().getEMail());
  1173.                         add = true;
  1174.                     }
  1175.                 }
  1176.                
  1177.                 if(!op2headers && add) {
  1178.                     jsonNode.set("userInfo", userInfoNode);
  1179.                 }
  1180.             }  
  1181.             if(informazioniTokenNormalizzate.getClaims()!=null && !informazioniTokenNormalizzate.getClaims().isEmpty()) {
  1182.                 if(informazioniTokenNormalizzate.getClaims().containsKey(Claims.JSON_WEB_TOKEN_RFC_7519_JWT_ID)) {
  1183.                     Object oPid = informazioniTokenNormalizzate.getClaims().get(Claims.JSON_WEB_TOKEN_RFC_7519_JWT_ID);
  1184.                     if(oPid instanceof String) {
  1185.                         String pId = (String) oPid;
  1186.                         if(set.get(CostantiPdD.HEADER_INTEGRAZIONE_TOKEN_JTI).booleanValue()) {
  1187.                             if(op2headers) {
  1188.                                 TransportUtils.setHeader(tokenForward.getTrasporto(),headerNames.get(CostantiPdD.HEADER_INTEGRAZIONE_TOKEN_JTI), pId);
  1189.                             }
  1190.                             else {
  1191.                                 jsonNode.put("jti", pId);
  1192.                             }
  1193.                         }
  1194.                     }
  1195.                 }
  1196.                 if(informazioniTokenNormalizzate.getClaims().containsKey(Costanti.PDND_PURPOSE_ID)) {
  1197.                     Object oPid = informazioniTokenNormalizzate.getClaims().get(Costanti.PDND_PURPOSE_ID);
  1198.                     if(oPid instanceof String) {
  1199.                         String pId = (String) oPid;
  1200.                         if(set.get(CostantiPdD.HEADER_INTEGRAZIONE_TOKEN_PURPOSE_ID).booleanValue()) {
  1201.                             if(op2headers) {
  1202.                                 TransportUtils.setHeader(tokenForward.getTrasporto(),headerNames.get(CostantiPdD.HEADER_INTEGRAZIONE_TOKEN_PURPOSE_ID), pId);
  1203.                             }
  1204.                             else {
  1205.                                 jsonNode.put("purposeId", pId);
  1206.                             }
  1207.                         }
  1208.                     }
  1209.                 }
  1210.                 if(informazioniTokenNormalizzate.getPdnd()!=null && !informazioniTokenNormalizzate.getPdnd().isEmpty()) {
  1211.                    
  1212.                     ObjectNode pdndNode = null;
  1213.                     ObjectNode organizationNode = null;
  1214.                     if(!op2headers) {
  1215.                         pdndNode = jsonUtils.newObjectNode();
  1216.                         organizationNode = jsonUtils.newObjectNode();
  1217.                         pdndNode.set("organization", organizationNode);
  1218.                     }
  1219.                    
  1220.                     boolean add = false;
  1221.                    
  1222.                     String organizationName = PDNDTokenInfo.readOrganizationNameFromPDNDMap(informazioniTokenNormalizzate.getPdnd());
  1223.                     if(organizationName!=null && StringUtils.isNotEmpty(organizationName) &&
  1224.                             set.get(CostantiPdD.HEADER_INTEGRAZIONE_TOKEN_PDND_ORGANIZATION_NAME).booleanValue()) {
  1225.                         if(op2headers) {
  1226.                             TransportUtils.setHeader(tokenForward.getTrasporto(),headerNames.get(CostantiPdD.HEADER_INTEGRAZIONE_TOKEN_PDND_ORGANIZATION_NAME), organizationName);
  1227.                         }
  1228.                         else {
  1229.                             organizationNode.put("name", organizationName);
  1230.                             add = true;
  1231.                         }
  1232.                     }
  1233.                    
  1234.                     String organizationCategory = PDNDTokenInfo.readOrganizationCategoryFromPDNDMap(informazioniTokenNormalizzate.getPdnd());
  1235.                     if(organizationCategory!=null && StringUtils.isNotEmpty(organizationCategory) &&
  1236.                             set.get(CostantiPdD.HEADER_INTEGRAZIONE_TOKEN_PDND_ORGANIZATION_CATEGORY).booleanValue()) {
  1237.                         if(op2headers) {
  1238.                             TransportUtils.setHeader(tokenForward.getTrasporto(),headerNames.get(CostantiPdD.HEADER_INTEGRAZIONE_TOKEN_PDND_ORGANIZATION_CATEGORY), organizationCategory);
  1239.                         }
  1240.                         else {
  1241.                             organizationNode.put("category", organizationCategory);
  1242.                             add = true;
  1243.                         }
  1244.                     }
  1245.                    
  1246.                     String organizationExternalOrigin = PDNDTokenInfo.readOrganizationExternalOriginFromPDNDMap(informazioniTokenNormalizzate.getPdnd());
  1247.                     String organizationExternalId = PDNDTokenInfo.readOrganizationExternalIdFromPDNDMap(informazioniTokenNormalizzate.getPdnd());
  1248.                     StringBuilder sbOrganizationExternal = new StringBuilder();
  1249.                    
  1250.                     if(organizationExternalOrigin!=null && StringUtils.isNotEmpty(organizationExternalOrigin)) {
  1251.                         sbOrganizationExternal.append(organizationExternalOrigin);
  1252.                         if(set.get(CostantiPdD.HEADER_INTEGRAZIONE_TOKEN_PDND_ORGANIZATION_EXTERNAL_ORIGIN).booleanValue()) {
  1253.                             if(op2headers) {
  1254.                                 TransportUtils.setHeader(tokenForward.getTrasporto(),headerNames.get(CostantiPdD.HEADER_INTEGRAZIONE_TOKEN_PDND_ORGANIZATION_EXTERNAL_ORIGIN), organizationExternalOrigin);
  1255.                             }
  1256.                             else {
  1257.                                 organizationNode.put("externalOrigin", organizationExternalOrigin);
  1258.                                 add = true;
  1259.                             }
  1260.                         }
  1261.                     }
  1262.                     if(organizationExternalId!=null && StringUtils.isNotEmpty(organizationExternalId)) {
  1263.                         if(sbOrganizationExternal.length()>0) {
  1264.                             sbOrganizationExternal.append(" ");
  1265.                         }
  1266.                         sbOrganizationExternal.append(organizationExternalId);
  1267.                         if(set.get(CostantiPdD.HEADER_INTEGRAZIONE_TOKEN_PDND_ORGANIZATION_EXTERNAL_ID).booleanValue()) {
  1268.                             if(op2headers) {
  1269.                                 TransportUtils.setHeader(tokenForward.getTrasporto(),headerNames.get(CostantiPdD.HEADER_INTEGRAZIONE_TOKEN_PDND_ORGANIZATION_EXTERNAL_ID), organizationExternalId);
  1270.                             }
  1271.                             else {
  1272.                                 organizationNode.put("externalId", organizationExternalId);
  1273.                                 add = true;
  1274.                             }
  1275.                         }
  1276.                     }
  1277.                    
  1278.                     String organizationExternal = sbOrganizationExternal.toString();
  1279.                     if(organizationExternal!=null && StringUtils.isNotEmpty(organizationExternal) &&
  1280.                             set.get(CostantiPdD.HEADER_INTEGRAZIONE_TOKEN_PDND_ORGANIZATION_EXTERNAL).booleanValue()) {
  1281.                         if(op2headers) {
  1282.                             TransportUtils.setHeader(tokenForward.getTrasporto(),headerNames.get(CostantiPdD.HEADER_INTEGRAZIONE_TOKEN_PDND_ORGANIZATION_EXTERNAL), organizationExternal);
  1283.                         }
  1284.                         else {
  1285.                             organizationNode.put("external", organizationExternal);
  1286.                             add = true;
  1287.                         }
  1288.                     }
  1289.                    
  1290.                     if(!op2headers && add) {
  1291.                         jsonNode.set("pdnd", pdndNode);
  1292.                     }
  1293.                 }
  1294.             }
  1295.             List<String> listCustomClaims = properties.getCustomClaimsKeysGestioneTokenForward();
  1296.             if(listCustomClaims!=null && !listCustomClaims.isEmpty()) {
  1297.                
  1298.                 ArrayNode customClaimsNode = null;
  1299.                 if(!op2headers) {
  1300.                     customClaimsNode = jsonUtils.newArrayNode();
  1301.                 }
  1302.                
  1303.                 boolean add = false;
  1304.                
  1305.                 for (String claimKey : listCustomClaims) {
  1306.                
  1307.                     String claimName = properties.getCustomClaimsNameGestioneTokenHeaderIntegrazione(claimKey);
  1308.                    
  1309.                     if(informazioniTokenNormalizzate.getClaims()!=null && informazioniTokenNormalizzate.getClaims().containsKey(claimName)) {
  1310.                        
  1311.                         Object claimValueObject = informazioniTokenNormalizzate.getClaims().get(claimName);
  1312.                         List<String> claimValues = null;
  1313.                         if(claimValueObject!=null) {
  1314.                             claimValues = TokenUtilities.getClaimValues(claimValueObject);
  1315.                         }
  1316.                         String headerName = null;
  1317.                         if(claimValues!=null && !claimValues.isEmpty()) {
  1318.                             boolean setCustomClaims = false;
  1319.                             if(op2headers) {
  1320.                                 headerName = properties.getCustomClaimsHeaderNameGestioneTokenHeaderIntegrazioneTrasporto(claimKey);
  1321.                                 if(portaDelegata) {
  1322.                                     setCustomClaims = properties.getCustomClaimsKeyPDSetEnabledGestioneTokenHeaderIntegrazioneTrasporto(claimKey);
  1323.                                 }
  1324.                                 else {
  1325.                                     setCustomClaims = properties.getCustomClaimsKeyPASetEnabledGestioneTokenHeaderIntegrazioneTrasporto(claimKey);
  1326.                                 }
  1327.                             }
  1328.                             else {
  1329.                                 headerName = properties.getCustomClaimsJsonPropertyNameGestioneTokenHeaderIntegrazioneJson(claimKey);
  1330.                                 if(portaDelegata) {
  1331.                                     setCustomClaims = properties.getCustomClaimsKeyPDSetEnabledGestioneTokenHeaderIntegrazioneJson(claimKey);
  1332.                                 }
  1333.                                 else {
  1334.                                     setCustomClaims = properties.getCustomClaimsKeyPASetEnabledGestioneTokenHeaderIntegrazioneJson(claimKey);
  1335.                                 }
  1336.                             }
  1337.                            
  1338.                             if(setCustomClaims) {
  1339.                                 String claimValue = TokenUtilities.getClaimValuesAsString(claimValues);
  1340.                                 if(op2headers) {
  1341.                                     TransportUtils.setHeader(tokenForward.getTrasporto(),headerName, claimValue);
  1342.                                 }
  1343.                                 else {
  1344.                                     ObjectNode propertyNode = jsonUtils.newObjectNode();
  1345.                                     propertyNode.put("name", headerName);
  1346.                                     propertyNode.put("value", claimValue);
  1347.                                     customClaimsNode.add(propertyNode);
  1348.                                     add = true;
  1349.                                 }
  1350.                             }
  1351.                         }
  1352.                     }
  1353.                    
  1354.                 }
  1355.                
  1356.                 if(!op2headers && add) {
  1357.                     jsonNode.set("claims", customClaimsNode);
  1358.                 }
  1359.             }

  1360.             Date processTime = DateManager.getDate();
  1361.             if(set.get(CostantiPdD.HEADER_INTEGRAZIONE_TOKEN_PROCESS_TIME).booleanValue()) {
  1362.                 if(op2headers) {
  1363.                     String value = null;
  1364.                     if(sdf!=null) {
  1365.                         value = sdf.format(processTime);
  1366.                     }
  1367.                     else {
  1368.                         value = (processTime.getTime() / 1000) + "";
  1369.                     }
  1370.                     TransportUtils.setHeader(tokenForward.getTrasporto(),headerNames.get(CostantiPdD.HEADER_INTEGRAZIONE_TOKEN_PROCESS_TIME), value);
  1371.                 }
  1372.                 else {
  1373.                     jsonNode.put("processTime", jsonUtils.getDateFormat().format(processTime));
  1374.                 }
  1375.             }
  1376.            
  1377.             if(!op2headers) {
  1378.                 String json = jsonUtils.toString(jsonNode);
  1379.                 if(Costanti.POLICY_TOKEN_FORWARD_INFO_RACCOLTE_MODE_OP2_JSON.equals(forwardInforRaccolteMode)) {
  1380.                     String headerName = properties.getGestioneTokenHeaderTrasportoJSON();
  1381.                     if(encodeBase64) {
  1382.                         TransportUtils.setHeader(tokenForward.getTrasporto(),headerName, Base64Utilities.encodeAsString(json.getBytes()));
  1383.                     }
  1384.                     else {
  1385.                         TransportUtils.setHeader(tokenForward.getTrasporto(),headerName, json);
  1386.                     }
  1387.                 }
  1388.                 else {
  1389.                     // JWS Compact
  1390.                     JWSOptions jwsOptions = new JWSOptions(JOSESerialization.COMPACT);
  1391.                     JsonSignature jsonCompactSignature = new JsonSignature(jwtSecurity,jwsOptions);
  1392.                     String compact = jsonCompactSignature.sign(json);
  1393.                     String headerName = properties.getGestioneTokenHeaderTrasportoJWT();
  1394.                     TransportUtils.setHeader(tokenForward.getTrasporto(),headerName, compact);
  1395.                 }
  1396.             }
  1397.         }
  1398.         else {
  1399.            
  1400.             if(forwardValidazioneJWT && esitoValidazioneJWT!=null && esitoValidazioneJWT.isValido() &&
  1401.                     esitoValidazioneJWT.getInformazioniToken()!=null &&
  1402.                     esitoValidazioneJWT.getInformazioniToken().getRawResponse()!=null) {
  1403.                
  1404.                 String value = esitoValidazioneJWT.getInformazioniToken().getRawResponse();
  1405.                 if(Costanti.POLICY_TOKEN_FORWARD_INFO_RACCOLTE_MODE_JWS.equals(forwardInforRaccolteMode)) {
  1406.                     // JWS Compact              
  1407.                     JWSOptions jwsOptions = new JWSOptions(JOSESerialization.COMPACT);
  1408.                     JsonSignature jsonCompactSignature = new JsonSignature(jwtSecurity,jwsOptions);
  1409.                     value = jsonCompactSignature.sign(value);
  1410.                 }
  1411.                 else if(Costanti.POLICY_TOKEN_FORWARD_INFO_RACCOLTE_MODE_JWE.equals(forwardInforRaccolteMode)) {
  1412.                     // JWE Compact
  1413.                     JWEOptions jweOptions = new JWEOptions(JOSESerialization.COMPACT);
  1414.                     JsonEncrypt jsonCompactEncrypt = new JsonEncrypt(jwtSecurity,jweOptions);
  1415.                     value = jsonCompactEncrypt.encrypt(value);
  1416.                 }
  1417.                 else {
  1418.                     //Costanti.POLICY_TOKEN_FORWARD_INFO_RACCOLTE_MODE_JSON
  1419.                     if(encodeBase64) {
  1420.                         value = Base64Utilities.encodeAsString(value.getBytes());
  1421.                     }
  1422.                 }
  1423.                 if(Costanti.POLICY_TOKEN_FORWARD_INFO_RACCOLTE_MODE_NO_OPENSPCOOP_CUSTOM_HEADER.equals(forwardValidazioneJWTMode)) {
  1424.                     TransportUtils.setHeader(tokenForward.getTrasporto(),forwardValidazioneJWTName, value);
  1425.                 }
  1426.                 else {
  1427.                     TransportUtils.setParameter(tokenForward.getUrl(),forwardValidazioneJWTName, value);
  1428.                 }
  1429.                
  1430.             }
  1431.            
  1432.             if(forwardIntrospection && esitoIntrospection!=null && esitoIntrospection.isValido() &&
  1433.                     esitoIntrospection.getInformazioniToken()!=null &&
  1434.                     esitoIntrospection.getInformazioniToken().getRawResponse()!=null) {
  1435.                
  1436.                 String value = esitoIntrospection.getInformazioniToken().getRawResponse();
  1437.                 if(Costanti.POLICY_TOKEN_FORWARD_INFO_RACCOLTE_MODE_JWS.equals(forwardInforRaccolteMode)) {
  1438.                     // JWS Compact              
  1439.                     JWSOptions jwsOptions = new JWSOptions(JOSESerialization.COMPACT);
  1440.                     JsonSignature jsonCompactSignature = new JsonSignature(jwtSecurity,jwsOptions);
  1441.                     value = jsonCompactSignature.sign(value);
  1442.                 }
  1443.                 else if(Costanti.POLICY_TOKEN_FORWARD_INFO_RACCOLTE_MODE_JWE.equals(forwardInforRaccolteMode)) {
  1444.                     // JWE Compact
  1445.                     JWEOptions jweOptions = new JWEOptions(JOSESerialization.COMPACT);
  1446.                     JsonEncrypt jsonCompactEncrypt = new JsonEncrypt(jwtSecurity,jweOptions);
  1447.                     value = jsonCompactEncrypt.encrypt(value);
  1448.                 }
  1449.                 else {
  1450.                     //Costanti.POLICY_TOKEN_FORWARD_INFO_RACCOLTE_MODE_JSON
  1451.                     if(encodeBase64) {
  1452.                         value = Base64Utilities.encodeAsString(value.getBytes());
  1453.                     }
  1454.                 }
  1455.                 if(Costanti.POLICY_TOKEN_FORWARD_INFO_RACCOLTE_MODE_NO_OPENSPCOOP_CUSTOM_HEADER.equals(forwardIntrospectionMode)) {
  1456.                     TransportUtils.setHeader(tokenForward.getTrasporto(),forwardIntrospectionName, value);
  1457.                 }
  1458.                 else {
  1459.                     TransportUtils.setParameter(tokenForward.getUrl(),forwardIntrospectionName, value);
  1460.                 }
  1461.                
  1462.             }
  1463.            
  1464.             if(forwardUserInfo && esitoUserInfo!=null && esitoUserInfo.isValido() &&
  1465.                     esitoUserInfo.getInformazioniToken()!=null &&
  1466.                     esitoUserInfo.getInformazioniToken().getRawResponse()!=null) {
  1467.                
  1468.                 String value = esitoUserInfo.getInformazioniToken().getRawResponse();
  1469.                 if(Costanti.POLICY_TOKEN_FORWARD_INFO_RACCOLTE_MODE_JWS.equals(forwardInforRaccolteMode)) {
  1470.                     // JWS Compact              
  1471.                     JWSOptions jwsOptions = new JWSOptions(JOSESerialization.COMPACT);
  1472.                     JsonSignature jsonCompactSignature = new JsonSignature(jwtSecurity,jwsOptions);
  1473.                     value = jsonCompactSignature.sign(value);
  1474.                 }
  1475.                 else if(Costanti.POLICY_TOKEN_FORWARD_INFO_RACCOLTE_MODE_JWE.equals(forwardInforRaccolteMode)) {
  1476.                     // JWE Compact
  1477.                     JWEOptions jweOptions = new JWEOptions(JOSESerialization.COMPACT);
  1478.                     JsonEncrypt jsonCompactEncrypt = new JsonEncrypt(jwtSecurity,jweOptions);
  1479.                     value = jsonCompactEncrypt.encrypt(value);
  1480.                 }
  1481.                 else {
  1482.                     //Costanti.POLICY_TOKEN_FORWARD_INFO_RACCOLTE_MODE_JSON
  1483.                     if(encodeBase64) {
  1484.                         value = Base64Utilities.encodeAsString(value.getBytes());
  1485.                     }
  1486.                 }
  1487.                 if(Costanti.POLICY_TOKEN_FORWARD_INFO_RACCOLTE_MODE_NO_OPENSPCOOP_CUSTOM_HEADER.equals(forwardUserInfoMode)) {
  1488.                     TransportUtils.setHeader(tokenForward.getTrasporto(),forwardUserInfoName, value);
  1489.                 }
  1490.                 else {
  1491.                     TransportUtils.setParameter(tokenForward.getUrl(),forwardUserInfoName, value);
  1492.                 }
  1493.                
  1494.             }
  1495.            
  1496.         }
  1497.        
  1498.     }
  1499.    
  1500.    
  1501.    
  1502.    
  1503.    
  1504.    
  1505.     // ********* [VALIDAZIONE-TOKEN] UTILITIES INTERNE ****************** */
  1506.    
  1507.     public static boolean isExpired(Date now, Date exp) throws TokenException {
  1508.        
  1509.         Date checkNow = now;
  1510.         Long tolerance = null;
  1511.         try {
  1512.             tolerance = OpenSPCoop2Properties.getInstance().getGestioneTokenExpTimeCheckToleranceMilliseconds();
  1513.         }catch(Exception e) {
  1514.             throw new TokenException(e.getMessage(),e);
  1515.         }
  1516.         if(tolerance!=null && tolerance.longValue()>0) {
  1517.             checkNow = new Date(now.getTime() - tolerance.longValue());
  1518.         }
  1519.        
  1520.         return !checkNow.before(exp);
  1521.     }
  1522.     public static boolean isFuture(Date now, Date nbf) throws TokenException {
  1523.        
  1524.         Date checkNow = now;
  1525.         Long tolerance = null;
  1526.         try {
  1527.             tolerance = OpenSPCoop2Properties.getInstance().getGestioneTokenNbfTimeCheckToleranceMilliseconds();
  1528.         }catch(Exception e) {
  1529.             throw new TokenException(e.getMessage(),e);
  1530.         }
  1531.         if(tolerance!=null && tolerance.longValue()>0) {
  1532.             checkNow = new Date(now.getTime() + tolerance.longValue());
  1533.         }
  1534.        
  1535.         return !nbf.before(checkNow);
  1536.     }
  1537.    
  1538.     public static boolean isProfiloModIPAEnabled() {
  1539.         try {
  1540.             Enumeration<String> en = ProtocolFactoryManager.getInstance().getProtocolNames();
  1541.             while (en.hasMoreElements()) {
  1542.                 String protocollo = en.nextElement();
  1543.                 if(protocollo.equals(CostantiLabel.MODIPA_PROTOCOL_NAME)) {
  1544.                     return true;
  1545.                 }
  1546.             }
  1547.             return false;
  1548.         }catch(Throwable t) {
  1549.             return false;
  1550.         }
  1551.     }
  1552.    
  1553.     private static List<String> policyGestioneTokenPDND = null;
  1554.     private static synchronized void initPolicyGestioneTokenPDND(Logger log) {
  1555.         if(policyGestioneTokenPDND==null) {
  1556.             try {
  1557.                 policyGestioneTokenPDND = new ArrayList<>();
  1558.                 if(isProfiloModIPAEnabled()) {
  1559.                     initPolicyGestioneTokenPDND();
  1560.                 }
  1561.             }catch(Exception e) {
  1562.                 log.error("Errore di inizializzazione policy 'PDND': "+e.getMessage(), e);
  1563.             }
  1564.         }
  1565.     }
  1566.     private static synchronized void initPolicyGestioneTokenPDND() throws ProtocolException {
  1567.         List<RemoteStoreConfig> listRSC = ModIUtils.getRemoteStoreConfig();
  1568.         if(listRSC!=null && !listRSC.isEmpty()) {
  1569.             for (RemoteStoreConfig r : listRSC) {
  1570.                 if(!policyGestioneTokenPDND.contains(r.getTokenPolicy())) {
  1571.                     policyGestioneTokenPDND.add(r.getTokenPolicy());
  1572.                 }
  1573.             }
  1574.         }
  1575.     }
  1576.     private static boolean isPdndTokenPolicy(Logger log, String tokenPolicy) {
  1577.         if(policyGestioneTokenPDND==null) {
  1578.             initPolicyGestioneTokenPDND(log) ;
  1579.         }
  1580.         return policyGestioneTokenPDND.contains(tokenPolicy);
  1581.     }
  1582.    
  1583.     private static List<Proprieta> readProprieta(AbstractDatiInvocazione datiInvocazione) throws DriverConfigurazioneException {
  1584.         List<Proprieta> l = null;
  1585.         if(datiInvocazione instanceof DatiInvocazionePortaDelegata) {
  1586.             DatiInvocazionePortaDelegata d = (DatiInvocazionePortaDelegata) datiInvocazione;
  1587.             PortaDelegata pd = d.getPd();
  1588.             if(pd==null && d.getIdPD()!=null) {
  1589.                 ConfigurazionePdDManager configManager = ConfigurazionePdDManager.getInstance(datiInvocazione.getState());
  1590.                 pd = configManager.getPortaDelegataSafeMethod(d.getIdPD(), datiInvocazione.getRequestInfo());
  1591.             }
  1592.             if(pd!=null) {
  1593.                 return pd.getProprieta();
  1594.             }
  1595.         }
  1596.         else {
  1597.             DatiInvocazionePortaApplicativa d = (DatiInvocazionePortaApplicativa) datiInvocazione;
  1598.             PortaApplicativa pa = d.getPa();
  1599.             if(pa==null && d.getIdPA()!=null) {
  1600.                 ConfigurazionePdDManager configManager = ConfigurazionePdDManager.getInstance(datiInvocazione.getState());
  1601.                 pa = configManager.getPortaApplicativaSafeMethod(d.getIdPA(), datiInvocazione.getRequestInfo());
  1602.             }
  1603.             if(pa!=null) {
  1604.                 return pa.getProprieta();
  1605.             }
  1606.         }
  1607.         return l;
  1608.     }
  1609.    
  1610.     static boolean isIatRequired(Logger log, PolicyGestioneToken policyGestioneToken, AbstractDatiInvocazione datiInvocazione, IProtocolFactory<?> protocollo, OpenSPCoop2Properties op2Properties) throws CoreException {
  1611.        
  1612.         String p = protocollo!=null ? protocollo.getProtocol() : "";
  1613.        
  1614.         boolean delegata = datiInvocazione instanceof DatiInvocazionePortaDelegata;
  1615.        
  1616.         boolean required = op2Properties.isGestioneTokenIatRequired();
  1617.         BooleanNullable bn = op2Properties.isGestioneTokenIatRequired(delegata, p);
  1618.         if(bn!=null && bn.getValue()!=null) {
  1619.             required = bn.getValue().booleanValue();
  1620.         }
  1621.        
  1622.         if(!delegata && isPdndTokenPolicy(log, policyGestioneToken.getName())) {
  1623.             bn = op2Properties.isGestioneTokenIatPdndRequired();
  1624.             if(bn!=null && bn.getValue()!=null) {
  1625.                 required = bn.getValue().booleanValue();
  1626.             }
  1627.         }
  1628.        
  1629.         try {
  1630.             List<Proprieta> props = readProprieta(datiInvocazione);
  1631.             return CostantiProprieta.isTokenValidationClaimsIatRequired(props, required);
  1632.         }catch(Exception e) {
  1633.             throw new CoreException(e.getMessage(),e);
  1634.         }
  1635.     }
  1636.    
  1637.     static boolean isExpRequired(Logger log, PolicyGestioneToken policyGestioneToken, AbstractDatiInvocazione datiInvocazione, IProtocolFactory<?> protocollo, OpenSPCoop2Properties op2Properties) throws CoreException {
  1638.        
  1639.         String p = protocollo!=null ? protocollo.getProtocol() : "";
  1640.        
  1641.         boolean delegata = datiInvocazione instanceof DatiInvocazionePortaDelegata;
  1642.        
  1643.         boolean required = op2Properties.isGestioneTokenExpRequired();
  1644.         BooleanNullable bn = op2Properties.isGestioneTokenExpRequired(delegata, p);
  1645.         if(bn!=null && bn.getValue()!=null) {
  1646.             required = bn.getValue().booleanValue();
  1647.         }
  1648.        
  1649.         if(!delegata && isPdndTokenPolicy(log, policyGestioneToken.getName())) {
  1650.             bn = op2Properties.isGestioneTokenExpPdndRequired();
  1651.             if(bn!=null && bn.getValue()!=null) {
  1652.                 required = bn.getValue().booleanValue();
  1653.             }
  1654.         }
  1655.        
  1656.         try {
  1657.             List<Proprieta> props = readProprieta(datiInvocazione);
  1658.             return CostantiProprieta.isTokenValidationClaimsExpRequired(props, required);
  1659.         }catch(Exception e) {
  1660.             throw new CoreException(e.getMessage(),e);
  1661.         }
  1662.     }
  1663.    
  1664.     static boolean isNbfRequired(Logger log, PolicyGestioneToken policyGestioneToken, AbstractDatiInvocazione datiInvocazione, IProtocolFactory<?> protocollo, OpenSPCoop2Properties op2Properties) throws CoreException {
  1665.        
  1666.         String p = protocollo!=null ? protocollo.getProtocol() : "";
  1667.        
  1668.         boolean delegata = datiInvocazione instanceof DatiInvocazionePortaDelegata;
  1669.        
  1670.         boolean required = op2Properties.isGestioneTokenNbfRequired();
  1671.         BooleanNullable bn = op2Properties.isGestioneTokenNbfRequired(delegata, p);
  1672.         if(bn!=null && bn.getValue()!=null) {
  1673.             required = bn.getValue().booleanValue();
  1674.         }
  1675.        
  1676.         if(!delegata && isPdndTokenPolicy(log, policyGestioneToken.getName())) {
  1677.             bn = op2Properties.isGestioneTokenNbfPdndRequired();
  1678.             if(bn!=null && bn.getValue()!=null) {
  1679.                 required = bn.getValue().booleanValue();
  1680.             }
  1681.         }
  1682.        
  1683.         try {
  1684.             List<Proprieta> props = readProprieta(datiInvocazione);
  1685.             return CostantiProprieta.isTokenValidationClaimsNbfRequired(props, required);
  1686.         }catch(Exception e) {
  1687.             throw new CoreException(e.getMessage(),e);
  1688.         }
  1689.     }
  1690.    
  1691.     static void validazioneInformazioniToken(boolean checkRequired, // verranno controllati solo nella validazione jwt
  1692.             Logger log, AbstractDatiInvocazione datiInvocazione, IProtocolFactory<?> protocolFactory,
  1693.             EsitoGestioneToken esitoGestioneToken, PolicyGestioneToken policyGestioneToken, boolean saveErrorInCache) throws TokenException, CoreException {
  1694.        
  1695.         Date now = DateManager.getDate();
  1696.        
  1697.         if(esitoGestioneToken.isValido()) {
  1698.             esitoGestioneToken.setDateValide(true); // tanto le ricontrollo adesso
  1699.         }
  1700.            
  1701.         OpenSPCoop2Properties op2Properties = OpenSPCoop2Properties.getInstance();
  1702.        
  1703.         /** === EXP === ***/
  1704.        
  1705.         if(esitoGestioneToken.isValido() && checkRequired) {
  1706.            
  1707.             boolean check = isExpRequired(log, policyGestioneToken, datiInvocazione, protocolFactory, op2Properties);
  1708.             if(check && esitoGestioneToken.getInformazioniToken().getExp()==null) {
  1709.                 esitoGestioneToken.setTokenValidazioneFallita();
  1710.                 esitoGestioneToken.setDateValide(false);
  1711.                 esitoGestioneToken.setDetails("Token rejected; the 'exp' (expiration time) claim is required but missing.");
  1712.                 if(policyGestioneToken.isMessageErrorGenerateEmptyMessage()) {
  1713.                     esitoGestioneToken.setErrorMessage(WWWAuthenticateGenerator.buildErrorMessage(WWWAuthenticateErrorCode.invalid_token, policyGestioneToken.getRealm(),
  1714.                             false, // ritorno l'errore preciso in questo caso // policyGestioneToken.isGenericError(),
  1715.                             esitoGestioneToken.getDetails()));          
  1716.                 }
  1717.                 else {
  1718.                     esitoGestioneToken.setWwwAuthenticateErrorHeader(WWWAuthenticateGenerator.buildHeaderValue(WWWAuthenticateErrorCode.invalid_token, policyGestioneToken.getRealm(),
  1719.                             false, // ritorno l'errore preciso in questo caso // policyGestioneToken.isGenericError(),
  1720.                             esitoGestioneToken.getDetails()));
  1721.                 }  
  1722.             }
  1723.            
  1724.         }
  1725.        
  1726.         if(esitoGestioneToken.isValido()) {
  1727.            
  1728.             boolean enabled = op2Properties.isGestioneTokenExpTimeCheck();
  1729.            
  1730.             if(enabled && esitoGestioneToken.getInformazioniToken().getExp()!=null) {  
  1731.                
  1732.                 boolean expired = isExpired(now, esitoGestioneToken.getInformazioniToken().getExp());

  1733.                 /*
  1734.                  *   The "exp" (expiration time) claim identifies the expiration time on
  1735.                  *   or after which the JWT MUST NOT be accepted for processing.  The
  1736.                  *   processing of the "exp" claim requires that the current date/time
  1737.                  *   MUST be before the expiration date/time listed in the "exp" claim.
  1738.                  **/
  1739.                 if(expired){
  1740.                     esitoGestioneToken.setTokenScaduto();
  1741.                     esitoGestioneToken.setDateValide(false);
  1742.                     esitoGestioneToken.setDetails("Token expired");
  1743.                     if(policyGestioneToken.isMessageErrorGenerateEmptyMessage()) {
  1744.                         esitoGestioneToken.setErrorMessage(WWWAuthenticateGenerator.buildErrorMessage(WWWAuthenticateErrorCode.invalid_token, policyGestioneToken.getRealm(),
  1745.                                 false, // ritorno l'errore preciso in questo caso // policyGestioneToken.isGenericError(),
  1746.                                 esitoGestioneToken.getDetails()));          
  1747.                     }
  1748.                     else {
  1749.                         esitoGestioneToken.setWwwAuthenticateErrorHeader(WWWAuthenticateGenerator.buildHeaderValue(WWWAuthenticateErrorCode.invalid_token, policyGestioneToken.getRealm(),
  1750.                                 false, // ritorno l'errore preciso in questo caso // policyGestioneToken.isGenericError(),
  1751.                                 esitoGestioneToken.getDetails()));
  1752.                     }  
  1753.                 }
  1754.             }
  1755.            
  1756.         }
  1757.            
  1758.        
  1759.        
  1760.         /** === NBF === ***/
  1761.        
  1762.         if(esitoGestioneToken.isValido() && checkRequired) {
  1763.            
  1764.             boolean check = isNbfRequired(log, policyGestioneToken, datiInvocazione, protocolFactory, op2Properties);
  1765.             if(check && esitoGestioneToken.getInformazioniToken().getNbf()==null) {
  1766.                 esitoGestioneToken.setTokenValidazioneFallita();
  1767.                 esitoGestioneToken.setDateValide(false);
  1768.                 esitoGestioneToken.setDetails("Token rejected; the 'nbf' (not before) claim is required but missing.");
  1769.                 if(policyGestioneToken.isMessageErrorGenerateEmptyMessage()) {
  1770.                     esitoGestioneToken.setErrorMessage(WWWAuthenticateGenerator.buildErrorMessage(WWWAuthenticateErrorCode.invalid_token, policyGestioneToken.getRealm(),
  1771.                             false, // ritorno l'errore preciso in questo caso // policyGestioneToken.isGenericError(),
  1772.                             esitoGestioneToken.getDetails()));          
  1773.                 }
  1774.                 else {
  1775.                     esitoGestioneToken.setWwwAuthenticateErrorHeader(WWWAuthenticateGenerator.buildHeaderValue(WWWAuthenticateErrorCode.invalid_token, policyGestioneToken.getRealm(),
  1776.                             false, // ritorno l'errore preciso in questo caso // policyGestioneToken.isGenericError(),
  1777.                             esitoGestioneToken.getDetails()));
  1778.                 }  
  1779.             }
  1780.            
  1781.         }
  1782.        
  1783.         if(esitoGestioneToken.isValido() &&
  1784.             esitoGestioneToken.getInformazioniToken().getNbf()!=null) {
  1785.            
  1786.             boolean future = isFuture(now, esitoGestioneToken.getInformazioniToken().getNbf());
  1787.            
  1788.             /*
  1789.              *   The "nbf" (not before) claim identifies the time before which the JWT
  1790.              *   MUST NOT be accepted for processing.  The processing of the "nbf"
  1791.              *   claim requires that the current date/time MUST be after or equal to
  1792.              *   the not-before date/time listed in the "nbf" claim.
  1793.              **/
  1794.            
  1795.             if(future){
  1796.                 esitoGestioneToken.setTokenNotUsableBefore();
  1797.                 esitoGestioneToken.setDateValide(false);
  1798.                 SimpleDateFormat sdf = DateUtils.getDefaultDateTimeFormatter(GestoreToken.DATE_FORMAT);
  1799.                 esitoGestioneToken.setDetails("Token not usable before "+sdf.format(esitoGestioneToken.getInformazioniToken().getNbf()));
  1800.                 if(policyGestioneToken.isMessageErrorGenerateEmptyMessage()) {
  1801.                     esitoGestioneToken.setErrorMessage(WWWAuthenticateGenerator.buildErrorMessage(WWWAuthenticateErrorCode.invalid_token, policyGestioneToken.getRealm(),
  1802.                             false, // ritorno l'errore preciso in questo caso // policyGestioneToken.isGenericError(),
  1803.                             esitoGestioneToken.getDetails()));  
  1804.                 }
  1805.                 else {
  1806.                     esitoGestioneToken.setWwwAuthenticateErrorHeader(WWWAuthenticateGenerator.buildHeaderValue(WWWAuthenticateErrorCode.invalid_token, policyGestioneToken.getRealm(),
  1807.                             false, // ritorno l'errore preciso in questo caso // policyGestioneToken.isGenericError(),
  1808.                             esitoGestioneToken.getDetails()));
  1809.                 }
  1810.             }
  1811.         }
  1812.        
  1813.        
  1814.        
  1815.        
  1816.         /** === IAT === ***/
  1817.        
  1818.         if(esitoGestioneToken.isValido() && checkRequired) {
  1819.            
  1820.             boolean check = isIatRequired(log, policyGestioneToken, datiInvocazione, protocolFactory, op2Properties);
  1821.             if(check && esitoGestioneToken.getInformazioniToken().getIat()==null) {
  1822.                 esitoGestioneToken.setTokenValidazioneFallita();
  1823.                 esitoGestioneToken.setDateValide(false);
  1824.                 esitoGestioneToken.setDetails("Token rejected; the 'iat' (issued at) claim is required but missing.");
  1825.                 if(policyGestioneToken.isMessageErrorGenerateEmptyMessage()) {
  1826.                     esitoGestioneToken.setErrorMessage(WWWAuthenticateGenerator.buildErrorMessage(WWWAuthenticateErrorCode.invalid_token, policyGestioneToken.getRealm(),
  1827.                             false, // ritorno l'errore preciso in questo caso // policyGestioneToken.isGenericError(),
  1828.                             esitoGestioneToken.getDetails()));          
  1829.                 }
  1830.                 else {
  1831.                     esitoGestioneToken.setWwwAuthenticateErrorHeader(WWWAuthenticateGenerator.buildHeaderValue(WWWAuthenticateErrorCode.invalid_token, policyGestioneToken.getRealm(),
  1832.                             false, // ritorno l'errore preciso in questo caso // policyGestioneToken.isGenericError(),
  1833.                             esitoGestioneToken.getDetails()));
  1834.                 }  
  1835.             }
  1836.            
  1837.         }
  1838.        
  1839.         if(esitoGestioneToken.isValido() &&
  1840.             esitoGestioneToken.getInformazioniToken().getIat()!=null) {            
  1841.             /*
  1842.              *   The "iat" (issued at) claim identifies the time at which the JWT was
  1843.              *   issued.  This claim can be used to determine the age of the JWT.
  1844.              *   The iat Claim can be used to reject tokens that were issued too far away from the current time,
  1845.              *   limiting the amount of time that nonces need to be stored to prevent attacks. The acceptable range is Client specific.
  1846.              **/
  1847.             Long old = op2Properties.getGestioneTokenIatTimeCheckMilliseconds();
  1848.             if(old!=null) {
  1849.                 Date oldMax = new Date((DateManager.getTimeMillis() - old.longValue()));
  1850.                 if(esitoGestioneToken.getInformazioniToken().getIat().before(oldMax)) {
  1851.                     esitoGestioneToken.setTokenScaduto();
  1852.                     esitoGestioneToken.setDateValide(false);
  1853.                     SimpleDateFormat sdf = DateUtils.getDefaultDateTimeFormatter(GestoreToken.DATE_FORMAT);
  1854.                     esitoGestioneToken.setDetails("Token expired; iat time '"+sdf.format(esitoGestioneToken.getInformazioniToken().getIat())+"' too old");
  1855.                     if(policyGestioneToken.isMessageErrorGenerateEmptyMessage()) {
  1856.                         esitoGestioneToken.setErrorMessage(WWWAuthenticateGenerator.buildErrorMessage(WWWAuthenticateErrorCode.invalid_token, policyGestioneToken.getRealm(),
  1857.                                 false, // ritorno l'errore preciso in questo caso // policyGestioneToken.isGenericError(),
  1858.                                 esitoGestioneToken.getDetails()));  
  1859.                     }
  1860.                     else {
  1861.                         esitoGestioneToken.setWwwAuthenticateErrorHeader(WWWAuthenticateGenerator.buildHeaderValue(WWWAuthenticateErrorCode.invalid_token, policyGestioneToken.getRealm(),
  1862.                                 false, // ritorno l'errore preciso in questo caso // policyGestioneToken.isGenericError(),
  1863.                                 esitoGestioneToken.getDetails()));
  1864.                     }
  1865.                 }
  1866.             }
  1867.            
  1868.             Long future = op2Properties.getGestioneTokenIatTimeCheckFutureToleranceMilliseconds();
  1869.             if(future!=null && future.longValue()>0) {
  1870.                 Date futureMax = new Date((DateManager.getTimeMillis() + future.longValue()));
  1871.                 if(esitoGestioneToken.getInformazioniToken().getIat().after(futureMax)) {
  1872.                     esitoGestioneToken.setTokenInTheFuture();
  1873.                     esitoGestioneToken.setDateValide(false);
  1874.                     SimpleDateFormat sdf = DateUtils.getDefaultDateTimeFormatter(GestoreToken.DATE_FORMAT);
  1875.                     esitoGestioneToken.setDetails("Token valid in the future; iat time '"+sdf.format(esitoGestioneToken.getInformazioniToken().getIat())+"' is in the future");
  1876.                     if(policyGestioneToken.isMessageErrorGenerateEmptyMessage()) {
  1877.                         esitoGestioneToken.setErrorMessage(WWWAuthenticateGenerator.buildErrorMessage(WWWAuthenticateErrorCode.invalid_token, policyGestioneToken.getRealm(),
  1878.                                 false, // ritorno l'errore preciso in questo caso // policyGestioneToken.isGenericError(),
  1879.                                 esitoGestioneToken.getDetails()));  
  1880.                     }
  1881.                     else {
  1882.                         esitoGestioneToken.setWwwAuthenticateErrorHeader(WWWAuthenticateGenerator.buildHeaderValue(WWWAuthenticateErrorCode.invalid_token, policyGestioneToken.getRealm(),
  1883.                                 false, // ritorno l'errore preciso in questo caso // policyGestioneToken.isGenericError(),
  1884.                                 esitoGestioneToken.getDetails()));
  1885.                     }
  1886.                 }
  1887.             }
  1888.            
  1889.         }
  1890.        
  1891.         if(!esitoGestioneToken.isValido()) {
  1892.             esitoGestioneToken.setNoCache(!saveErrorInCache);
  1893.         }
  1894.     }
  1895.    
  1896.     static void validazioneInformazioniTokenEnrichPDNDClientInfo(EsitoGestioneToken esitoGestioneToken, PolicyGestioneToken policyGestioneToken,
  1897.             PdDContext pddContext, IProtocolFactory<?> protocolFactory, AbstractDatiInvocazione datiInvocazione,
  1898.             SecurityToken securityTokenForContext) throws CoreException, ProtocolException {
  1899.        
  1900.         if(
  1901.                 (policyGestioneToken!=null && policyGestioneToken.getName()!=null) // dal nome della policy viene capito se e' attivo il recupero dei dati PDND
  1902.                 &&
  1903.                 (esitoGestioneToken!=null && esitoGestioneToken.getInformazioniToken()!=null && esitoGestioneToken.getInformazioniToken().getClientId()!=null) // il clientId serve per poter effettuare il recupero dei dati
  1904.                 &&
  1905.                 (datiInvocazione instanceof DatiInvocazionePortaApplicativa) // solo per erogazioni
  1906.                 &&
  1907.                 (org.openspcoop2.protocol.engine.constants.Costanti.MODIPA_PROTOCOL_NAME.equals(protocolFactory.getProtocol())) // solo per profilo modi
  1908.                 ) {
  1909.             OpenSPCoop2Properties op2Properties = OpenSPCoop2Properties.getInstance();
  1910.             if(op2Properties.isGestoreChiaviPDNDretrieveClientInfoAfterVoucherPDNDValidation()) {
  1911.                
  1912.                 IDSoggetto idSoggetto = null;
  1913.                 DatiInvocazionePortaApplicativa datiPA = (DatiInvocazionePortaApplicativa) datiInvocazione;
  1914.                 if(datiPA.getPa()!=null && datiPA.getPa().getTipoSoggettoProprietario()!=null && datiPA.getPa().getNomeSoggettoProprietario()!=null) {
  1915.                     idSoggetto = new IDSoggetto(datiPA.getPa().getTipoSoggettoProprietario(), datiPA.getPa().getNomeSoggettoProprietario());
  1916.                 }
  1917.                 else if(datiPA.getRequestInfo()!=null && datiPA.getRequestInfo().getIdentitaPdD()!=null) {
  1918.                     idSoggetto = datiPA.getRequestInfo().getIdentitaPdD();
  1919.                 }
  1920.                    
  1921.                 PDNDResolver pdndResolver = new PDNDResolver(pddContext, ModIUtils.getRemoteStoreConfig());
  1922.                 pdndResolver.enrichTokenInfo(datiInvocazione.getRequestInfo(), idSoggetto,
  1923.                         esitoGestioneToken.getInformazioniToken(), securityTokenForContext);
  1924.             }
  1925.         }
  1926.        
  1927.     }
  1928.    
  1929.     static void validazioneInformazioniTokenHeader(String jsonHeader, PolicyGestioneToken policyGestioneToken) throws TokenException {
  1930.        
  1931.         if(policyGestioneToken.isValidazioneJWTHeader()) {
  1932.            
  1933.             try {
  1934.            
  1935.                 JSONUtils jsonUtils = JSONUtils.getInstance();
  1936.                 if(jsonUtils.isJson(jsonHeader)) {
  1937.                     JsonNode root = jsonUtils.getAsNode(jsonHeader);
  1938.                     Map<String, Serializable> readClaims = jsonUtils.convertToSimpleMap(root);
  1939.                    
  1940.                     validazioneInformazioniTokenHeader(readClaims, policyGestioneToken.getValidazioneJWTHeaderTyp(), Claims.JSON_WEB_TOKEN_RFC_7515_TYPE);
  1941.                    
  1942.                     validazioneInformazioniTokenHeader(readClaims, policyGestioneToken.getValidazioneJWTHeaderCty(), Claims.JSON_WEB_TOKEN_RFC_7515_CONTENT_TYPE);
  1943.                    
  1944.                     validazioneInformazioniTokenHeader(readClaims, policyGestioneToken.getValidazioneJWTHeaderAlg(), Claims.JSON_WEB_TOKEN_RFC_7515_ALGORITHM);
  1945.                 }  
  1946.                
  1947.             }catch(Exception e) {
  1948.                 throw new TokenException("JWT header validation failed; "+e.getMessage(),e);
  1949.             }
  1950.            
  1951.         }
  1952.        
  1953.     }
  1954.    
  1955.     private static void validazioneInformazioniTokenHeader(Map<String, Serializable> readClaims, List<String> expectedValues, String claim) throws TokenException {
  1956.         if(expectedValues!=null && !expectedValues.isEmpty()) {
  1957.             String v = null;
  1958.             if(readClaims!=null && !readClaims.isEmpty()) {
  1959.                 v = TokenUtilities.getClaimAsString(readClaims,claim);
  1960.             }
  1961.             if(v==null || StringUtils.isEmpty(v)) {
  1962.                 throw new TokenException("Expected claim '"+claim+"' not found");
  1963.             }
  1964.             boolean find = false;
  1965.             for (String vCheck : expectedValues) {
  1966.                 if(v.equalsIgnoreCase(vCheck)) {
  1967.                     find = true;
  1968.                     break;
  1969.                 }
  1970.             }
  1971.             if(!find) {
  1972.                 throw new TokenException("Claim '"+claim+"' with invalid value '"+v+"'");
  1973.             }
  1974.         }
  1975.     }
  1976.    
  1977.     static String buildPrefixCacheKeyValidazione(String policy, String funzione) {
  1978.         StringBuilder bf = new StringBuilder(funzione);
  1979.         bf.append("_");
  1980.         bf.append(policy);
  1981.         bf.append("_");
  1982.         return bf.toString();
  1983.     }
  1984.     static String buildCacheKeyValidazione(String policy, String funzione, boolean portaDelegata, String token) {
  1985.         StringBuilder bf = new StringBuilder();
  1986.         bf.append(buildPrefixCacheKeyValidazione(policy, funzione));
  1987.         if(portaDelegata){
  1988.             bf.append("PD");
  1989.         }
  1990.         else {
  1991.             bf.append("PA");
  1992.         }
  1993.         bf.append("_");
  1994.         bf.append(token);
  1995.         return bf.toString();
  1996.     }
  1997.    
  1998.     static HttpResponse http(Logger log, PolicyGestioneToken policyGestioneToken, HTTP_TYPE httpType,
  1999.             DynamicDiscovery dynamicDiscovery, String token,
  2000.             PdDContext pddContext, IProtocolFactory<?> protocolFactory,
  2001.             IState state, boolean delegata, String idModulo, PortaApplicativa pa, PortaDelegata pd,
  2002.             IDSoggetto idDominio, IDServizio idServizio,
  2003.             Busta busta, RequestInfo requestInfo) throws Exception {
  2004.        
  2005.         // *** Raccola Parametri ***
  2006.        
  2007.         Map<String, Object> dynamicMap = TokenUtilities.buildDynamicMap(busta, requestInfo, pddContext, log);
  2008.        
  2009.         String endpoint = null;
  2010.         String prefixConnettore = null;
  2011.         boolean introspectionService = false;
  2012.         boolean userInfoService = false;
  2013.         switch (httpType) {
  2014.         case DYNAMIC_DISCOVERY:
  2015.             endpoint = policyGestioneToken.getDynamicDiscoveryEndpoint();
  2016.             if(endpoint!=null && !"".equals(endpoint)) {
  2017.                 endpoint = DynamicUtils.convertDynamicPropertyValue("endpoint.gwt", endpoint, dynamicMap, pddContext);  
  2018.             }
  2019.             prefixConnettore = "[EndpointDynamicDiscovery: "+endpoint+"] ";
  2020.             break;
  2021.         case INTROSPECTION:
  2022.             if(policyGestioneToken.isDynamicDiscovery()) {
  2023.                 check(dynamicDiscovery);
  2024.                 endpoint = dynamicDiscovery.getIntrospectionEndpoint();
  2025.                 if(endpoint!=null && !"".equals(endpoint)) {
  2026.                     endpoint = DynamicUtils.convertDynamicPropertyValue("endpoint.gwt", endpoint, dynamicMap, pddContext);  
  2027.                 }
  2028.                 if(endpoint==null || StringUtils.isEmpty(endpoint)) {
  2029.                     throw new TokenException("DynamicDiscovery.introspectionEndpoint undefined");
  2030.                 }
  2031.             }
  2032.             else {
  2033.                 endpoint = policyGestioneToken.getIntrospectionEndpoint();
  2034.             }
  2035.             prefixConnettore = "[EndpointIntrospection: "+endpoint+"] ";    
  2036.             introspectionService = true;
  2037.             break;
  2038.         case USER_INFO:
  2039.             if(policyGestioneToken.isDynamicDiscovery()) {
  2040.                 check(dynamicDiscovery);
  2041.                 endpoint = dynamicDiscovery.getUserinfoEndpoint();
  2042.                 if(endpoint!=null && !"".equals(endpoint)) {
  2043.                     endpoint = DynamicUtils.convertDynamicPropertyValue("endpoint.gwt", endpoint, dynamicMap, pddContext);  
  2044.                 }
  2045.                 if(endpoint==null || StringUtils.isEmpty(endpoint)) {
  2046.                     throw new TokenException("DynamicDiscovery.userinfoEndpoint undefined");
  2047.                 }
  2048.             }
  2049.             else {
  2050.                 endpoint = policyGestioneToken.getUserInfoEndpoint();
  2051.             }
  2052.             prefixConnettore = "[EndpointUserInfo: "+endpoint+"] ";    
  2053.             userInfoService = true;
  2054.             break;
  2055.         }
  2056.        
  2057.         TipoTokenRequest tipoTokenRequest = null;
  2058.         String positionTokenName = null;
  2059.         if(introspectionService) {
  2060.             tipoTokenRequest = policyGestioneToken.getIntrospectionTipoTokenRequest();  
  2061.         }
  2062.         else if(userInfoService) {
  2063.             tipoTokenRequest = policyGestioneToken.getUserInfoTipoTokenRequest();      
  2064.         }
  2065.         if(tipoTokenRequest!=null) {
  2066.             switch (tipoTokenRequest) {
  2067.             case authorization:
  2068.                 break;
  2069.             case header:
  2070.                 if(introspectionService) {
  2071.                     positionTokenName = policyGestioneToken.getIntrospectionTipoTokenRequestHeaderName();
  2072.                 }else {
  2073.                     positionTokenName = policyGestioneToken.getUserInfoTipoTokenRequestHeaderName();
  2074.                 }
  2075.                 break;
  2076.             case url:
  2077.                 if(introspectionService) {
  2078.                     positionTokenName = policyGestioneToken.getIntrospectionTipoTokenRequestUrlPropertyName();
  2079.                 }else {
  2080.                     positionTokenName = policyGestioneToken.getUserInfoTipoTokenRequestUrlPropertyName();
  2081.                 }
  2082.                 break;
  2083.             case form:
  2084.                 if(introspectionService) {
  2085.                     positionTokenName = policyGestioneToken.getIntrospectionTipoTokenRequestFormPropertyName();
  2086.                 }else {
  2087.                     positionTokenName = policyGestioneToken.getUserInfoTipoTokenRequestFormPropertyName();
  2088.                 }
  2089.                 break;
  2090.             }
  2091.         }
  2092.         if(positionTokenName!=null && !"".equals(positionTokenName)) {
  2093.             positionTokenName = DynamicUtils.convertDynamicPropertyValue("positionTokenName.gwt", positionTokenName, dynamicMap, pddContext);  
  2094.         }
  2095.        
  2096.         String contentType = null;
  2097.         if(introspectionService || userInfoService) {
  2098.             if(introspectionService) {
  2099.                 contentType = policyGestioneToken.getIntrospectionContentType();
  2100.             }else {
  2101.                 contentType = policyGestioneToken.getUserInfoContentType();
  2102.             }
  2103.         }
  2104.         if(contentType!=null && !"".equals(contentType)) {
  2105.             contentType = DynamicUtils.convertDynamicPropertyValue("contentType.gwt", contentType, dynamicMap, pddContext);
  2106.         }
  2107.        
  2108.         HttpRequestMethod httpMethod = null;
  2109.         switch (httpType) {
  2110.         case DYNAMIC_DISCOVERY:
  2111.             httpMethod = HttpRequestMethod.GET;
  2112.             break;
  2113.         case INTROSPECTION:
  2114.             httpMethod = policyGestioneToken.getIntrospectionHttpMethod();
  2115.             break;
  2116.         case USER_INFO:
  2117.             httpMethod = policyGestioneToken.getUserInfoHttpMethod();
  2118.             break;
  2119.         }
  2120.        
  2121.        
  2122.        
  2123.         // Nell'endpoint config ci finisce i timeout e la configurazione proxy
  2124.         Properties endpointConfig = policyGestioneToken.getProperties().get(Costanti.POLICY_ENDPOINT_CONFIG);
  2125.         resolveDynamicProperyValues(endpointConfig, dynamicMap, pddContext);
  2126.         if(endpointConfig.containsKey(CostantiConnettori.CONNETTORE_HTTP_PROXY_HOSTNAME)) {
  2127.             String hostProxy = endpointConfig.getProperty(CostantiConnettori.CONNETTORE_HTTP_PROXY_HOSTNAME);
  2128.             String portProxy = endpointConfig.getProperty(CostantiConnettori.CONNETTORE_HTTP_PROXY_PORT);
  2129.             prefixConnettore = prefixConnettore+GestoreToken.getMessageViaProxy(hostProxy, portProxy);
  2130.         }
  2131.        
  2132.         boolean https = false;
  2133.         if(!https) {
  2134.             switch (httpType) {
  2135.             case DYNAMIC_DISCOVERY:
  2136.                 https = policyGestioneToken.isEndpointHttps(false, false);
  2137.                 break;
  2138.             case INTROSPECTION:
  2139.                 https = policyGestioneToken.isEndpointHttps(true, false);
  2140.                 break;
  2141.             case USER_INFO:
  2142.                 https = policyGestioneToken.isEndpointHttps(false, true);
  2143.                 break;
  2144.             }
  2145.         }
  2146.         boolean httpsClient = false;
  2147.         Properties sslConfig = null;
  2148.         Properties sslClientConfig = null;
  2149.         if(https) {
  2150.             sslConfig = policyGestioneToken.getProperties().get(Costanti.POLICY_ENDPOINT_SSL_CONFIG);
  2151.             resolveDynamicProperyValues(sslConfig, dynamicMap, pddContext);
  2152.             if(introspectionService || userInfoService) {
  2153.                 if(introspectionService) {
  2154.                     httpsClient = policyGestioneToken.isIntrospectionHttpsAuthentication();
  2155.                 }else {
  2156.                     httpsClient = policyGestioneToken.isUserInfoHttpsAuthentication();
  2157.                 }
  2158.             }
  2159.             if(httpsClient) {
  2160.                 sslClientConfig = policyGestioneToken.getProperties().get(Costanti.POLICY_ENDPOINT_SSL_CLIENT_CONFIG);
  2161.                 TokenUtilities.injectSameKeystoreForHttpsClient(sslConfig, sslClientConfig);
  2162.                 resolveDynamicProperyValues(sslClientConfig, dynamicMap, pddContext);
  2163.             }
  2164.         }
  2165.        
  2166.         boolean basic = false;
  2167.         String username = null;
  2168.         String password = null;
  2169.         if(introspectionService || userInfoService) {
  2170.             if(introspectionService) {
  2171.                 basic = policyGestioneToken.isIntrospectionBasicAuthentication();
  2172.             }else {
  2173.                 basic = policyGestioneToken.isUserInfoBasicAuthentication();
  2174.             }
  2175.         }
  2176.         if(basic) {
  2177.             if(introspectionService) {
  2178.                 username = policyGestioneToken.getIntrospectionBasicAuthenticationUsername();
  2179.                 password = policyGestioneToken.getIntrospectionBasicAuthenticationPassword();
  2180.             }
  2181.             else {
  2182.                 username = policyGestioneToken.getUserInfoBasicAuthenticationUsername();
  2183.                 password = policyGestioneToken.getUserInfoBasicAuthenticationPassword();
  2184.             }
  2185.             if(username!=null && !"".equals(username)) {
  2186.                 username = DynamicUtils.convertDynamicPropertyValue("username.gwt", username, dynamicMap, pddContext);  
  2187.             }
  2188.             if(password!=null && !"".equals(password)) {
  2189.                 password = DynamicUtils.convertDynamicPropertyValue("password.gwt", password, dynamicMap, pddContext);  
  2190.             }
  2191.         }
  2192.        
  2193.         boolean bearer = false;
  2194.         String bearerToken = null;
  2195.         if(introspectionService || userInfoService) {
  2196.             if(introspectionService) {
  2197.                 bearer = policyGestioneToken.isIntrospectionBearerAuthentication();
  2198.             }else {
  2199.                 bearer = policyGestioneToken.isUserInfoBearerAuthentication();
  2200.             }
  2201.         }
  2202.         if(bearer) {
  2203.             if(introspectionService) {
  2204.                 bearerToken = policyGestioneToken.getIntrospectionBeareAuthenticationToken();
  2205.             }
  2206.             else {
  2207.                 bearerToken = policyGestioneToken.getUserInfoBeareAuthenticationToken();
  2208.             }
  2209.             if(bearerToken!=null && !"".equals(bearerToken)) {
  2210.                 bearerToken = DynamicUtils.convertDynamicPropertyValue("bearerToken.gwt", bearerToken, dynamicMap, pddContext);
  2211.             }
  2212.         }
  2213.        
  2214.        
  2215.        
  2216.         // *** Definizione Connettore ***
  2217.        
  2218.         ConnettoreMsg connettoreMsg = new ConnettoreMsg();
  2219.         ConnettoreBaseHTTP connettore = null;
  2220.         if(https) {
  2221.             connettoreMsg.setTipoConnettore(TipiConnettore.HTTPS.getNome());
  2222.             connettore = new ConnettoreHTTPS();
  2223.         }
  2224.         else {
  2225.             connettoreMsg.setTipoConnettore(TipiConnettore.HTTP.getNome());
  2226.             connettore = new ConnettoreHTTP();
  2227.         }
  2228.         connettoreMsg.setIdModulo(idModulo);
  2229.         connettoreMsg.setState(state);
  2230.         PolicyTimeoutConfig policyConfig = new PolicyTimeoutConfig();
  2231.         switch (httpType) {
  2232.         case DYNAMIC_DISCOVERY:
  2233.             policyConfig.setPolicyValidazioneDynamicDiscovery(policyGestioneToken.getName());  
  2234.             break;
  2235.         case INTROSPECTION:
  2236.             policyConfig.setPolicyValidazioneIntrospection(policyGestioneToken.getName());
  2237.             break;
  2238.         case USER_INFO:
  2239.             policyConfig.setPolicyValidazioneUserInfo(policyGestioneToken.getName());
  2240.             break;
  2241.         }
  2242.         connettoreMsg.setPolicyTimeoutConfig(policyConfig);
  2243.        
  2244.         ForwardProxy forwardProxy = TokenUtilities.getForwardProxy(policyGestioneToken,
  2245.                 requestInfo, state, delegata,
  2246.                 idDominio, idServizio);
  2247.         if(forwardProxy!=null && forwardProxy.isEnabled() && forwardProxy.getConfigToken()!=null) {
  2248.             boolean enabled = false;
  2249.             switch (httpType) {
  2250.             case DYNAMIC_DISCOVERY:
  2251.                 enabled = forwardProxy.getConfigToken().isTokenDynamicDiscoveryEnabled();
  2252.                 break;
  2253.             case INTROSPECTION:
  2254.                 enabled = forwardProxy.getConfigToken().isTokenIntrospectionEnabled();
  2255.                 break;
  2256.             case USER_INFO:
  2257.                 enabled = forwardProxy.getConfigToken().isTokenUserInfoEnabled();
  2258.                 break;
  2259.             }
  2260.             if(enabled) {
  2261.                 connettoreMsg.setForwardProxy(forwardProxy);
  2262.             }
  2263.         }
  2264.        
  2265.         connettore.setForceDisable_proxyPassReverse(true);
  2266.         connettore.init(pddContext, protocolFactory);
  2267.         connettore.setRegisterSendIntoContext(false);
  2268.        
  2269.         if(basic){
  2270.             InvocazioneCredenziali credenziali = new InvocazioneCredenziali();
  2271.             credenziali.setUser(username);
  2272.             credenziali.setPassword(password);
  2273.             connettoreMsg.setCredenziali(credenziali);
  2274.         }
  2275.        
  2276.         connettoreMsg.setConnectorProperties(new java.util.HashMap<>());
  2277.         connettoreMsg.getConnectorProperties().put(CostantiConnettori.CONNETTORE_LOCATION, endpoint);
  2278.         boolean debug = false;
  2279.         OpenSPCoop2Properties properties = OpenSPCoop2Properties.getInstance();
  2280.         switch (httpType) {
  2281.         case DYNAMIC_DISCOVERY:
  2282.             debug = properties.isGestioneTokenDynamicDiscoveryDebug();
  2283.             break;
  2284.         case INTROSPECTION:
  2285.             debug = properties.isGestioneTokenIntrospectionDebug();
  2286.             break;
  2287.         case USER_INFO:
  2288.             debug = properties.isGestioneTokenUserInfoDebug();
  2289.             break;
  2290.         }
  2291.         if(debug) {
  2292.             connettoreMsg.getConnectorProperties().put(CostantiConnettori.CONNETTORE_DEBUG, true+"");
  2293.         }
  2294.         connettoreMsg.getConnectorProperties().put(CostantiConnettori.CONNETTORE_HTTP_DATA_TRANSFER_MODE, TransferLengthModes.CONTENT_LENGTH.getNome());
  2295.         GestoreToken.addProperties(connettoreMsg, endpointConfig);
  2296.         if(https) {
  2297.             GestoreToken.addProperties(connettoreMsg, sslConfig);
  2298.             if(httpsClient) {
  2299.                 GestoreToken.addProperties(connettoreMsg, sslClientConfig);
  2300.             }
  2301.         }
  2302.        
  2303.         byte[] content = null;
  2304.        
  2305.         TransportRequestContext transportRequestContext = new TransportRequestContext(log);
  2306.         if(httpMethod!=null) {
  2307.             transportRequestContext.setRequestType(httpMethod.name());
  2308.         }
  2309.         transportRequestContext.setHeaders(new HashMap<>());
  2310.         if(bearer) {
  2311.             String authorizationHeader = HttpConstants.AUTHORIZATION_PREFIX_BEARER+bearerToken;
  2312.             TransportUtils.setHeader(transportRequestContext.getHeaders(),HttpConstants.AUTHORIZATION, authorizationHeader);
  2313.         }
  2314.         if(contentType!=null) {
  2315.             TransportUtils.setHeader(transportRequestContext.getHeaders(),HttpConstants.CONTENT_TYPE, contentType);
  2316.         }
  2317.         if(tipoTokenRequest!=null) {
  2318.             switch (tipoTokenRequest) {
  2319.             case authorization:
  2320.                 transportRequestContext.removeHeader(HttpConstants.AUTHORIZATION);
  2321.                 String authorizationHeader = HttpConstants.AUTHORIZATION_PREFIX_BEARER+token;
  2322.                 TransportUtils.setHeader(transportRequestContext.getHeaders(),HttpConstants.AUTHORIZATION, authorizationHeader);
  2323.                 break;
  2324.             case header:
  2325.                 TransportUtils.setHeader(transportRequestContext.getHeaders(),positionTokenName, token);
  2326.                 break;
  2327.             case url:
  2328.                 transportRequestContext.setParameters(new HashMap<>());
  2329.                 TransportUtils.setParameter(transportRequestContext.getParameters(),positionTokenName, token);
  2330.                 break;
  2331.             case form:
  2332.                 transportRequestContext.removeHeader(HttpConstants.CONTENT_TYPE);
  2333.                 TransportUtils.setHeader(transportRequestContext.getHeaders(),HttpConstants.CONTENT_TYPE, HttpConstants.CONTENT_TYPE_X_WWW_FORM_URLENCODED);
  2334.                 content = (positionTokenName+"="+token).getBytes();
  2335.                 break;
  2336.             }
  2337.         }
  2338.        
  2339.         OpenSPCoop2MessageParseResult pr = OpenSPCoop2MessageFactory.getDefaultMessageFactory().createMessage(MessageType.BINARY, transportRequestContext, content);
  2340.         OpenSPCoop2Message msg = pr.getMessage_throwParseException();
  2341.         connettoreMsg.setRequestMessage(msg);
  2342.         connettoreMsg.setGenerateErrorWithConnectorPrefix(false);
  2343.         connettore.setHttpMethod(msg);
  2344.         connettore.setPa(pa);
  2345.         connettore.setPd(pd);
  2346.        
  2347.         ResponseCachingConfigurazione responseCachingConfigurazione = new ResponseCachingConfigurazione();
  2348.         responseCachingConfigurazione.setStato(StatoFunzionalita.DISABILITATO);
  2349.         boolean send = connettore.send(responseCachingConfigurazione, connettoreMsg);
  2350.         if(!send) {
  2351.             if(connettore.getEccezioneProcessamento()!=null) {
  2352.                 throw new TokenException(prefixConnettore+connettore.getErrore(), connettore.getEccezioneProcessamento());
  2353.             }
  2354.             else {
  2355.                 throw new TokenException(prefixConnettore+connettore.getErrore());
  2356.             }
  2357.         }
  2358.        
  2359.         OpenSPCoop2Message msgResponse = connettore.getResponse();
  2360.         ByteArrayOutputStream bout = null;
  2361.         if(msgResponse!=null) {
  2362.             bout = new ByteArrayOutputStream();
  2363.             if(msgResponse!=null) {
  2364.                 msgResponse.writeTo(bout, true);
  2365.             }
  2366.             bout.flush();
  2367.             bout.close();
  2368.         }
  2369.        
  2370.         HttpResponse httpResponse = new HttpResponse();
  2371.         httpResponse.setResultHTTPOperation(connettore.getCodiceTrasporto());
  2372.        
  2373.         if(connettore.getCodiceTrasporto() >= 200 &&  connettore.getCodiceTrasporto() < 299) {
  2374.             String msgSuccess = prefixConnettore+GestoreToken.getMessageConnettoreConnessioneSuccesso(connettore);
  2375.             if(bout!=null && bout.size()>0) {
  2376.                 log.debug(msgSuccess);
  2377.                 httpResponse.setContent(bout.toByteArray());
  2378.                 return httpResponse;
  2379.             }
  2380.             else {
  2381.                 throw new TokenException(msgSuccess+GestoreToken.CONNETTORE_RISPOSTA_NON_PERVENUTA);
  2382.             }
  2383.         }
  2384.         else {
  2385.             String msgError = prefixConnettore+GestoreToken.getMessageConnettoreConnessioneErrore(connettore);
  2386.             if(bout!=null && bout.size()>0) {
  2387.                 String e = msgError+": "+bout.toString();
  2388.                 log.debug(e);
  2389.                 httpResponse.setContent(bout.toByteArray());
  2390.                 return httpResponse;
  2391.             }
  2392.             else {
  2393.                 log.error(msgError);
  2394.                 throw new TokenException(msgError);
  2395.             }
  2396.         }
  2397.        
  2398.        
  2399.     }
  2400.    
  2401.     private static void resolveDynamicProperyValues(Properties p,
  2402.             Map<String, Object> dynamicMap, Context context) throws DynamicException {
  2403.         if(p!=null && !p.isEmpty()) {
  2404.             Enumeration<?> oKey = p.keys();
  2405.             while (oKey.hasMoreElements()) {
  2406.                 Object object = oKey.nextElement();
  2407.                 if(object instanceof String) {
  2408.                     String key = (String) object;
  2409.                     String value = p.getProperty(key);
  2410.                     if(value!=null && !"".equals(value) && value.contains("{") && value.contains("}")) {
  2411.                         value = DynamicUtils.convertDynamicPropertyValue(key+".gwt", value, dynamicMap, context);
  2412.                         p.put(key, value);
  2413.                     }          
  2414.                 }
  2415.             }
  2416.         }
  2417.     }

  2418.     static void check(DynamicDiscovery dynamicDiscovery) throws TokenException {
  2419.         if(dynamicDiscovery==null) {
  2420.             throw new TokenException("DynamicDiscovery information not found");
  2421.         }
  2422.         if(!dynamicDiscovery.isValid()) {
  2423.             throw new TokenException("DynamicDiscovery failed");
  2424.         }
  2425.     }
  2426.    
  2427. }

  2428. enum HTTP_TYPE {
  2429.    
  2430.     DYNAMIC_DISCOVERY, INTROSPECTION, USER_INFO
  2431.    
  2432. }