TokenUtilities.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.Serializable;
  22. import java.util.ArrayList;
  23. import java.util.HashMap;
  24. import java.util.List;
  25. import java.util.Map;
  26. import java.util.Properties;

  27. import org.apache.commons.lang.StringUtils;
  28. import org.apache.cxf.rt.security.rs.RSSecurityConstants;
  29. import org.openspcoop2.core.commons.DBUtils;
  30. import org.openspcoop2.core.commons.Filtri;
  31. import org.openspcoop2.core.commons.ISearch;
  32. import org.openspcoop2.core.commons.Liste;
  33. import org.openspcoop2.core.commons.Search;
  34. import org.openspcoop2.core.config.GenericProperties;
  35. import org.openspcoop2.core.config.GestioneToken;
  36. import org.openspcoop2.core.config.Property;
  37. import org.openspcoop2.core.config.constants.CostantiConfigurazione;
  38. import org.openspcoop2.core.constants.CostantiConnettori;
  39. import org.openspcoop2.core.id.IDGenericProperties;
  40. import org.openspcoop2.core.id.IDServizio;
  41. import org.openspcoop2.core.id.IDSoggetto;
  42. import org.openspcoop2.core.mvc.properties.Item;
  43. import org.openspcoop2.core.mvc.properties.constants.ItemType;
  44. import org.openspcoop2.core.mvc.properties.provider.ExternalResources;
  45. import org.openspcoop2.core.mvc.properties.provider.ProviderException;
  46. import org.openspcoop2.core.mvc.properties.provider.ProviderValidationException;
  47. import org.openspcoop2.core.mvc.properties.utils.DBPropertiesUtils;
  48. import org.openspcoop2.core.mvc.properties.utils.MultiPropertiesUtilities;
  49. import org.openspcoop2.core.plugins.Plugin;
  50. import org.openspcoop2.core.plugins.constants.TipoPlugin;
  51. import org.openspcoop2.core.plugins.utils.PluginsDriverUtils;
  52. import org.openspcoop2.pdd.config.ConfigurazionePdDManager;
  53. import org.openspcoop2.pdd.config.ForwardProxy;
  54. import org.openspcoop2.pdd.core.dynamic.DynamicMapBuilderUtils;
  55. import org.openspcoop2.pdd.core.token.attribute_authority.PolicyAttributeAuthority;
  56. import org.openspcoop2.protocol.sdk.Busta;
  57. import org.openspcoop2.protocol.sdk.Context;
  58. import org.openspcoop2.protocol.sdk.state.IState;
  59. import org.openspcoop2.protocol.sdk.state.RequestInfo;
  60. import org.openspcoop2.security.message.constants.SecurityConstants;
  61. import org.openspcoop2.security.message.jose.JOSECostanti;
  62. import org.openspcoop2.security.message.utils.AbstractSecurityProvider;
  63. import org.openspcoop2.utils.certificate.KeystoreParams;
  64. import org.openspcoop2.utils.certificate.KeystoreType;
  65. import org.slf4j.Logger;

  66. /**    
  67.  * TokenUtilities
  68.  *
  69.  * @author Poli Andrea (poli@link.it)
  70.  * @author $Author$
  71.  * @version $Rev$, $Date$
  72.  */
  73. public class TokenUtilities {
  74.    
  75.     private TokenUtilities() {}

  76.     public static Properties getDefaultProperties(Map<String, Properties> mapProperties) {
  77.         return MultiPropertiesUtilities.getDefaultProperties(mapProperties);
  78.     }
  79.     public static Properties getDynamicDiscoveryClaimsMappingProperties(Map<String, Properties> mapProperties) {
  80.         return mapProperties.get(Costanti.DYNAMIC_DISCOVERY_PARSER_COLLECTION_ID);
  81.     }
  82.     public static Properties getValidazioneJwtClaimsMappingProperties(Map<String, Properties> mapProperties) {
  83.         return mapProperties.get(Costanti.VALIDAZIONE_JWT_TOKEN_PARSER_COLLECTION_ID);
  84.     }
  85.     public static Properties getIntrospectionClaimsMappingProperties(Map<String, Properties> mapProperties) {
  86.         return mapProperties.get(Costanti.INTROSPECTION_TOKEN_PARSER_COLLECTION_ID);
  87.     }
  88.     public static Properties getUserInfoClaimsMappingProperties(Map<String, Properties> mapProperties) {
  89.         return mapProperties.get(Costanti.USERINFO_TOKEN_PARSER_COLLECTION_ID);
  90.     }
  91.    
  92.     public static Properties getRetrieveResponseClaimsMappingProperties(Map<String, Properties> mapProperties) {
  93.         return mapProperties.get(Costanti.RETRIEVE_TOKEN_PARSER_COLLECTION_ID);
  94.     }
  95.    
  96.     public static List<String> getClaims(Properties p, String name) {
  97.         String v = p.getProperty(name);
  98.         List<String> l = new ArrayList<>();
  99.         if(v!=null) {
  100.             if(v.contains(",")) {
  101.                 String [] tmp = v.split(",");
  102.                 for (String s : tmp) {
  103.                     if(StringUtils.isNotEmpty(s.trim())) {
  104.                         l.add(s.trim());
  105.                     }
  106.                 }
  107.             }
  108.             else {
  109.                 l.add(v.trim());
  110.             }
  111.         }
  112.         return l;
  113.     }
  114.    
  115.     public static Map<String, Properties> getMultiProperties(GenericProperties gp) throws ProviderException {
  116.         Map<String, Properties> multiProperties = null;
  117.         try {
  118.             HashMap<String, String> properties = new HashMap<>();
  119.             for (Property pConfig : gp.getPropertyList()) {
  120.                 properties.put(pConfig.getNome(), pConfig.getValore());
  121.             }
  122.             multiProperties = DBPropertiesUtils.toMultiMap(properties);
  123.         }catch(Exception e) {
  124.             throw new ProviderException(e.getMessage(),e);
  125.         }
  126.         return multiProperties;
  127.     }

  128.     public static boolean isDynamicDiscoveryEnabled(Map<String, Properties> mapProperties) {
  129.         return isDynamicDiscoveryEnabled(getDefaultProperties(mapProperties));
  130.     }
  131.     public static boolean isDynamicDiscoveryEnabled(Properties pDefault) {
  132.         return isEnabled(pDefault, Costanti.POLICY_DISCOVERY_STATO);
  133.     }
  134.     public static boolean isDynamicDiscoveryEnabled(GenericProperties gp) throws ProviderException {
  135.         Map<String, Properties> multiProperties = getMultiProperties(gp);
  136.         return isDynamicDiscoveryEnabled(multiProperties);
  137.     }
  138.    
  139.     public static boolean isValidazioneEnabled(Map<String, Properties> mapProperties) {
  140.         return isValidazioneEnabled(getDefaultProperties(mapProperties));
  141.     }
  142.     public static boolean isValidazioneEnabled(Properties pDefault) {
  143.         return isEnabled(pDefault, Costanti.POLICY_VALIDAZIONE_STATO);
  144.     }
  145.     public static boolean isValidazioneEnabled(GenericProperties gp) throws ProviderException {
  146.         Map<String, Properties> multiProperties = getMultiProperties(gp);
  147.         return isValidazioneEnabled(multiProperties);
  148.     }
  149.        
  150.     public static boolean isIntrospectionEnabled(Map<String, Properties> mapProperties) {
  151.         return isIntrospectionEnabled(getDefaultProperties(mapProperties));
  152.     }
  153.     public static boolean isIntrospectionEnabled(Properties pDefault) {
  154.         return isEnabled(pDefault, Costanti.POLICY_INTROSPECTION_STATO);
  155.     }
  156.     public static boolean isIntrospectionEnabled(GenericProperties gp) throws ProviderException {
  157.         Map<String, Properties> multiProperties = getMultiProperties(gp);
  158.         return isIntrospectionEnabled(multiProperties);
  159.     }
  160.    
  161.     public static boolean isUserInfoEnabled(Map<String, Properties> mapProperties) {
  162.         return isUserInfoEnabled(getDefaultProperties(mapProperties));
  163.     }
  164.     public static boolean isUserInfoEnabled(Properties pDefault) {
  165.         return isEnabled(pDefault, Costanti.POLICY_USER_INFO_STATO);
  166.     }
  167.     public static boolean isUserInfoEnabled(GenericProperties gp) throws ProviderException {
  168.         Map<String, Properties> multiProperties = getMultiProperties(gp);
  169.         return isUserInfoEnabled(multiProperties);
  170.     }
  171.    
  172.     public static boolean isTokenForwardEnabled(Map<String, Properties> mapProperties) {
  173.         return isTokenForwardEnabled(getDefaultProperties(mapProperties));
  174.     }
  175.     public static boolean isTokenForwardEnabled(Properties pDefault) {
  176.         return isEnabled(pDefault, Costanti.POLICY_TOKEN_FORWARD_STATO);
  177.     }
  178.     public static boolean isTokenForwardEnabled(GenericProperties gp) throws ProviderException {
  179.         Map<String, Properties> multiProperties = getMultiProperties(gp);
  180.         return isTokenForwardEnabled(multiProperties);
  181.     }
  182.    
  183.     public static boolean isEnabled(Properties p, String propertyName) {
  184.         return MultiPropertiesUtilities.isEnabled(p, propertyName);
  185.     }
  186.    
  187.     private static String getPrefixPolicy(GenericProperties gp) {
  188.         return "La configurazione nella policy "+gp.getNome();
  189.     }
  190.    
  191.     public static KeystoreParams getValidazioneJwtKeystoreParams(GenericProperties gp) throws TokenException, ProviderException, ProviderValidationException {
  192.         PolicyGestioneToken policy = TokenUtilities.convertTo(gp, new GestioneToken());
  193.         if(!TokenUtilities.isValidazioneEnabled(gp)) {
  194.             throw new TokenException(getPrefixPolicy(gp)+" non utilizza la funzionalità di validazione JWT");
  195.         }
  196.         return getValidazioneJwtKeystoreParams(policy);
  197.     }
  198.     public static KeystoreParams getValidazioneJwtKeystoreParams(PolicyGestioneToken policy) throws TokenException {
  199.         String tokenType = policy.getTipoToken();
  200.         Properties p = null;
  201.         if(org.openspcoop2.pdd.core.token.Costanti.POLICY_TOKEN_TYPE_JWS.equals(tokenType)) {
  202.             // JWS Compact              
  203.             p = policy.getProperties().get(org.openspcoop2.pdd.core.token.Costanti.POLICY_VALIDAZIONE_JWS_VERIFICA_PROP_REF_ID);
  204.         }
  205.         else if(org.openspcoop2.pdd.core.token.Costanti.POLICY_TOKEN_TYPE_JWE.equals(tokenType)) {
  206.             // JWE Compact
  207.             p = policy.getProperties().get(org.openspcoop2.pdd.core.token.Costanti.POLICY_VALIDAZIONE_JWE_DECRYPT_PROP_REF_ID);
  208.         }
  209.         if(p!=null && p.containsKey(SecurityConstants.JOSE_KEYSTORE_FILE)) {
  210.             KeystoreParams keystoreParams = new KeystoreParams();
  211.             keystoreParams.setPath(p.getProperty(SecurityConstants.JOSE_KEYSTORE_FILE));
  212.             String type = p.getProperty(SecurityConstants.JOSE_KEYSTORE_TYPE);
  213.             if(type==null) {
  214.                 type = KeystoreType.JKS.getNome();
  215.             }
  216.             keystoreParams.setType(type);
  217.             keystoreParams.setPassword(p.getProperty(SecurityConstants.JOSE_KEYSTORE_PSWD));
  218.             keystoreParams.setKeyAlias(p.getProperty(SecurityConstants.JOSE_KEYSTORE_KEY_ALIAS));
  219.             keystoreParams.setKeyPassword(p.getProperty(RSSecurityConstants.RSSEC_KEY_PSWD));
  220.            
  221.             fillKeyPairParamters(keystoreParams, type, p);
  222.            
  223.             return keystoreParams;
  224.         }
  225.         return null;
  226.     }
  227.     private static void fillKeyPairParamters(KeystoreParams keystoreParams, String type, Properties p) throws TokenException {
  228.         if(SecurityConstants.KEYSTORE_TYPE_KEY_PAIR_VALUE.equalsIgnoreCase(type)) {
  229.             String keystorePublicKeyFile = p.getProperty(SecurityConstants.JOSE_KEYSTORE_PUBLIC_KEY);
  230.             if(keystorePublicKeyFile==null) {
  231.                 throw new TokenException("Public key file undefined");
  232.             }
  233.             keystoreParams.setKeyPairPublicKeyPath(keystorePublicKeyFile);
  234.         }
  235.        
  236.         if(SecurityConstants.KEYSTORE_TYPE_KEY_PAIR_VALUE.equalsIgnoreCase(type)
  237.                 ||
  238.             SecurityConstants.KEYSTORE_TYPE_PUBLIC_KEY_VALUE.equalsIgnoreCase(type)) {
  239.             String keyPairAlgorithm = p.getProperty(SecurityConstants.JOSE_KEYSTORE_KEY_ALGORITHM);
  240.             if(keyPairAlgorithm==null) {
  241.                 throw new TokenException("Key pair algorithm undefined");
  242.             }
  243.             keystoreParams.setKeyPairAlgorithm(keyPairAlgorithm);
  244.         }
  245.     }
  246.    
  247.     public static KeystoreParams getForwardToJwtKeystoreParams(GenericProperties gp) throws TokenException, ProviderException, ProviderValidationException {
  248.         PolicyGestioneToken policy = TokenUtilities.convertTo(gp, new GestioneToken());
  249.         if(!TokenUtilities.isTokenForwardEnabled(gp) || !policy.isForwardTokenInformazioniRaccolte()) {
  250.             throw new TokenException(getPrefixPolicy(gp)+" non utilizza la funzionalità di forward delle informazioni raccolte del token");
  251.         }
  252.         return getForwardToJwtKeystoreParams(policy);
  253.     }
  254.     public static KeystoreParams getForwardToJwtKeystoreParams(PolicyGestioneToken policy) throws TokenException {
  255.         String forwardInformazioniRaccolteMode = policy.getForwardTokenInformazioniRaccolteMode();
  256.         Properties p = null;
  257.         if(Costanti.POLICY_TOKEN_FORWARD_INFO_RACCOLTE_MODE_OP2_JWS.equals(forwardInformazioniRaccolteMode) ||
  258.                 Costanti.POLICY_TOKEN_FORWARD_INFO_RACCOLTE_MODE_JWS.equals(forwardInformazioniRaccolteMode)) {
  259.             // JWS Compact              
  260.             p = policy.getProperties().get(org.openspcoop2.pdd.core.token.Costanti.POLICY_TOKEN_FORWARD_INFO_RACCOLTE_SIGNATURE_PROP_REF_ID);
  261.         }
  262.         else if(Costanti.POLICY_TOKEN_FORWARD_INFO_RACCOLTE_MODE_JWE.equals(forwardInformazioniRaccolteMode)) {
  263.             // JWE Compact
  264.             p = policy.getProperties().get(org.openspcoop2.pdd.core.token.Costanti.POLICY_TOKEN_FORWARD_INFO_RACCOLTE_ENCRYP_PROP_REF_ID);
  265.         }
  266.         if(p!=null && p.containsKey(SecurityConstants.JOSE_KEYSTORE_FILE)) {
  267.             KeystoreParams keystoreParams = new KeystoreParams();
  268.             keystoreParams.setPath(p.getProperty(SecurityConstants.JOSE_KEYSTORE_FILE));
  269.             String type = p.getProperty(SecurityConstants.JOSE_KEYSTORE_TYPE);
  270.             if(type==null) {
  271.                 type = KeystoreType.JKS.getNome();
  272.             }
  273.             keystoreParams.setType(type);
  274.             keystoreParams.setPassword(p.getProperty(SecurityConstants.JOSE_KEYSTORE_PSWD));
  275.             keystoreParams.setKeyAlias(p.getProperty(SecurityConstants.JOSE_KEYSTORE_KEY_ALIAS));
  276.             keystoreParams.setKeyPassword(p.getProperty(RSSecurityConstants.RSSEC_KEY_PSWD));
  277.             keystoreParams.setByokPolicy(p.getProperty(SecurityConstants.JOSE_KEYSTORE_BYOK_POLICY));
  278.            
  279.             fillKeyPairParamters(keystoreParams, type, p);
  280.            
  281.             return keystoreParams;
  282.         }
  283.         return null;
  284.     }
  285.    
  286.     public static PolicyGestioneToken convertTo(GenericProperties gp, GestioneToken gestioneToken) throws ProviderException, ProviderValidationException {
  287.    
  288.         PolicyGestioneToken policy = new PolicyGestioneToken();
  289.         policy.setName(gp.getNome());
  290.         policy.setDescrizione(gp.getDescrizione());
  291.        
  292.         Map<String, Properties> multiProperties = TokenUtilities.getMultiProperties(gp);
  293.         policy.setProperties(multiProperties);
  294.        
  295.         policy.setTokenOpzionale(false);
  296.        
  297.         policy.setDynamicDiscovery(false);
  298.        
  299.         policy.setValidazioneJWT(false);
  300.         policy.setValidazioneJWTWarningOnly(false);
  301.        
  302.         policy.setIntrospection(false);
  303.         policy.setIntrospectionWarningOnly(false);
  304.        
  305.         policy.setUserInfo(false);
  306.         policy.setUserInfoWarningOnly(false);
  307.        
  308.         policy.setForwardToken(false);
  309.        
  310.         if(gestioneToken!=null) {
  311.             fill(policy, gestioneToken, multiProperties);
  312.         }
  313.        
  314.         return policy;

  315.     }
  316.     private static void fill(PolicyGestioneToken policy, GestioneToken gestioneToken, Map<String, Properties> multiProperties) {
  317.         if(gestioneToken.getTokenOpzionale()!=null) {
  318.             policy.setTokenOpzionale(org.openspcoop2.core.config.constants.StatoFunzionalita.ABILITATO.equals(gestioneToken.getTokenOpzionale()));
  319.         }
  320.        
  321.         boolean dynamicDiscoveryEnabledDaPolicy = isDynamicDiscoveryEnabled(multiProperties);
  322.         policy.setDynamicDiscovery(dynamicDiscoveryEnabledDaPolicy);
  323.        
  324.         boolean validazioneEnabledDaPolicy = isValidazioneEnabled(multiProperties);
  325.         if(validazioneEnabledDaPolicy &&
  326.             gestioneToken.getValidazione()!=null) {
  327.             switch (gestioneToken.getValidazione()) {
  328.             case ABILITATO:
  329.                 policy.setValidazioneJWT(true);
  330.                 policy.setValidazioneJWTWarningOnly(false);
  331.                 break;
  332.             case WARNING_ONLY:
  333.                 policy.setValidazioneJWT(true);
  334.                 policy.setValidazioneJWTWarningOnly(true);
  335.                 break;
  336.             case DISABILITATO:
  337.                 policy.setValidazioneJWT(false);
  338.                 policy.setValidazioneJWTWarningOnly(false);
  339.                 break;
  340.             }
  341.         }
  342.        
  343.         boolean introspectionEnabledDaPolicy = isIntrospectionEnabled(multiProperties);
  344.         if(introspectionEnabledDaPolicy &&
  345.             gestioneToken.getIntrospection()!=null) {
  346.             switch (gestioneToken.getIntrospection()) {
  347.             case ABILITATO:
  348.                 policy.setIntrospection(true);
  349.                 policy.setIntrospectionWarningOnly(false);
  350.                 break;
  351.             case WARNING_ONLY:
  352.                 policy.setIntrospection(true);
  353.                 policy.setIntrospectionWarningOnly(true);
  354.                 break;
  355.             case DISABILITATO:
  356.                 policy.setIntrospection(false);
  357.                 policy.setIntrospectionWarningOnly(false);
  358.                 break;
  359.             }
  360.         }
  361.        
  362.         boolean userInfoEnabledDaPolicy = isUserInfoEnabled(multiProperties);
  363.         if(userInfoEnabledDaPolicy &&
  364.             gestioneToken.getUserInfo()!=null) {
  365.             switch (gestioneToken.getUserInfo()) {
  366.             case ABILITATO:
  367.                 policy.setUserInfo(true);
  368.                 policy.setUserInfoWarningOnly(false);
  369.                 break;
  370.             case WARNING_ONLY:
  371.                 policy.setUserInfo(true);
  372.                 policy.setUserInfoWarningOnly(true);
  373.                 break;
  374.             case DISABILITATO:
  375.                 policy.setUserInfo(false);
  376.                 policy.setUserInfoWarningOnly(false);
  377.                 break;
  378.             }
  379.         }
  380.        
  381.         boolean forwardEnabledDaPolicy = isTokenForwardEnabled(multiProperties);
  382.         if(forwardEnabledDaPolicy &&
  383.             gestioneToken.getForward()!=null) {
  384.             policy.setForwardToken(org.openspcoop2.core.config.constants.StatoFunzionalita.ABILITATO.equals(gestioneToken.getForward()));
  385.         }
  386.     }
  387.    
  388.    
  389.     public static List<String> getClaimValues(Object value) {
  390.         List<String> lRet = null;
  391.         if(value!=null) {
  392.             if(value instanceof List<?>) {
  393.                 List<?> l = (List<?>) value;
  394.                 return getClaimValues(l);
  395.             }
  396.             else {
  397.                 String sValue = value.toString();
  398.                 List<String> l = new ArrayList<>();
  399.                 l.add(sValue);
  400.                 return l;
  401.             }
  402.         }
  403.         return lRet;
  404.     }
  405.     private static List<String> getClaimValues(List<?> l) {
  406.         List<String> lRet = null;
  407.         if(!l.isEmpty()) {
  408.             List<String> lString = new ArrayList<>();
  409.             for (Object o : l) {
  410.                 if(o!=null) {
  411.                     lString.add(o.toString());
  412.                 }
  413.             }
  414.             if(!lString.isEmpty()) {
  415.                 return lString;
  416.             }
  417.         }
  418.         return lRet;
  419.     }
  420.    
  421.     public static String getClaimValuesAsString(List<String> claimValues) {
  422.         StringBuilder claimValueSB = new StringBuilder();
  423.         if(claimValues==null || claimValues.isEmpty()) {
  424.             return null;
  425.         }
  426.         if(claimValues.size()>1) {
  427.             for (String c : claimValues) {
  428.                 if(claimValueSB.length()>0) {
  429.                     claimValueSB.append(",");
  430.                 }
  431.                 claimValueSB.append(c);
  432.             }
  433.         }
  434.         else {
  435.             claimValueSB.append(claimValues.get(0));
  436.         }
  437.         return claimValueSB.length()>0 ? claimValueSB.toString() : null;
  438.     }
  439.    
  440.     public static String getClaimAsString(Map<String, Serializable> claims, String claim) {
  441.         List<String> l = getClaimAsList(claims, claim);
  442.         if(l==null || l.isEmpty()) {
  443.             return null;
  444.         }
  445.         return TokenUtilities.getClaimValuesAsString(l);
  446.     }
  447.     public static List<String> getClaimAsList(Map<String, Serializable> claims, String claim) {
  448.         List<String> l = null;
  449.         Object o = claims.get(claim);
  450.         if(o==null) {
  451.             return l;
  452.         }
  453.         l = TokenUtilities.getClaimValues(o);
  454.         List<String> lRet = null;
  455.         if(l!=null && l.isEmpty()) {
  456.             return lRet;
  457.         }
  458.         return l;
  459.     }
  460.    
  461.     public static String getFirstClaimAsString(Map<String, Serializable> claims, List<String> names) {
  462.         for (String name : names) {
  463.             String claim = getClaimAsString(claims, name);
  464.             if(claim!=null) {
  465.                 return claim;
  466.             }
  467.         }
  468.         return null;
  469.     }
  470.     public static List<String> getFirstClaimAsList(Map<String, Serializable> claims, List<String> names) {
  471.         List<String> lRet = null;
  472.         for (String name : names) {
  473.             List<String> l = getClaimAsList(claims, name);
  474.             if(l!=null && !l.isEmpty()) {
  475.                 return l;
  476.             }
  477.         }
  478.         return lRet;
  479.     }
  480.    
  481.     public static KeystoreParams getSignedJwtKeystoreParams(GenericProperties gp) throws Exception {
  482.         PolicyNegoziazioneToken policy = TokenUtilities.convertTo(gp);
  483.         return getSignedJwtKeystoreParams(policy);
  484.     }
  485.     public static KeystoreParams getSignedJwtKeystoreParams(PolicyNegoziazioneToken policy) throws TokenException {
  486.    
  487.         if(!policy.isRfc7523x509Grant()) {
  488.             throw new TokenException("La configurazione nella policy "+policy.getName()+" non utilizza la funzionalità SignedJWT (RFC 7523)");
  489.         }
  490.        
  491.         String keystoreType = policy.getJwtSignKeystoreType();
  492.         if(keystoreType==null) {
  493.             throw new TokenException("JWT Signature keystore type undefined");
  494.         }
  495.         String keystoreFile = policy.getJwtSignKeystoreFile();
  496.         if(keystoreFile==null) {
  497.             throw new TokenException("JWT Signature keystore file undefined");
  498.         }
  499.         String keystorePassword = policy.getJwtSignKeystorePassword();
  500.         if(keystorePassword==null &&
  501.                 !SecurityConstants.KEYSTORE_TYPE_JWK_VALUE.equalsIgnoreCase(keystoreType) &&
  502.                 !SecurityConstants.KEYSTORE_TYPE_KEY_PAIR_VALUE.equalsIgnoreCase(keystoreType) &&
  503.                 !SecurityConstants.KEYSTORE_TYPE_PUBLIC_KEY_VALUE.equalsIgnoreCase(keystoreType)) {
  504.             boolean required = true;
  505.             if(KeystoreType.JKS.isType(keystoreType)) {
  506.                 required = DBUtils.isKeystoreJksPasswordRequired();
  507.             }
  508.             else if(KeystoreType.PKCS12.isType(keystoreType)) {
  509.                 required = DBUtils.isKeystorePkcs12PasswordRequired();
  510.             }
  511.             if(required) {
  512.                 throw new TokenException("JWT Signature keystore password undefined");
  513.             }
  514.         }
  515.         String keyAlias = policy.getJwtSignKeyAlias();
  516.         if(keyAlias==null &&
  517.             !SecurityConstants.KEYSTORE_TYPE_KEY_PAIR_VALUE.equalsIgnoreCase(keystoreType) &&
  518.             !SecurityConstants.KEYSTORE_TYPE_PUBLIC_KEY_VALUE.equalsIgnoreCase(keystoreType)) {
  519.             throw new TokenException("JWT Signature key alias undefined");
  520.         }
  521.        
  522.         String keyPassword = policy.getJwtSignKeyPassword();
  523.         if(keyPassword==null &&
  524.                 !SecurityConstants.KEYSTORE_TYPE_JWK_VALUE.equalsIgnoreCase(keystoreType) &&
  525.                 !SecurityConstants.KEYSTORE_TYPE_KEY_PAIR_VALUE.equalsIgnoreCase(keystoreType) &&
  526.                 !SecurityConstants.KEYSTORE_TYPE_PUBLIC_KEY_VALUE.equalsIgnoreCase(keystoreType)) {
  527.             boolean required = true;
  528.             if(KeystoreType.JKS.isType(keystoreType)) {
  529.                 required = DBUtils.isKeystoreJksKeyPasswordRequired();
  530.             }
  531.             else if(KeystoreType.PKCS12.isType(keystoreType)) {
  532.                 required = DBUtils.isKeystorePkcs12KeyPasswordRequired();
  533.             }
  534.             if(required) {
  535.                 throw new TokenException("JWT Signature key password undefined");
  536.             }
  537.         }
  538.        
  539.         String keystoreByokPolicy = policy.getJwtSignKeystoreByokPolicy();
  540.        
  541.         KeystoreParams keystoreParams = new KeystoreParams();
  542.         keystoreParams.setPath(keystoreFile);
  543.         keystoreParams.setType(keystoreType);
  544.         keystoreParams.setPassword(keystorePassword);
  545.         keystoreParams.setKeyAlias(keyAlias);
  546.         keystoreParams.setKeyPassword(keyPassword);
  547.         keystoreParams.setByokPolicy(keystoreByokPolicy);
  548.        
  549.         fillKeyPairParamters(keystoreParams, keystoreType, policy);
  550.        
  551.         return keystoreParams;
  552.        
  553.     }
  554.    
  555.     private static void fillKeyPairParamters(KeystoreParams keystoreParams, String keystoreType, PolicyNegoziazioneToken policy) throws TokenException {
  556.         if(SecurityConstants.KEYSTORE_TYPE_KEY_PAIR_VALUE.equalsIgnoreCase(keystoreType)) {
  557.             String keystorePublicKeyFile = policy.getJwtSignKeystoreFilePublicKey();
  558.             if(keystorePublicKeyFile==null) {
  559.                 throw new TokenException("JWT Signature public key file undefined");
  560.             }
  561.             keystoreParams.setKeyPairPublicKeyPath(keystorePublicKeyFile);
  562.         }
  563.        
  564.         if(SecurityConstants.KEYSTORE_TYPE_KEY_PAIR_VALUE.equalsIgnoreCase(keystoreType)
  565.                 ||
  566.             SecurityConstants.KEYSTORE_TYPE_PUBLIC_KEY_VALUE.equalsIgnoreCase(keystoreType)) {
  567.             String keyPairAlgorithm = policy.getJwtSignKeyPairAlgorithm();
  568.             if(keyPairAlgorithm==null) {
  569.                 throw new TokenException("JWT Signature key pair algorithm undefined");
  570.             }
  571.             keystoreParams.setKeyPairAlgorithm(keyPairAlgorithm);
  572.         }
  573.     }
  574.    
  575.     public static PolicyNegoziazioneToken convertTo(GenericProperties gp) throws Exception {
  576.        
  577.         PolicyNegoziazioneToken policy = new PolicyNegoziazioneToken();
  578.         policy.setName(gp.getNome());
  579.         policy.setDescrizione(gp.getDescrizione());
  580.        
  581.         HashMap<String, String> properties = new HashMap<>();
  582.         for (Property pConfig : gp.getPropertyList()) {
  583.             properties.put(pConfig.getNome(), pConfig.getValore());
  584.         }
  585.         Map<String, Properties> multiProperties = DBPropertiesUtils.toMultiMap(properties);
  586.         policy.setProperties(multiProperties);
  587.        
  588.         return policy;

  589.     }
  590.    
  591.     public static void checkClaims(String oggetto, Properties claims, String elemento, List<String> denyClaims, boolean checkSpazi) throws ProviderValidationException {
  592.         if(claims!=null && !claims.isEmpty()) {
  593.             for (Object oClaim : claims.keySet()) {
  594.                 if(oClaim instanceof String) {
  595.                     String claim = (String) oClaim;
  596.                     String value = claims.getProperty(claim);
  597.                     validateClaims(oggetto, elemento, denyClaims, checkSpazi, claim, value);
  598.                 }
  599.             }
  600.         }
  601.     }
  602.     private static void validateClaims(String oggetto, String elemento, List<String> denyClaims, boolean checkSpazi,
  603.             String claim, String value) throws ProviderValidationException {
  604.         String indicato = "indicato nel campo '"+elemento+"'";
  605.         if(denyClaims.contains(claim) || denyClaims.contains(claim.toLowerCase())) {
  606.             throw new ProviderValidationException(oggetto+" '"+claim+"', "+indicato+", non può essere configurato");
  607.         }
  608.         if(value==null || StringUtils.isEmpty(value)) {
  609.             throw new ProviderValidationException(oggetto+" '"+claim+"', "+indicato+", non è valorizzato");
  610.         }
  611.         if(checkSpazi) {
  612.             if(value.contains(" ")) {
  613.                 throw new ProviderValidationException("Non indicare spazi nel "+oggetto+" '"+claim+"', "+indicato+"");
  614.             }
  615.         }
  616.         else {
  617.             if(value.startsWith(" ")) {
  618.                 throw new ProviderValidationException("Il valore del "+oggetto+" '"+claim+"', "+indicato+", non deve iniziare con uno spazio");
  619.             }
  620.             if(value.endsWith(" ")) {
  621.                 throw new ProviderValidationException("Il valore del "+oggetto+" '"+claim+"', "+indicato+", non deve terminare con uno spazio");
  622.             }
  623.         }
  624.     }
  625.    
  626.     public static String deleteSignature(String token) {
  627.         // verifico che sia un JWT
  628.         if(token.contains(".")) {
  629.             String [] tmp = token.split("\\.");
  630.             if(tmp!=null && tmp.length==3 &&
  631.                 tmp[2]!=null) {
  632.                 if(tmp[0]!=null && tmp[1]!=null) {
  633.                     return tmp[0]+"."+tmp[1]+".==SIGNATURE==";
  634.                 }
  635.                 else if(tmp[0]==null && tmp[1]!=null) {
  636.                     return "."+tmp[1]+".==SIGNATURE==";
  637.                 }
  638.                 else if(tmp[0]!=null && tmp[1]==null) {
  639.                     return tmp[0]+"..==SIGNATURE==";
  640.                 }
  641.                 else {
  642.                     return "..==SIGNATURE==";
  643.                 }
  644.             }
  645.         }
  646.         return token;
  647.     }
  648.     public static Map<String, Serializable> replaceTokenInMapByValue(Map<String, Serializable> claims, String valueOriginale, String newValue) {
  649.        
  650.         Map<String, Serializable> newMap = new HashMap<>();
  651.        
  652.         if(claims!=null && !claims.isEmpty()) {
  653.             for (Map.Entry<String,Serializable> entry : claims.entrySet()) {
  654.                 String key = entry.getKey();
  655.                 Serializable o = claims.get(key);
  656.                 if(o instanceof String && valueOriginale.equals(o)) {
  657.                     newMap.put(key, newValue);
  658.                 }
  659.                 else {
  660.                     newMap.put(key, o);
  661.                 }
  662.             }
  663.         }
  664.        
  665.         return newMap;
  666.     }
  667.    
  668.     private static final String EXTERNAL_RESOURCE_UNDEFINED = "External resource undefined";
  669.     private static final String RECUPERO_PLUGIN_REGISTRATI_FALLITO_PREFIX = "Recupero plugin registrati fallito: ";
  670.    
  671.     public static List<String> getTokenPluginValues(ExternalResources externalResources, TipoPlugin tipoPlugin) throws ProviderException{
  672.         return getTokenPluginList(externalResources, tipoPlugin, true);
  673.     }
  674.     public static List<String> getTokenPluginLabels(ExternalResources externalResources, TipoPlugin tipoPlugin) throws ProviderException{
  675.         return getTokenPluginList(externalResources, tipoPlugin, false);
  676.     }
  677.     private static List<String> getTokenPluginList(ExternalResources externalResources, TipoPlugin tipoPlugin, boolean value) throws ProviderException{
  678.         if(externalResources==null) {
  679.             throw new ProviderException(EXTERNAL_RESOURCE_UNDEFINED);
  680.         }
  681.         ISearch ricerca = new Search(true);
  682.         ricerca.addFilter(Liste.CONFIGURAZIONE_PLUGINS_CLASSI,  Filtri.FILTRO_TIPO_PLUGIN_CLASSI, tipoPlugin.toString());
  683.         List<Plugin> list = null;
  684.         try {
  685.             list = PluginsDriverUtils.pluginsClassiList(ricerca, externalResources.getConnection(), externalResources.getLog(), externalResources.getTipoDB());
  686.         }catch(Exception t) {
  687.             throw new ProviderException(RECUPERO_PLUGIN_REGISTRATI_FALLITO_PREFIX+t.getMessage(),t);
  688.         }
  689.         List<String> values = new ArrayList<>();
  690.         values.add(CostantiConfigurazione.POLICY_ID_NON_DEFINITA);
  691.         if(list!=null && !list.isEmpty()) {
  692.             for (Plugin plugin : list) {
  693.                 if(plugin.isStato()) {
  694.                     if(value) {
  695.                         values.add(plugin.getTipo());
  696.                     }
  697.                     else {
  698.                         values.add(plugin.getLabel());
  699.                     }
  700.                 }
  701.             }
  702.         }
  703.        
  704.         return values;
  705.     }
  706.    
  707.     public static String dynamicUpdateTokenPluginChoice(ExternalResources externalResources, TipoPlugin tipoPlugin, Item item, String actualValue) {
  708.         try {
  709.             if(externalResources==null) {
  710.                 throw new ProviderException(EXTERNAL_RESOURCE_UNDEFINED);
  711.             }
  712.             ISearch ricerca = new Search(true);
  713.             ricerca.addFilter(Liste.CONFIGURAZIONE_PLUGINS_CLASSI,  Filtri.FILTRO_TIPO_PLUGIN_CLASSI, tipoPlugin.toString());
  714.             List<Plugin> listTmp = pluginsClassiList(ricerca, externalResources);
  715.             List<Plugin> list = null;
  716.             if(listTmp!=null && !listTmp.isEmpty()) {
  717.                 list = new ArrayList<>();
  718.                 for (Plugin p : listTmp) {
  719.                     if(p.isStato()) {  
  720.                         list.add(p);
  721.                     }
  722.                 }
  723.             }
  724.             if(list==null || list.isEmpty()) {
  725.                 item.setType(ItemType.HIDDEN);
  726.                 item.setValue(CostantiConfigurazione.POLICY_ID_NON_DEFINITA);
  727.                 return CostantiConfigurazione.POLICY_ID_NON_DEFINITA;
  728.             }
  729.             else {
  730.                 item.setType(ItemType.SELECT);
  731.                 item.setValue(actualValue);
  732.                 return actualValue;
  733.             }
  734.         }catch(Exception t) {
  735.             // ignore
  736.             return actualValue;
  737.         }
  738.     }
  739.     private static List<Plugin> pluginsClassiList(ISearch ricerca, ExternalResources externalResources) throws ProviderException{
  740.         try {
  741.             return PluginsDriverUtils.pluginsClassiList(ricerca, externalResources.getConnection(), externalResources.getLog(), externalResources.getTipoDB());
  742.         }catch(Exception t) {
  743.             throw new ProviderException(RECUPERO_PLUGIN_REGISTRATI_FALLITO_PREFIX+t.getMessage(),t);
  744.         }
  745.     }
  746.     public static String dynamicUpdateTokenPluginClassName(ExternalResources externalResources, TipoPlugin tipoPlugin,
  747.             List<?> items, Map<String, String> mapNameValue, Item item,
  748.             String idChoice, String actualValue) {
  749.         try {
  750.             if(externalResources==null) {
  751.                 throw new ProviderException(EXTERNAL_RESOURCE_UNDEFINED);
  752.             }
  753.            
  754.             List<Plugin> list = fillListTipoPlugin(externalResources, tipoPlugin);
  755.            
  756.             return dynamicUpdateTokenPluginClassName(list,
  757.                     items, mapNameValue, item,
  758.                     idChoice, actualValue);
  759.            
  760.         }catch(Exception t) {
  761.             // ignore
  762.         }
  763.         return actualValue;
  764.     }
  765.     private static List<Plugin> fillListTipoPlugin(ExternalResources externalResources, TipoPlugin tipoPlugin) throws ProviderException {
  766.         ISearch ricerca = new Search(true);
  767.         ricerca.addFilter(Liste.CONFIGURAZIONE_PLUGINS_CLASSI,  Filtri.FILTRO_TIPO_PLUGIN_CLASSI, tipoPlugin.toString());
  768.         List<Plugin> listTmp = pluginsClassiList(ricerca, externalResources);
  769.         List<Plugin> list = null;
  770.         if(listTmp!=null && !listTmp.isEmpty()) {
  771.             list = new ArrayList<>();
  772.             for (Plugin p : listTmp) {
  773.                 if(p.isStato()) {  
  774.                     list.add(p);
  775.                 }
  776.             }
  777.         }
  778.         return list;
  779.     }
  780.     private static String dynamicUpdateTokenPluginClassName(List<Plugin> list,
  781.             List<?> items, Map<String, String> mapNameValue, Item item,
  782.             String idChoice, String actualValue) {
  783.         if(list!=null && !list.isEmpty()) {
  784.             item.setRequired(false);
  785.            
  786.             if(actualValue==null) {
  787.                 item.setType(ItemType.HIDDEN);
  788.                 item.setValue(CostantiConfigurazione.POLICY_ID_NON_DEFINITA);
  789.                 return CostantiConfigurazione.POLICY_ID_NON_DEFINITA;
  790.             }
  791.             else {
  792.                 String pluginSelected = AbstractSecurityProvider.readValue(idChoice, items, mapNameValue);
  793.                 if(pluginSelected!=null && !StringUtils.isEmpty(pluginSelected) && !CostantiConfigurazione.POLICY_ID_NON_DEFINITA.equals(pluginSelected)) {
  794.                     item.setType(ItemType.HIDDEN);
  795.                     item.setValue(CostantiConfigurazione.POLICY_ID_NON_DEFINITA);
  796.                     return CostantiConfigurazione.POLICY_ID_NON_DEFINITA;
  797.                 }
  798.             }
  799.            
  800.             if(StringUtils.isNotEmpty(actualValue) && !CostantiConfigurazione.POLICY_ID_NON_DEFINITA.equals(actualValue)) {
  801.                 item.setType(ItemType.TEXT);
  802.             }
  803.         }
  804.         else {
  805.             item.setType(ItemType.TEXT);
  806.             item.setRequired(true);
  807.         }
  808.         return actualValue;
  809.     }
  810.    
  811.    
  812.    
  813.    
  814.     public static HashMap<String, Serializable> toHashMapSerializable(Map<String, Serializable> map) {
  815.         HashMap<String, Serializable> mapNull = null;
  816.         if(map instanceof HashMap) {
  817.             return (HashMap<String, Serializable>) map;
  818.         }
  819.         else if(map!=null) {
  820.             HashMap<String, Serializable> sMap = new HashMap<>();
  821.             for (Map.Entry<String,Serializable> entry : map.entrySet()) {
  822.                 sMap.put(entry.getKey(), entry.getValue());
  823.             }
  824.         }
  825.         return mapNull;
  826.     }
  827.    
  828.     public static String readJtiFromInformazioniToken(Context context) {
  829.         Object oInformazioniTokenNormalizzate = null;
  830.         if(context!=null) {
  831.             oInformazioniTokenNormalizzate = context.getObject(org.openspcoop2.pdd.core.token.Costanti.PDD_CONTEXT_TOKEN_INFORMAZIONI_NORMALIZZATE);
  832.         }
  833.         InformazioniToken informazioniTokenNormalizzate = null;
  834.         String jtiClaimReceived = null;
  835.         if(oInformazioniTokenNormalizzate!=null) {
  836.             informazioniTokenNormalizzate = (InformazioniToken) oInformazioniTokenNormalizzate;
  837.             jtiClaimReceived = informazioniTokenNormalizzate.getJti();
  838.         }
  839.         return jtiClaimReceived;
  840.     }
  841.    
  842.    
  843.    
  844.    
  845.     public static Map<String, Object> buildDynamicMap(Busta busta,
  846.             RequestInfo requestInfo, Context pddContext, Logger log) {
  847.         return DynamicMapBuilderUtils.buildDynamicMap(busta, requestInfo, pddContext, log);
  848.     }
  849.     public static String convertDynamicPropertyValue(String v, String nome, Map<String, Object> dynamicMap, Context context) throws TokenException {
  850.         return DynamicMapBuilderUtils.convertDynamicPropertyValue(v, nome, dynamicMap, context);
  851.     }
  852.    
  853.    
  854.    
  855.    
  856.    
  857.    
  858.    
  859.    
  860.    
  861.    
  862.     public static void injectJOSEConfig(Properties p, AbstractPolicyToken policyToken, DynamicDiscovery dynamicDiscovery,
  863.             Busta busta, IDSoggetto idDominio, IDServizio idServizio,
  864.             Context context, Logger log,
  865.             RequestInfo requestInfo, IState state, boolean delegata) throws TokenException {
  866.        
  867.         Map<String, Object> dynamicMap = TokenUtilities.buildDynamicMap(busta, requestInfo, context, log);
  868.        
  869.         if(policyToken instanceof PolicyGestioneToken) {
  870.             injectJOSEConfigDynamicDiscovery(p, (PolicyGestioneToken)policyToken, dynamicDiscovery,
  871.                     dynamicMap, context);
  872.         }
  873.         injectJOSEConfigKeystore(p,  
  874.                 dynamicMap, context);
  875.         injectJOSEConfigSsl(p, policyToken,
  876.                 dynamicMap, context);
  877.         injectJOSEConfigTimeout(p, policyToken,
  878.                 dynamicMap, context);
  879.         injectJOSEConfigProxy(p, policyToken,
  880.                 dynamicMap, context);
  881.         injectJOSEConfigForwardProxy(p, policyToken,
  882.                 idDominio, idServizio,
  883.                 requestInfo, state, delegata);
  884.     }
  885.     private static void injectJOSEConfigDynamicDiscovery(Properties p, PolicyGestioneToken policyGestioneToken, DynamicDiscovery dynamicDiscovery,
  886.             Map<String, Object> dynamicMap, Context context) throws TokenException {
  887.         if(policyGestioneToken.isDynamicDiscovery()) {
  888.             GestoreTokenValidazioneUtilities.check(dynamicDiscovery);
  889.             String endpoint = dynamicDiscovery.getJwksUri();
  890.             endpoint = convertDynamicPropertyValue(endpoint, "endpoint", dynamicMap, context);
  891.             if(endpoint==null || StringUtils.isEmpty(endpoint)) {
  892.                 throw new TokenException("DynamicDiscovery.jwkUri undefined");
  893.             }
  894.             p.put(SecurityConstants.JOSE_KEYSTORE_FILE, endpoint);
  895.         }
  896.     }
  897.     private static void injectJOSEConfigKeystore(Properties p,
  898.             Map<String, Object> dynamicMap, Context context) throws TokenException {
  899.        
  900.         String file = p.getProperty(SecurityConstants.JOSE_KEYSTORE_FILE);
  901.         if(file!=null && !"".equals(file)) {
  902.             file = convertDynamicPropertyValue(file, "file", dynamicMap, context);
  903.             p.put(SecurityConstants.JOSE_KEYSTORE_FILE, file);
  904.         }
  905.        
  906.         String alias = p.getProperty(SecurityConstants.JOSE_KEYSTORE_KEY_ALIAS);
  907.         if(alias!=null && !"".equals(alias)) {
  908.             alias = convertDynamicPropertyValue(alias, "alias", dynamicMap, context);
  909.             p.put(SecurityConstants.JOSE_KEYSTORE_KEY_ALIAS, alias);
  910.         }
  911.        
  912.         String pwd = p.getProperty(SecurityConstants.JOSE_KEYSTORE_PSWD);
  913.         if(pwd!=null && !"".equals(pwd)) {
  914.             pwd = convertDynamicPropertyValue(pwd, "pwd", dynamicMap, context);
  915.             p.put(SecurityConstants.JOSE_KEYSTORE_PSWD, pwd);
  916.         }
  917.        
  918.         String type = p.getProperty(SecurityConstants.JOSE_KEYSTORE_TYPE);
  919.         if(type!=null && !"".equals(type)) {
  920.             type = convertDynamicPropertyValue(type, "type", dynamicMap, context);
  921.             p.put(SecurityConstants.JOSE_KEYSTORE_TYPE, type);
  922.         }
  923.        
  924.     }
  925.     public static void injectJOSEConfigSsl(Properties p, AbstractPolicyToken policyToken,
  926.             Map<String, Object> dynamicMap, Context context) throws TokenException {
  927.         boolean https = false;
  928.         if(policyToken instanceof PolicyGestioneToken) {
  929.             https = ((PolicyGestioneToken)policyToken).isEndpointHttps();
  930.         }
  931.         else if(policyToken instanceof PolicyAttributeAuthority) {
  932.             try {
  933.                 https = ((PolicyAttributeAuthority)policyToken).isEndpointHttps();
  934.             }catch(Exception e) {
  935.                 throw new TokenException(e.getMessage(),e);
  936.             }
  937.         }
  938.         if(https) {
  939.             Properties sslConfig = policyToken.getProperties().get(Costanti.POLICY_ENDPOINT_SSL_CONFIG);
  940.             if(sslConfig!=null) {
  941.                 injectJOSEConfigSsl(p, sslConfig,
  942.                         dynamicMap, context);
  943.             }
  944.         }
  945.     }
  946.     private static void injectJOSEConfigSsl(Properties p, Properties sslConfig,
  947.             Map<String, Object> dynamicMap, Context context) throws TokenException {
  948.         String trustAll = sslConfig.getProperty(CostantiConnettori.CONNETTORE_HTTPS_TRUST_ALL_CERTS);
  949.         if(trustAll!=null && StringUtils.isNotEmpty(trustAll) && "true".equalsIgnoreCase(trustAll)) {
  950.             p.put(JOSECostanti.ID_TRUSTSTORE_SSL_KEYSTORE_TRUSTALL, trustAll);
  951.         }
  952.         else {
  953.             injectJOSEConfigSslTrustStore(p, sslConfig,
  954.                     dynamicMap, context);
  955.         }
  956.        
  957.         String hostnameVerifier = sslConfig.getProperty(CostantiConnettori.CONNETTORE_HTTPS_HOSTNAME_VERIFIER);
  958.         if(hostnameVerifier!=null && StringUtils.isNotEmpty(hostnameVerifier)) {
  959.             p.put(JOSECostanti.ID_TRUSTSTORE_SSL_KEYSTORE_HOSTNAME_VERIFIER, hostnameVerifier);
  960.         }
  961.     }
  962.     private static void injectJOSEConfigSslTrustStore(Properties p, Properties sslConfig,
  963.             Map<String, Object> dynamicMap, Context context) throws TokenException {
  964.         String trustLocation = sslConfig.getProperty(CostantiConnettori.CONNETTORE_HTTPS_TRUST_STORE_LOCATION);
  965.         if(trustLocation!=null && StringUtils.isNotEmpty(trustLocation)) {
  966.             trustLocation = convertDynamicPropertyValue(trustLocation, "trustLocation", dynamicMap, context);
  967.             p.put(JOSECostanti.ID_TRUSTSTORE_SSL_KEYSTORE_FILE, trustLocation);
  968.            
  969.             String trustType = sslConfig.getProperty(CostantiConnettori.CONNETTORE_HTTPS_TRUST_STORE_TYPE);
  970.             if(trustType!=null && StringUtils.isNotEmpty(trustType)) {
  971.                 trustType = convertDynamicPropertyValue(trustType, "trustType", dynamicMap, context);
  972.                 p.put(JOSECostanti.ID_TRUSTSTORE_SSL_KEYSTORE_TYPE, trustType);
  973.             }
  974.            
  975.             String trustPassword = sslConfig.getProperty(CostantiConnettori.CONNETTORE_HTTPS_TRUST_STORE_PASSWORD);
  976.             if(trustPassword!=null && StringUtils.isNotEmpty(trustPassword)) {
  977.                 trustPassword = convertDynamicPropertyValue(trustPassword, "trustPassword", dynamicMap, context);
  978.                 p.put(JOSECostanti.ID_TRUSTSTORE_SSL_KEYSTORE_PASSWORD, trustPassword);
  979.             }
  980.            
  981.             String trustCrl = sslConfig.getProperty(CostantiConnettori.CONNETTORE_HTTPS_TRUST_STORE_CRLS);
  982.             if(trustCrl!=null && StringUtils.isNotEmpty(trustCrl)) {
  983.                 trustCrl = convertDynamicPropertyValue(trustCrl, "trustCrl", dynamicMap, context);
  984.                 p.put(JOSECostanti.ID_TRUSTSTORE_SSL_KEYSTORE_CRL, trustCrl);
  985.             }
  986.         }
  987.     }
  988.     private static void injectJOSEConfigTimeout(Properties p, AbstractPolicyToken policyToken,
  989.             Map<String, Object> dynamicMap, Context context) throws TokenException {
  990.         Properties endpointConfig = policyToken.getProperties().get(Costanti.POLICY_ENDPOINT_CONFIG);
  991.         if(endpointConfig!=null && endpointConfig.containsKey(CostantiConnettori.CONNETTORE_CONNECTION_TIMEOUT)) {
  992.             String connectionTimeout = endpointConfig.getProperty(CostantiConnettori.CONNETTORE_CONNECTION_TIMEOUT);
  993.             if(connectionTimeout!=null && StringUtils.isNotEmpty(connectionTimeout)) {
  994.                 connectionTimeout = convertDynamicPropertyValue(connectionTimeout, "connectionTimeout", dynamicMap, context);
  995.             }
  996.            
  997.             String readTimeout = endpointConfig.getProperty(CostantiConnettori.CONNETTORE_READ_CONNECTION_TIMEOUT);
  998.             if(readTimeout!=null && StringUtils.isNotEmpty(readTimeout)) {
  999.                 readTimeout = convertDynamicPropertyValue(readTimeout, "readTimeout", dynamicMap, context);
  1000.             }
  1001.        
  1002.             if(connectionTimeout!=null) {
  1003.                 p.put(JOSECostanti.ID_TRUSTSTORE_SSL_KEYSTORE_CONNECTION_TIMEOUT, connectionTimeout);
  1004.             }
  1005.             if(readTimeout!=null) {
  1006.                 p.put(JOSECostanti.ID_TRUSTSTORE_SSL_KEYSTORE_READ_TIMEOUT, readTimeout);
  1007.             }
  1008.         }
  1009.     }
  1010.     private static void injectJOSEConfigProxy(Properties p, AbstractPolicyToken policyToken,
  1011.             Map<String, Object> dynamicMap, Context context) throws TokenException {
  1012.         Properties endpointConfig = policyToken.getProperties().get(Costanti.POLICY_ENDPOINT_CONFIG);
  1013.         if(endpointConfig!=null && endpointConfig.containsKey(CostantiConnettori.CONNETTORE_HTTP_PROXY_HOSTNAME)) {
  1014.             String hostProxy = endpointConfig.getProperty(CostantiConnettori.CONNETTORE_HTTP_PROXY_HOSTNAME);
  1015.             if(hostProxy!=null && StringUtils.isNotEmpty(hostProxy)) {
  1016.                 hostProxy = convertDynamicPropertyValue(hostProxy, "hostProxy", dynamicMap, context);
  1017.             }
  1018.            
  1019.             String portProxy = endpointConfig.getProperty(CostantiConnettori.CONNETTORE_HTTP_PROXY_PORT);
  1020.             if(portProxy!=null && StringUtils.isNotEmpty(portProxy)) {
  1021.                 portProxy = convertDynamicPropertyValue(portProxy, "portProxy", dynamicMap, context);
  1022.             }
  1023.        
  1024.             if(hostProxy!=null) {
  1025.                 p.put(JOSECostanti.ID_PROXY_HOSTNAME, hostProxy);
  1026.             }
  1027.             if(portProxy!=null) {
  1028.                 p.put(JOSECostanti.ID_PROXY_PORT, portProxy);
  1029.             }
  1030.            
  1031.             injectJOSEConfigProxyCredentials(p, endpointConfig,
  1032.                     dynamicMap, context);
  1033.         }
  1034.     }
  1035.     private static void injectJOSEConfigProxyCredentials(Properties p, Properties endpointConfig,
  1036.             Map<String, Object> dynamicMap, Context context) throws TokenException {
  1037.         String usernameProxy = endpointConfig.getProperty(CostantiConnettori.CONNETTORE_HTTP_PROXY_USERNAME);
  1038.         String passwordProxy = endpointConfig.getProperty(CostantiConnettori.CONNETTORE_HTTP_PROXY_PASSWORD);
  1039.         if(usernameProxy!=null && StringUtils.isNotEmpty(usernameProxy)) {
  1040.             usernameProxy = convertDynamicPropertyValue(usernameProxy, "usernameProxy", dynamicMap, context);
  1041.             p.put(JOSECostanti.ID_PROXY_USERNAME, usernameProxy);
  1042.            
  1043.             if(passwordProxy!=null && StringUtils.isNotEmpty(passwordProxy)) {
  1044.                 passwordProxy = convertDynamicPropertyValue(passwordProxy, "passwordProxy", dynamicMap, context);
  1045.             }
  1046.             if(passwordProxy!=null) {
  1047.                 p.put(JOSECostanti.ID_PROXY_PASSWORD, passwordProxy);
  1048.             }
  1049.         }
  1050.     }
  1051.     private static void injectJOSEConfigForwardProxy(Properties p, AbstractPolicyToken policyToken,
  1052.             IDSoggetto idDominio, IDServizio idServizio,
  1053.             RequestInfo requestInfo, IState state, boolean delegata) throws TokenException {

  1054.         ForwardProxy forwardProxy = getForwardProxy(policyToken,
  1055.                 requestInfo, state, delegata,
  1056.                 idDominio, idServizio);
  1057.         if(forwardProxy!=null && forwardProxy.isEnabled() && forwardProxy.getConfigToken()!=null) {
  1058.             boolean enabled = false;
  1059.             if(policyToken instanceof PolicyGestioneToken) {
  1060.                 enabled = forwardProxy.getConfigToken().isTokenJwtValidationEnabled();
  1061.             }
  1062.             else if(policyToken instanceof PolicyAttributeAuthority) {
  1063.                 enabled = forwardProxy.getConfigToken().isAttributeAuthorityResponseJwtValidationEnabled();
  1064.             }
  1065.             if(enabled) {
  1066.                 p.put(JOSECostanti.ID_FORWARD_PROXY_ENDPOINT, forwardProxy.getUrl());
  1067.                 if(forwardProxy.getConfig()!=null) {
  1068.                     if(forwardProxy.getConfig().getHeader()!=null) {
  1069.                         p.put(JOSECostanti.ID_FORWARD_PROXY_HEADER, forwardProxy.getConfig().getHeader());
  1070.                         p.put(JOSECostanti.ID_FORWARD_PROXY_HEADER_BASE64, forwardProxy.getConfig().isHeaderBase64()+"");
  1071.                     }
  1072.                     else if(forwardProxy.getConfig().getQuery()!=null) {
  1073.                         p.put(JOSECostanti.ID_FORWARD_PROXY_QUERY, forwardProxy.getConfig().getQuery());
  1074.                         p.put(JOSECostanti.ID_FORWARD_PROXY_QUERY_BASE64, forwardProxy.getConfig().isQueryBase64()+"");
  1075.                     }
  1076.                 }
  1077.             }
  1078.         }
  1079.     }
  1080.    
  1081.    
  1082.    
  1083.    
  1084.     public static ForwardProxy getForwardProxy(AbstractPolicyToken policyToken,
  1085.             RequestInfo requestInfo, IState state, boolean delegata,
  1086.             IDSoggetto idDominio, IDServizio idServizio) throws TokenException{
  1087.         ForwardProxy forwardProxy = null;
  1088.         ConfigurazionePdDManager configurazionePdDManager = ConfigurazionePdDManager.getInstance(state);
  1089.         if(configurazionePdDManager.isForwardProxyEnabled(requestInfo)) {
  1090.             try {
  1091.                 IDGenericProperties policy = new IDGenericProperties();
  1092.                 policy.setTipologia(CostantiConfigurazione.GENERIC_PROPERTIES_TOKEN_TIPOLOGIA_VALIDATION);
  1093.                 policy.setNome(policyToken.getName());
  1094.                 if(delegata) {
  1095.                     forwardProxy = configurazionePdDManager.getForwardProxyConfigFruizione(idDominio, idServizio, policy, requestInfo);
  1096.                 }
  1097.                 else {
  1098.                     forwardProxy = configurazionePdDManager.getForwardProxyConfigErogazione(idDominio, idServizio, policy, requestInfo);
  1099.                 }
  1100.             }catch(Exception e) {
  1101.                 throw new TokenException(GestoreToken.getMessageErroreGovWayProxy(e),e);
  1102.             }
  1103.         }
  1104.         return forwardProxy;
  1105.     }
  1106.    
  1107.    
  1108.    
  1109.     public static void injectSameKeystoreForHttpsClient(Properties sslConfig, Properties sslClientConfig) {
  1110.         if(!sslClientConfig.containsKey(CostantiConnettori.CONNETTORE_HTTPS_KEY_STORE_LOCATION) && !sslClientConfig.containsKey(CostantiConnettori.CONNETTORE_HTTPS_KEY_STORE_PASSWORD)) {
  1111.             // modalita usa valori del truststore
  1112.             String trustStoreLocation = sslConfig.getProperty(CostantiConnettori.CONNETTORE_HTTPS_TRUST_STORE_LOCATION);
  1113.             String trustStorePassword = sslConfig.getProperty(CostantiConnettori.CONNETTORE_HTTPS_TRUST_STORE_PASSWORD);
  1114.             if(trustStoreLocation!=null) {
  1115.                 sslClientConfig.put(CostantiConnettori.CONNETTORE_HTTPS_KEY_STORE_LOCATION, trustStoreLocation);
  1116.                 if(trustStorePassword!=null) {
  1117.                     sslClientConfig.put(CostantiConnettori.CONNETTORE_HTTPS_TRUST_STORE_PASSWORD, trustStorePassword);
  1118.                 }
  1119.             }
  1120.         }
  1121.     }
  1122. }