GestoreTokenNegoziazioneUtilities.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.net.URI;
  23. import java.security.cert.Certificate;
  24. import java.security.cert.X509Certificate;
  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.DBUtils;
  34. import org.openspcoop2.core.config.InvocazioneCredenziali;
  35. import org.openspcoop2.core.config.PortaApplicativa;
  36. import org.openspcoop2.core.config.PortaDelegata;
  37. import org.openspcoop2.core.config.ResponseCachingConfigurazione;
  38. import org.openspcoop2.core.config.constants.CostantiConfigurazione;
  39. import org.openspcoop2.core.config.constants.StatoFunzionalita;
  40. import org.openspcoop2.core.constants.CostantiConnettori;
  41. import org.openspcoop2.core.constants.TipiConnettore;
  42. import org.openspcoop2.core.constants.TipoPdD;
  43. import org.openspcoop2.core.constants.TransferLengthModes;
  44. import org.openspcoop2.core.id.IDGenericProperties;
  45. import org.openspcoop2.core.id.IDServizio;
  46. import org.openspcoop2.core.id.IDSoggetto;
  47. import org.openspcoop2.core.mvc.properties.provider.ProviderException;
  48. import org.openspcoop2.core.mvc.properties.provider.ProviderValidationException;
  49. import org.openspcoop2.message.OpenSPCoop2Message;
  50. import org.openspcoop2.message.OpenSPCoop2MessageFactory;
  51. import org.openspcoop2.message.OpenSPCoop2MessageParseResult;
  52. import org.openspcoop2.message.constants.MessageType;
  53. import org.openspcoop2.pdd.config.ConfigurazionePdDManager;
  54. import org.openspcoop2.pdd.config.ForwardProxy;
  55. import org.openspcoop2.pdd.config.OpenSPCoop2Properties;
  56. import org.openspcoop2.pdd.core.PdDContext;
  57. import org.openspcoop2.pdd.core.connettori.ConnettoreBaseHTTP;
  58. import org.openspcoop2.pdd.core.connettori.ConnettoreHTTP;
  59. import org.openspcoop2.pdd.core.connettori.ConnettoreHTTPS;
  60. import org.openspcoop2.pdd.core.connettori.ConnettoreMsg;
  61. import org.openspcoop2.pdd.core.controllo_traffico.PolicyTimeoutConfig;
  62. import org.openspcoop2.pdd.core.dynamic.DynamicMapBuilderUtils;
  63. import org.openspcoop2.pdd.core.token.parser.Claims;
  64. import org.openspcoop2.pdd.core.token.parser.ClaimsNegoziazione;
  65. import org.openspcoop2.pdd.core.token.parser.INegoziazioneTokenParser;
  66. import org.openspcoop2.protocol.sdk.Busta;
  67. import org.openspcoop2.protocol.sdk.IProtocolFactory;
  68. import org.openspcoop2.protocol.sdk.state.IState;
  69. import org.openspcoop2.protocol.sdk.state.RequestInfo;
  70. import org.openspcoop2.security.SecurityException;
  71. import org.openspcoop2.security.keystore.JWKSetStore;
  72. import org.openspcoop2.security.keystore.KeyPairStore;
  73. import org.openspcoop2.security.keystore.MerlinKeystore;
  74. import org.openspcoop2.security.keystore.cache.GestoreKeystoreCache;
  75. import org.openspcoop2.security.message.constants.SecurityConstants;
  76. import org.openspcoop2.utils.UtilsException;
  77. import org.openspcoop2.utils.certificate.KeyStore;
  78. import org.openspcoop2.utils.certificate.KeystoreParams;
  79. import org.openspcoop2.utils.certificate.KeystoreType;
  80. import org.openspcoop2.utils.certificate.byok.BYOKProvider;
  81. import org.openspcoop2.utils.certificate.byok.BYOKRequestParams;
  82. import org.openspcoop2.utils.date.DateManager;
  83. import org.openspcoop2.utils.id.UniqueIdentifierManager;
  84. import org.openspcoop2.utils.json.JSONUtils;
  85. import org.openspcoop2.utils.properties.PropertiesUtilities;
  86. import org.openspcoop2.utils.regexp.RegExpNotFoundException;
  87. import org.openspcoop2.utils.regexp.RegularExpressionEngine;
  88. import org.openspcoop2.utils.security.JOSESerialization;
  89. import org.openspcoop2.utils.security.JWSOptions;
  90. import org.openspcoop2.utils.security.JsonSignature;
  91. import org.openspcoop2.utils.security.JwtHeaders;
  92. import org.openspcoop2.utils.transport.TransportRequestContext;
  93. import org.openspcoop2.utils.transport.TransportUtils;
  94. import org.openspcoop2.utils.transport.http.HttpConstants;
  95. import org.openspcoop2.utils.transport.http.HttpRequestMethod;
  96. import org.openspcoop2.utils.transport.http.HttpResponse;
  97. import org.slf4j.Logger;

  98. import com.fasterxml.jackson.databind.node.ObjectNode;

  99. /**    
  100.  * GestoreTokenNegoziazioneUtilities
  101.  *
  102.  * @author Poli Andrea (poli@link.it)
  103.  * @author $Author$
  104.  * @version $Rev$, $Date$
  105.  */
  106. public class GestoreTokenNegoziazioneUtilities {
  107.    
  108.     private GestoreTokenNegoziazioneUtilities() {}

  109.     static EsitoNegoziazioneToken endpointTokenEngine(boolean debug, Logger log, PolicyNegoziazioneToken policyNegoziazioneToken,
  110.             Busta busta, RequestInfo requestInfo, TipoPdD tipoPdD,
  111.             NegoziazioneTokenDynamicParameters dynamicParameters, IProtocolFactory<?> protocolFactory,
  112.             IState state, boolean delegata, String idModulo, PortaApplicativa pa, PortaDelegata pd,
  113.             IDSoggetto idDominio, IDServizio idServizio,
  114.             InformazioniNegoziazioneToken previousToken,
  115.             InformazioniNegoziazioneToken_DatiRichiesta datiRichiesta) {
  116.        
  117.         EsitoNegoziazioneToken esito = null;
  118.        
  119.         boolean refreshModeEnabled = false;
  120.         try {
  121.             if(policyNegoziazioneToken.isClientCredentialsGrant()) {
  122.                 refreshModeEnabled = OpenSPCoop2Properties.getInstance().isGestioneRetrieveTokenRefreshTokenGrantTypeClientCredentials();  
  123.                 if(datiRichiesta!=null) {
  124.                     datiRichiesta.setGrantType(Costanti.ID_RETRIEVE_TOKEN_METHOD_CLIENT_CREDENTIAL);
  125.                 }
  126.             }
  127.             else if(policyNegoziazioneToken.isUsernamePasswordGrant()) {
  128.                 refreshModeEnabled = OpenSPCoop2Properties.getInstance().isGestioneRetrieveTokenRefreshTokenGrantTypeUsernamePassword();    
  129.                 if(datiRichiesta!=null) {
  130.                     datiRichiesta.setGrantType(Costanti.ID_RETRIEVE_TOKEN_METHOD_USERNAME_PASSWORD);
  131.                 }
  132.             }
  133.             else if(policyNegoziazioneToken.isRfc7523x509Grant()) {
  134.                 refreshModeEnabled = OpenSPCoop2Properties.getInstance().isGestioneRetrieveTokenRefreshTokenGrantTypeRfc7523x509();
  135.                 if(datiRichiesta!=null) {
  136.                     datiRichiesta.setGrantType(Costanti.ID_RETRIEVE_TOKEN_METHOD_RFC_7523_X509);
  137.                 }
  138.             }
  139.             else if(policyNegoziazioneToken.isRfc7523ClientSecretGrant()) {
  140.                 refreshModeEnabled = OpenSPCoop2Properties.getInstance().isGestioneRetrieveTokenRefreshTokenGrantTypeRfc7523ClientSecret();
  141.                 if(datiRichiesta!=null) {
  142.                     datiRichiesta.setGrantType(Costanti.ID_RETRIEVE_TOKEN_METHOD_RFC_7523_CLIENT_SECRET);
  143.                 }
  144.             }
  145.             else if(policyNegoziazioneToken.isCustomGrant()) {
  146.                 refreshModeEnabled = OpenSPCoop2Properties.getInstance().isGestioneRetrieveTokenRefreshTokenGrantTypeCustom();  
  147.                 if(datiRichiesta!=null) {
  148.                     datiRichiesta.setGrantType(Costanti.ID_RETRIEVE_TOKEN_METHOD_CUSTOM);
  149.                 }
  150.             }
  151.         }catch(Exception t) {
  152.             log.error("Errore durante la comprensione della modalità di refresh: "+t.getMessage(),t);
  153.         }
  154.        
  155.        
  156.         if(refreshModeEnabled && previousToken!=null && previousToken.getRefreshToken()!=null) {
  157.             try {
  158.                 // Verico scadenza refresh
  159.                 if(previousToken.getRefreshExpiresIn()!=null) {
  160.                     Date now = DateManager.getDate();
  161.                    
  162.                     OpenSPCoop2Properties properties = OpenSPCoop2Properties.getInstance();
  163.                     now = updateNowForExpire("RefreshToken", now, previousToken.getRetrievedRefreshTokenIn(), previousToken.getRefreshExpiresIn(),
  164.                             properties.getGestioneRetrieveTokenRefreshTokenBeforeExpirePercent(), properties.getGestioneRetrieveTokenRefreshTokenBeforeExpireSeconds());
  165.                    
  166.                     if(!now.before(previousToken.getRefreshExpiresIn())){
  167.                         // scaduto refresh token
  168.                         log.debug("Refresh token scaduto");
  169.                         refreshModeEnabled = false;
  170.                     }
  171.                 }
  172.                 if(refreshModeEnabled) {
  173.                     esito = invokeEndpointToken(debug, log, policyNegoziazioneToken,
  174.                             busta, requestInfo, tipoPdD,
  175.                             dynamicParameters, protocolFactory,
  176.                             state, delegata, idModulo, pa, pd,
  177.                             idDominio, idServizio,
  178.                             refreshModeEnabled, previousToken,
  179.                             datiRichiesta);
  180.                     if(esito!=null && esito.isValido()) {
  181.                         // ricontrollo tutte le date (l'ho appena preso, dovrebbero essere buone)
  182.                         boolean checkPerRinegoziazione = false;
  183.                         validazioneInformazioniNegoziazioneToken(checkPerRinegoziazione, esito,  
  184.                                 policyNegoziazioneToken.isSaveErrorInCache());
  185.                         if(datiRichiesta!=null) {
  186.                             datiRichiesta.setRefresh(true);
  187.                         }
  188.                         return esito;
  189.                     }
  190.                     if(esito==null || esito.getEccezioneProcessamento()==null) {
  191.                         throw new TokenException("token not refreshed");
  192.                     }
  193.                     else {
  194.                         throw new TokenException("token not refreshed: "+esito.getEccezioneProcessamento());
  195.                     }
  196.                 }
  197.             }catch(Exception t) {
  198.                 String msgError = "Refresh token failed: "+t.getMessage();
  199.                 log.error(msgError);
  200.             }
  201.         }
  202.        
  203.         if(datiRichiesta!=null) {
  204.             datiRichiesta.setRefresh(null);
  205.         }
  206.         return invokeEndpointToken(debug, log, policyNegoziazioneToken,
  207.                 busta, requestInfo, tipoPdD,
  208.                 dynamicParameters, protocolFactory,
  209.                 state, delegata, idModulo, pa, pd,
  210.                 idDominio, idServizio,
  211.                 false, null,
  212.                 datiRichiesta);
  213.        
  214.     }
  215.    
  216.    
  217.     private static EsitoNegoziazioneToken invokeEndpointToken(boolean debug, Logger log, PolicyNegoziazioneToken policyNegoziazioneToken,
  218.             Busta busta, RequestInfo requestInfo, TipoPdD tipoPdD,
  219.             NegoziazioneTokenDynamicParameters dynamicParameters, IProtocolFactory<?> protocolFactory,
  220.             IState state, boolean delegata, String idModulo, PortaApplicativa pa, PortaDelegata pd,
  221.             IDSoggetto idDominio, IDServizio idServizio,
  222.             boolean refreshModeEnabled, InformazioniNegoziazioneToken previousToken,
  223.             InformazioniNegoziazioneToken_DatiRichiesta datiRichiesta) {
  224.    
  225.         EsitoNegoziazioneToken esitoNegoziazioneToken = new EsitoNegoziazioneToken();
  226.        
  227.         esitoNegoziazioneToken.setTokenInternalError();
  228.        
  229.         try{
  230.             String detailsError = null;
  231.             InformazioniNegoziazioneToken informazioniToken = null;
  232.             Exception eProcess = null;
  233.            
  234.             INegoziazioneTokenParser tokenParser = policyNegoziazioneToken.getNegoziazioneTokenParser();
  235.            
  236.             HttpResponse httpResponse = null;
  237.             Integer httpResponseCode = null;
  238.             byte[] risposta = null;
  239.             try {
  240.                 httpResponse = http(debug, log, policyNegoziazioneToken,
  241.                         busta, requestInfo, tipoPdD,
  242.                         dynamicParameters, protocolFactory,
  243.                         state, delegata, idModulo, pa, pd,
  244.                         idDominio, idServizio,
  245.                         refreshModeEnabled, (refreshModeEnabled && previousToken!=null) ? previousToken.getRefreshToken() : null,
  246.                         datiRichiesta);
  247.                 risposta = httpResponse.getContent();
  248.                 httpResponseCode = httpResponse.getResultHTTPOperation();
  249.             }catch(Exception e) {
  250.                 detailsError = "(Errore di Connessione) "+ e.getMessage();
  251.                 eProcess = e;
  252.             }
  253.            
  254.             if(detailsError==null) {
  255.                 try {
  256.                     if(datiRichiesta!=null && datiRichiesta.getPrepareRequest()!=null) {
  257.                         datiRichiesta.setParseResponse(DateManager.getDate());
  258.                     }
  259.                     informazioniToken = new InformazioniNegoziazioneToken(datiRichiesta, httpResponseCode, new String(risposta),tokenParser,previousToken);
  260.                 }catch(Exception e) {
  261.                     detailsError = "Risposta del servizio di negoziazione token non valida: "+e.getMessage();
  262.                     eProcess = e;
  263.                 }
  264.             }
  265.                    
  266.             if(informazioniToken!=null && informazioniToken.isValid()) {
  267.                 esitoNegoziazioneToken.setTokenValido();
  268.                 esitoNegoziazioneToken.setInformazioniNegoziazioneToken(informazioniToken);
  269.                 esitoNegoziazioneToken.setToken(informazioniToken.getAccessToken());
  270.                 esitoNegoziazioneToken.setNoCache(false);
  271.             }
  272.             else {
  273.                 esitoNegoziazioneToken.setTokenValidazioneFallita();
  274.                 esitoNegoziazioneToken.setNoCache(!policyNegoziazioneToken.isSaveErrorInCache());
  275.                 esitoNegoziazioneToken.setEccezioneProcessamento(eProcess);
  276.                 if(detailsError!=null) {
  277.                     esitoNegoziazioneToken.setDetails(detailsError);    
  278.                 }
  279.                 else {
  280.                     esitoNegoziazioneToken.setDetails("AccessToken non recuperabile");  
  281.                 }
  282.                
  283.                 // comunque lo aggiungo per essere consultabile nei casi di errore
  284.                 if(OpenSPCoop2Properties.getInstance().isGestioneRetrieveTokenSaveTokenInfoRetrieveFailed()) {
  285.                     if(informazioniToken!=null) {
  286.                         if(httpResponseCode!=null) {
  287.                             informazioniToken.setHttpResponseCode(httpResponseCode+"");
  288.                         }
  289.                         informazioniToken.setErrorDetails(esitoNegoziazioneToken.getDetails());
  290.                     }
  291.                     else {
  292.                         informazioniToken = new InformazioniNegoziazioneToken(datiRichiesta,
  293.                                 esitoNegoziazioneToken.getDetails(), httpResponseCode, risposta);
  294.                     }
  295.                     esitoNegoziazioneToken.setInformazioniNegoziazioneToken(informazioniToken);
  296.                 }
  297.             }
  298.            
  299.         }catch(Exception e){
  300.             esitoNegoziazioneToken.setTokenInternalError();
  301.             esitoNegoziazioneToken.setDetails(e.getMessage());
  302.             esitoNegoziazioneToken.setEccezioneProcessamento(e);
  303.         }
  304.        
  305.         if(datiRichiesta!=null && datiRichiesta.getPrepareRequest()!=null) {
  306.             datiRichiesta.setProcessComplete(DateManager.getDate());
  307.         }
  308.         return esitoNegoziazioneToken;
  309.     }
  310.    
  311.     static String buildPrefixCacheKeyNegoziazione(String policy, String funzione) {
  312.         StringBuilder bf = new StringBuilder(funzione);
  313.         bf.append("_");
  314.         bf.append(policy);
  315.         bf.append("_");
  316.         return bf.toString();
  317.     }
  318.     static String buildCacheKeyNegoziazione(String policy, String funzione, boolean portaDelegata, NegoziazioneTokenDynamicParameters dynamicParameters) {
  319.         StringBuilder bf = new StringBuilder();
  320.         bf.append(buildPrefixCacheKeyNegoziazione(policy, funzione));
  321.         if(portaDelegata){ // serve per non aver classcast exception nei risultati
  322.             bf.append("PD");
  323.         }
  324.         else {
  325.             bf.append("PA");
  326.         }
  327.         bf.append("_");
  328.        
  329.         String dynamicParametersKeyCache = dynamicParameters.toString("_", true);
  330.         bf.append(dynamicParametersKeyCache);
  331.        
  332.         return bf.toString();
  333.     }  
  334.     static void validazioneInformazioniNegoziazioneToken(boolean checkPerRinegoziazione, EsitoNegoziazioneToken esitoNegoziazioneToken, boolean saveErrorInCache) {
  335.        
  336.         Date now = DateManager.getDate();
  337.        
  338.         if(esitoNegoziazioneToken.isValido()) {
  339.             esitoNegoziazioneToken.setDateValide(true); // tanto le ricontrollo adesso
  340.         }
  341.        
  342.         if(esitoNegoziazioneToken.isValido() &&    
  343.             esitoNegoziazioneToken.getInformazioniNegoziazioneToken().getExpiresIn()!=null) {          
  344.                
  345.             if(checkPerRinegoziazione) {
  346.                
  347.                 OpenSPCoop2Properties properties = OpenSPCoop2Properties.getInstance();
  348.                 now = updateNowForExpire("NegoziazioneToken", now, esitoNegoziazioneToken.getInformazioniNegoziazioneToken().getRetrievedIn(), esitoNegoziazioneToken.getInformazioniNegoziazioneToken().getExpiresIn(),
  349.                         properties.getGestioneRetrieveTokenRefreshTokenBeforeExpirePercent(), properties.getGestioneRetrieveTokenRefreshTokenBeforeExpireSeconds());
  350.                
  351.             }
  352.            
  353.             /*
  354.              *  The lifetime in seconds of the access token.  For example, the value "3600" denotes that the access token will
  355.              * expire in one hour from the time the response was generated.
  356.              * If omitted, the authorization server SHOULD provide the expiration time via other means or document the default value.
  357.              **/
  358.             if(!now.before(esitoNegoziazioneToken.getInformazioniNegoziazioneToken().getExpiresIn())){
  359.                 esitoNegoziazioneToken.setTokenScaduto();
  360.                 esitoNegoziazioneToken.setDateValide(false);
  361.                 esitoNegoziazioneToken.setDetails("AccessToken expired");  
  362.             }
  363.            
  364.         }
  365.            
  366.         if(!esitoNegoziazioneToken.isValido()) {
  367.             esitoNegoziazioneToken.setNoCache(!saveErrorInCache);
  368.         }
  369.     }
  370.    
  371.     static Map<String, Object> buildDynamicNegoziazioneTokenMap(Busta busta,
  372.             RequestInfo requestInfo, PdDContext pddContext, Logger log) {
  373.         return TokenUtilities.buildDynamicMap(busta,
  374.                 requestInfo, pddContext, log);
  375.     }
  376.    
  377.     private static HttpResponse http(boolean debug, Logger log, PolicyNegoziazioneToken policyNegoziazioneToken,
  378.             Busta busta, RequestInfo requestInfo, TipoPdD tipoPdD,
  379.             NegoziazioneTokenDynamicParameters dynamicParameters, IProtocolFactory<?> protocolFactory,
  380.             IState state, boolean delegata, String idModulo, PortaApplicativa pa, PortaDelegata pd,
  381.             IDSoggetto idDominio, IDServizio idServizio,
  382.             boolean refreshModeEnabled, String refreshToken,
  383.             InformazioniNegoziazioneToken_DatiRichiesta datiRichiesta) throws TokenException, ProviderException, ProviderValidationException, UtilsException, SecurityException {
  384.        
  385.        
  386.         // *** Raccola Parametri ***
  387.        
  388.         String endpoint = dynamicParameters.getEndpoint();
  389.         if(datiRichiesta!=null) {
  390.             datiRichiesta.setEndpoint(endpoint);
  391.         }
  392.        
  393.         HttpRequestMethod httpMethod = dynamicParameters.getHttpMethod();
  394.        
  395.         // Nell'endpoint config ci finisce i timeout e la configurazione proxy
  396.         Properties endpointConfig = policyNegoziazioneToken.getProperties().get(Costanti.POLICY_ENDPOINT_CONFIG);
  397.        
  398.         boolean https = policyNegoziazioneToken.isEndpointHttps();
  399.         boolean httpsClient = false;
  400.         Properties sslConfig = null;
  401.         Properties sslClientConfig = null;
  402.         if(https) {
  403.             sslConfig = policyNegoziazioneToken.getProperties().get(Costanti.POLICY_ENDPOINT_SSL_CONFIG);
  404.             httpsClient = policyNegoziazioneToken.isHttpsAuthentication();
  405.             if(httpsClient) {
  406.                 sslClientConfig = policyNegoziazioneToken.getProperties().get(Costanti.POLICY_ENDPOINT_SSL_CLIENT_CONFIG);
  407.                 TokenUtilities.injectSameKeystoreForHttpsClient(sslConfig, sslClientConfig);
  408.             }
  409.         }
  410.        
  411.         boolean basic = policyNegoziazioneToken.isBasicAuthentication();
  412.         boolean basicAsAuthorizationHeader = policyNegoziazioneToken.isBasicAuthenticationAsAuthorizationHeader();
  413.         String username = null;
  414.         String password = null;
  415.         if(basic) {
  416.             username = dynamicParameters.getBasicUsername();
  417.             password = dynamicParameters.getBasicPassword();
  418.             if(datiRichiesta!=null) {
  419.                 datiRichiesta.setClientId(username);
  420.             }
  421.         }
  422.        
  423.         boolean bearer = policyNegoziazioneToken.isBearerAuthentication();
  424.         String bearerToken = null;
  425.         if(bearer) {
  426.             bearerToken = dynamicParameters.getBearerToken();
  427.             if(datiRichiesta!=null) {
  428.                 datiRichiesta.setClientToken(bearerToken);
  429.             }
  430.         }
  431.        
  432.        
  433.        
  434.         // *** Definizione Connettore ***
  435.        
  436.         ConnettoreMsg connettoreMsg = new ConnettoreMsg();
  437.         ConnettoreBaseHTTP connettore = null;
  438.         if(https) {
  439.             connettoreMsg.setTipoConnettore(TipiConnettore.HTTPS.getNome());
  440.             connettore = new ConnettoreHTTPS();
  441.         }
  442.         else {
  443.             connettoreMsg.setTipoConnettore(TipiConnettore.HTTP.getNome());
  444.             connettore = new ConnettoreHTTP();
  445.         }
  446.         connettoreMsg.setIdModulo(idModulo);
  447.         connettoreMsg.setState(state);
  448.         PolicyTimeoutConfig policyConfig = new PolicyTimeoutConfig();
  449.         policyConfig.setPolicyNegoziazione(policyNegoziazioneToken.getName());
  450.         connettoreMsg.setPolicyTimeoutConfig(policyConfig);
  451.        
  452.         ForwardProxy forwardProxy = null;
  453.         ConfigurazionePdDManager configurazionePdDManager = ConfigurazionePdDManager.getInstance(state);
  454.         if(configurazionePdDManager.isForwardProxyEnabled(requestInfo)) {
  455.             try {
  456.                 IDGenericProperties policy = new IDGenericProperties();
  457.                 policy.setTipologia(CostantiConfigurazione.GENERIC_PROPERTIES_TOKEN_TIPOLOGIA_RETRIEVE);
  458.                 policy.setNome(policyNegoziazioneToken.getName());
  459.                 if(delegata) {
  460.                     forwardProxy = configurazionePdDManager.getForwardProxyConfigFruizione(idDominio, idServizio, policy, requestInfo);
  461.                 }
  462.                 else {
  463.                     forwardProxy = configurazionePdDManager.getForwardProxyConfigErogazione(idDominio, idServizio, policy, requestInfo);
  464.                 }
  465.             }catch(Exception e) {
  466.                 throw new TokenException(GestoreToken.getMessageErroreGovWayProxy(e),e);
  467.             }
  468.         }
  469.         if(forwardProxy!=null && forwardProxy.isEnabled() && forwardProxy.getConfigToken()!=null && forwardProxy.getConfigToken().isTokenRetrieveEnabled()) {
  470.             connettoreMsg.setForwardProxy(forwardProxy);
  471.         }
  472.        
  473.         connettore.setForceDisable_proxyPassReverse(true);
  474.         connettore.init(dynamicParameters.getPddContext(), protocolFactory);
  475.         connettore.setRegisterSendIntoContext(false);
  476.        
  477.         if(basic && basicAsAuthorizationHeader){
  478.             InvocazioneCredenziali credenziali = new InvocazioneCredenziali();
  479.             credenziali.setUser(username);
  480.             credenziali.setPassword(password);
  481.             connettoreMsg.setCredenziali(credenziali);
  482.         }
  483.        
  484.         connettoreMsg.setConnectorProperties(new java.util.HashMap<>());
  485.         connettoreMsg.getConnectorProperties().put(CostantiConnettori.CONNETTORE_LOCATION, endpoint);
  486.         OpenSPCoop2Properties properties = OpenSPCoop2Properties.getInstance();
  487.         Boolean debugTramiteProperties = properties.getGestioneRetrieveTokenDebug();
  488.         if(debugTramiteProperties!=null) {
  489.             if(debugTramiteProperties) {
  490.                 connettoreMsg.getConnectorProperties().put(CostantiConnettori.CONNETTORE_DEBUG, true+"");
  491.             }
  492.         }
  493.         else if(debug) { // impostazione del connettore
  494.             connettoreMsg.getConnectorProperties().put(CostantiConnettori.CONNETTORE_DEBUG, true+"");
  495.         }
  496.         connettoreMsg.getConnectorProperties().put(CostantiConnettori.CONNETTORE_HTTP_DATA_TRANSFER_MODE, TransferLengthModes.CONTENT_LENGTH.getNome());
  497.         GestoreToken.addProperties(connettoreMsg, endpointConfig);
  498.         if(https) {
  499.             GestoreToken.addProperties(connettoreMsg, sslConfig);
  500.             if(httpsClient) {
  501.                 GestoreToken.addProperties(connettoreMsg, sslClientConfig);
  502.             }
  503.         }
  504.        
  505.        
  506.         TransportRequestContext transportRequestContext = new TransportRequestContext(log);
  507.         transportRequestContext.setRequestType(httpMethod.name());
  508.         transportRequestContext.setHeaders(new HashMap<>());
  509.         if(bearer) {
  510.             String authorizationHeader = HttpConstants.AUTHORIZATION_PREFIX_BEARER+bearerToken;
  511.             TransportUtils.setHeader(transportRequestContext.getHeaders(),HttpConstants.AUTHORIZATION, authorizationHeader);
  512.         }
  513.        
  514.         Map<String, List<String>> pContent = new HashMap<>();
  515.         boolean custom = false;
  516.         if(refreshModeEnabled) {
  517.             TransportUtils.setParameter(pContent,ClaimsNegoziazione.OAUTH2_RFC_6749_REQUEST_GRANT_TYPE, ClaimsNegoziazione.OAUTH2_RFC_6749_REQUEST_GRANT_TYPE_REFRESH_TOKEN);
  518.             TransportUtils.setParameter(pContent,ClaimsNegoziazione.OAUTH2_RFC_6749_REFRESH_TOKEN, refreshToken);
  519.         }
  520.         else if(policyNegoziazioneToken.isClientCredentialsGrant()) {
  521.             TransportUtils.setParameter(pContent,ClaimsNegoziazione.OAUTH2_RFC_6749_REQUEST_GRANT_TYPE, ClaimsNegoziazione.OAUTH2_RFC_6749_REQUEST_GRANT_TYPE_CLIENT_CREDENTIALS_GRANT);
  522.         }
  523.         else if(policyNegoziazioneToken.isRfc7523x509Grant() || policyNegoziazioneToken.isRfc7523ClientSecretGrant()) {
  524.             TransportUtils.setParameter(pContent,ClaimsNegoziazione.OAUTH2_RFC_6749_REQUEST_GRANT_TYPE, ClaimsNegoziazione.OAUTH2_RFC_6749_REQUEST_GRANT_TYPE_CLIENT_CREDENTIALS_GRANT);
  525.             TransportUtils.setParameter(pContent,ClaimsNegoziazione.OAUTH2_RFC_6749_REQUEST_CLIENT_ASSERTION_TYPE, ClaimsNegoziazione.OAUTH2_RFC_6749_REQUEST_CLIENT_ASSERTION_TYPE_RFC_7523);
  526.         }
  527.         else if(policyNegoziazioneToken.isUsernamePasswordGrant()) {
  528.             TransportUtils.setParameter(pContent,ClaimsNegoziazione.OAUTH2_RFC_6749_REQUEST_GRANT_TYPE, ClaimsNegoziazione.OAUTH2_RFC_6749_REQUEST_GRANT_TYPE_RESOURCE_OWNER_PASSWORD_CREDENTIALS_GRANT);
  529.         }
  530.         else if(policyNegoziazioneToken.isCustomGrant()) {
  531.             custom = true;
  532.         }
  533.         else {
  534.             throw new TokenException("Nessuna modalità definita");
  535.         }
  536.        
  537.         transportRequestContext.removeHeader(HttpConstants.CONTENT_TYPE);
  538.         String contentType = null;
  539.         if(custom) {
  540.             contentType = dynamicParameters.getHttpContentType();
  541.             if(contentType!=null && StringUtils.isNotEmpty(contentType)) {
  542.                 TransportUtils.setHeader(transportRequestContext.getHeaders(),HttpConstants.CONTENT_TYPE, contentType);
  543.             }
  544.         }
  545.         else {
  546.             contentType = HttpConstants.CONTENT_TYPE_X_WWW_FORM_URLENCODED;
  547.             TransportUtils.setHeader(transportRequestContext.getHeaders(),HttpConstants.CONTENT_TYPE, contentType);
  548.         }
  549.        
  550.         if(!custom && basic && !basicAsAuthorizationHeader){
  551.             TransportUtils.setParameter(pContent,ClaimsNegoziazione.OAUTH2_RFC_6749_REQUEST_CLIENT_ID, username);
  552.             TransportUtils.setParameter(pContent,ClaimsNegoziazione.OAUTH2_RFC_6749_REQUEST_CLIENT_SECRET, password);
  553.         }
  554.        
  555.         if(policyNegoziazioneToken.isUsernamePasswordGrant()) {
  556.             String usernamePasswordGrantUsername = dynamicParameters.getUsernamePasswordGrantUsername();
  557.             String usernamePasswordGrantPassword = dynamicParameters.getUsernamePasswordGrantPassword();
  558.             TransportUtils.setParameter(pContent,ClaimsNegoziazione.OAUTH2_RFC_6749_REQUEST_USERNAME, usernamePasswordGrantUsername);
  559.             TransportUtils.setParameter(pContent,ClaimsNegoziazione.OAUTH2_RFC_6749_REQUEST_PASSWORD, usernamePasswordGrantPassword);
  560.             if(datiRichiesta!=null) {
  561.                 datiRichiesta.setUsername(usernamePasswordGrantUsername);
  562.             }
  563.         }
  564.        
  565.         if(policyNegoziazioneToken.isRfc7523x509Grant() || policyNegoziazioneToken.isRfc7523ClientSecretGrant()) {
  566.             String jwt = buildJwt(policyNegoziazioneToken,
  567.                     busta, tipoPdD,
  568.                     dynamicParameters,
  569.                     protocolFactory, requestInfo);
  570.             String signedJwt = signJwt(policyNegoziazioneToken, jwt, contentType, dynamicParameters,
  571.                     busta, requestInfo, log);
  572.             TransportUtils.setParameter(pContent,ClaimsNegoziazione.OAUTH2_RFC_6749_REQUEST_CLIENT_ASSERTION, signedJwt);
  573.             if(datiRichiesta!=null) {
  574.                 boolean infoNormalizzate = properties.isGestioneRetrieveTokenGrantTypeRfc7523SaveClientAssertionJWTInfoTransazioniRegistrazioneInformazioniNormalizzate();
  575.                 datiRichiesta.setJwtClientAssertion(new InformazioniJWTClientAssertion(log, signedJwt, infoNormalizzate));
  576.             }
  577.         }
  578.        
  579.         if(!custom) {
  580.             List<String> scopes = policyNegoziazioneToken.getScopes(dynamicParameters);
  581.             if(scopes!=null && !scopes.isEmpty()) {
  582.                 StringBuilder bf = new StringBuilder();
  583.                 for (String scope : scopes) {
  584.                     if(bf.length()>0) {
  585.                         bf.append(" ");
  586.                     }
  587.                     bf.append(scope);
  588.                 }
  589.                 if(bf.length()>0) {
  590.                     TransportUtils.setParameter(pContent,ClaimsNegoziazione.OAUTH2_RFC_6749_REQUEST_SCOPE, bf.toString());
  591.                     if(datiRichiesta!=null) {
  592.                         datiRichiesta.setScope(scopes);
  593.                     }
  594.                 }
  595.             }
  596.            
  597.             String aud = dynamicParameters.getAudience();
  598.             if(aud!=null && !"".equals(aud)) {
  599.                 TransportUtils.setParameter(pContent,ClaimsNegoziazione.OAUTH2_RFC_6749_REQUEST_AUDIENCE, aud);
  600.                 if(datiRichiesta!=null) {
  601.                     datiRichiesta.setAudience(aud);
  602.                 }
  603.             }
  604.         }
  605.        
  606.         // indicazione se siamo in una token policy PDND
  607.         boolean pdnd = isTokenPolicyVersoPDND(policyNegoziazioneToken, OpenSPCoop2Properties.getInstance(), protocolFactory);
  608.         if(pdnd) {
  609.             String formClientId = dynamicParameters.getFormClientId();
  610.             if(formClientId==null) {
  611.                 OpenSPCoop2Properties op2Properties = OpenSPCoop2Properties.getInstance();
  612.                 String nomeSoggettoInterno = getNomeSoggettoInterno(busta, tipoPdD,
  613.                         protocolFactory, requestInfo,
  614.                         op2Properties);
  615.                 if(op2Properties.isGestioneRetrieveTokenPdndDatiRichiestaForceClientId(protocolFactory!=null ? protocolFactory.getProtocol() : null, nomeSoggettoInterno)) {
  616.                     formClientId = dynamicParameters.getSignedJwtClientId();
  617.                 }
  618.             }
  619.             if(formClientId!=null && !"".equals(formClientId) && !Costanti.POLICY_RETRIEVE_TOKEN_JWT_CLAIM_UNDEFINED.equals(formClientId)) {
  620.                 TransportUtils.setParameter(pContent,Costanti.PDND_OAUTH2_RFC_6749_REQUEST_CLIENT_ID, formClientId);
  621.                 if(datiRichiesta!=null && datiRichiesta.getClientId()==null) { // dovrebbe essere null poiche' il tipo PDND non e' abilitabile per il tipo clientId/Secret
  622.                     datiRichiesta.setClientId(formClientId);
  623.                 }
  624.             }
  625.            
  626.             String formResource = dynamicParameters.getFormResource();
  627.             if(formResource!=null && !"".equals(formResource) && !Costanti.POLICY_RETRIEVE_TOKEN_JWT_CLAIM_UNDEFINED.equals(formResource)) {
  628.                 TransportUtils.setParameter(pContent,Costanti.PDND_OAUTH2_RFC_6749_REQUEST_RESOURCE, formResource);
  629.             }
  630.         }
  631.        
  632.         String parameters = dynamicParameters.getParameters();
  633.         if(!custom && parameters!=null && !"".equals(parameters)) {
  634.             Properties convertTextToProperties = PropertiesUtilities.convertTextToProperties(parameters);
  635.             if(convertTextToProperties!=null && !convertTextToProperties.isEmpty()) {
  636.                 Map<String, String> mapParameters = new HashMap<>();
  637.                 Enumeration<Object> keys = convertTextToProperties.keys();
  638.                 while (keys.hasMoreElements()) {
  639.                     String nome = (String) keys.nextElement();
  640.                     if(nome!=null && !"".equals(nome)) {
  641.                         String valore = convertTextToProperties.getProperty(nome);
  642.                         if(valore!=null) {
  643.                             TransportUtils.setParameter(pContent, nome, valore);
  644.                             mapParameters.put(nome, valore);
  645.                         }
  646.                     }
  647.                 }
  648.                 if(datiRichiesta!=null && !mapParameters.isEmpty()) {
  649.                     datiRichiesta.setParameters(mapParameters);
  650.                 }
  651.             }
  652.         }
  653.        
  654.         String httpHeaders = dynamicParameters.getHttpHeaders();
  655.         if(httpHeaders!=null && !"".equals(httpHeaders)) {
  656.             Properties convertTextToProperties = PropertiesUtilities.convertTextToProperties(httpHeaders);
  657.             if(convertTextToProperties!=null && !convertTextToProperties.isEmpty()) {
  658.                 Map<String, String> mapHttpHeaders = new HashMap<>();
  659.                 Enumeration<Object> keys = convertTextToProperties.keys();
  660.                 while (keys.hasMoreElements()) {
  661.                     String nome = (String) keys.nextElement();
  662.                     if(nome!=null && !"".equals(nome)) {
  663.                         String valore = convertTextToProperties.getProperty(nome);
  664.                         if(valore!=null) {
  665.                             TransportUtils.setHeader(transportRequestContext.getHeaders(),nome, valore);
  666.                             mapHttpHeaders.put(nome, valore);
  667.                         }
  668.                     }
  669.                 }
  670.                 if(datiRichiesta!=null && !mapHttpHeaders.isEmpty()) {
  671.                     datiRichiesta.setHttpHeaders(mapHttpHeaders);
  672.                 }
  673.             }
  674.         }

  675.         String prefixUrl = "PREFIX?";
  676.         byte [] content = null;
  677.         if(custom) {
  678.             String contentString = dynamicParameters.getHttpPayload();
  679.             if(contentString!=null && StringUtils.isNotEmpty(contentString)) {
  680.                 content = contentString.getBytes();
  681.                 connettoreMsg.forceSendContent();
  682.             }
  683.         }
  684.         else {
  685.             String contentString = TransportUtils.buildUrlWithParameters(pContent, prefixUrl , log);
  686.             contentString = contentString.substring(prefixUrl.length());
  687.             if(contentString.startsWith("&") && contentString.length()>1) {
  688.                 contentString = contentString.substring(1);
  689.             }
  690.             content = contentString.getBytes();
  691.         }
  692.            
  693.         try {
  694.             OpenSPCoop2MessageParseResult pr = OpenSPCoop2MessageFactory.getDefaultMessageFactory().createMessage(MessageType.BINARY, transportRequestContext, content);
  695.             OpenSPCoop2Message msg = pr.getMessage_throwParseException();
  696.             connettoreMsg.setRequestMessage(msg);
  697.             connettoreMsg.setGenerateErrorWithConnectorPrefix(false);
  698.                        
  699.             connettore.setHttpMethod(msg);
  700.             connettore.setPa(pa);
  701.             connettore.setPd(pd);
  702.         }catch(Exception e) {
  703.             throw new TokenException(e.getMessage(),e);
  704.         }
  705.        
  706.         ResponseCachingConfigurazione responseCachingConfigurazione = new ResponseCachingConfigurazione();
  707.         responseCachingConfigurazione.setStato(StatoFunzionalita.DISABILITATO);
  708.         String prefixConnettore = "[EndpointNegoziazioneToken: "+endpoint+"] ";
  709.         if(endpointConfig.containsKey(CostantiConnettori.CONNETTORE_HTTP_PROXY_HOSTNAME)) {
  710.             String hostProxy = endpointConfig.getProperty(CostantiConnettori.CONNETTORE_HTTP_PROXY_HOSTNAME);
  711.             String portProxy = endpointConfig.getProperty(CostantiConnettori.CONNETTORE_HTTP_PROXY_PORT);
  712.             prefixConnettore = prefixConnettore+GestoreToken.getMessageViaProxy(hostProxy, portProxy);
  713.         }
  714.         if(datiRichiesta!=null && datiRichiesta.getPrepareRequest()!=null) {
  715.             datiRichiesta.setSendRequest(DateManager.getDate());
  716.         }
  717.         boolean send = connettore.send(responseCachingConfigurazione, connettoreMsg);
  718.         if(datiRichiesta!=null && datiRichiesta.getPrepareRequest()!=null) {
  719.             datiRichiesta.setReceiveResponse(DateManager.getDate());
  720.         }
  721.         if(!send) {
  722.             if(connettore.getEccezioneProcessamento()!=null) {
  723.                 throw new TokenException(prefixConnettore+connettore.getErrore(), connettore.getEccezioneProcessamento());
  724.             }
  725.             else {
  726.                 throw new TokenException(prefixConnettore+connettore.getErrore());
  727.             }
  728.         }
  729.        
  730.         OpenSPCoop2Message msgResponse = connettore.getResponse();
  731.         ByteArrayOutputStream bout = null;
  732.         if(msgResponse!=null) {
  733.             try {
  734.                 bout = new ByteArrayOutputStream();
  735.                 if(msgResponse!=null) {
  736.                     msgResponse.writeTo(bout, true);
  737.                 }
  738.                 bout.flush();
  739.                 bout.close();
  740.             }catch(Exception e) {
  741.                 throw new TokenException(e.getMessage(),e);
  742.             }
  743.         }
  744.        
  745.         HttpResponse httpResponse = new HttpResponse();
  746.         httpResponse.setResultHTTPOperation(connettore.getCodiceTrasporto());
  747.        
  748.         if(connettore.getCodiceTrasporto() >= 200 &&  connettore.getCodiceTrasporto() < 299) {
  749.             String msgSuccess = prefixConnettore+GestoreToken.getMessageConnettoreConnessioneSuccesso(connettore);
  750.             if(bout!=null && bout.size()>0) {
  751.                 log.debug(msgSuccess);
  752.                 httpResponse.setContent(bout.toByteArray());
  753.                 return httpResponse;
  754.             }
  755.             else {
  756.                 throw new TokenException(msgSuccess+GestoreToken.CONNETTORE_RISPOSTA_NON_PERVENUTA);
  757.             }
  758.         }
  759.         else {
  760.             String msgError = prefixConnettore+GestoreToken.getMessageConnettoreConnessioneErrore(connettore);
  761.             if(bout!=null && bout.size()>0) {
  762.                 String e = msgError+": "+bout.toString();
  763.                 log.debug(e);
  764.                 httpResponse.setContent(bout.toByteArray());
  765.                 return httpResponse;
  766.             }
  767.             else {
  768.                 log.error(msgError);
  769.                 throw new TokenException(msgError);
  770.             }
  771.         }
  772.        
  773.        
  774.     }
  775.    
  776.     private static String getNomeSoggettoInterno(Busta busta, TipoPdD tipoPdD,
  777.             IProtocolFactory<?> protocolFactory, RequestInfo requestInfo,
  778.             OpenSPCoop2Properties op2Properties) {
  779.         // soggetto interno
  780.         String nomeSoggettoInterno = null;
  781.         if(TipoPdD.APPLICATIVA.equals(tipoPdD) && busta!=null && busta.getDestinatario()!=null) {
  782.             nomeSoggettoInterno = busta.getDestinatario();
  783.         }
  784.         else if(TipoPdD.DELEGATA.equals(tipoPdD) && busta!=null && busta.getMittente()!=null) {
  785.             nomeSoggettoInterno = busta.getMittente();
  786.         }
  787.         else {
  788.             nomeSoggettoInterno = op2Properties.getIdentitaPortaDefault(protocolFactory!=null ? protocolFactory.getProtocol() : null, requestInfo).getNome();
  789.         }
  790.         return nomeSoggettoInterno;
  791.     }
  792.    
  793.     private static boolean isTokenPolicyVersoPDND(PolicyNegoziazioneToken policyNegoziazioneToken, OpenSPCoop2Properties op2Properties, IProtocolFactory<?> protocolFactory) throws TokenException {
  794.         boolean pdnd = policyNegoziazioneToken.isPDND();
  795.         if(!pdnd) {
  796.             // per client interop verifico la url
  797.             try {
  798.                 pdnd = policyNegoziazioneToken.getEndpoint()!=null && RegularExpressionEngine.isMatch(policyNegoziazioneToken.getEndpoint(),
  799.                         op2Properties.getGestioneRetrieveTokenPdndUrlPatternMatch(protocolFactory!=null ? protocolFactory.getProtocol() : null));
  800.             }catch(RegExpNotFoundException notFound) {
  801.                 pdnd = false;
  802.             }catch(Exception e) {
  803.                 throw new TokenException(e.getMessage(),e);
  804.             }
  805.         }
  806.         return pdnd;
  807.     }
  808.    
  809.     private static String buildJwt(PolicyNegoziazioneToken policyNegoziazioneToken,
  810.             Busta busta, TipoPdD tipoPdD,
  811.             NegoziazioneTokenDynamicParameters dynamicParameters,
  812.             IProtocolFactory<?> protocolFactory, RequestInfo requestInfo) throws TokenException, UtilsException {
  813.        
  814.         // https://datatracker.ietf.org/doc/html/rfc7523
  815.        
  816.         OpenSPCoop2Properties op2Properties = OpenSPCoop2Properties.getInstance();
  817.         JSONUtils jsonUtils = JSONUtils.getInstance(false);
  818.        
  819.         ObjectNode jwtPayload = jsonUtils.newObjectNode();

  820.         // indicazione se siamo in una token policy PDND
  821.         boolean pdnd = isTokenPolicyVersoPDND(policyNegoziazioneToken, op2Properties, protocolFactory);
  822.        
  823.         // soggetto interno
  824.         String nomeSoggettoInterno = getNomeSoggettoInterno(busta, tipoPdD,
  825.                 protocolFactory, requestInfo,
  826.                 op2Properties);
  827.        
  828.         // add iat, nbf, exp
  829.         long nowMs = DateManager.getTimeMillis();
  830.         long nowSeconds = nowMs/1000;
  831.        
  832.         String issuer = dynamicParameters.getSignedJwtIssuer();
  833.         if(issuer==null) {
  834.             issuer = nomeSoggettoInterno;
  835.         }
  836.         if(!Costanti.POLICY_RETRIEVE_TOKEN_JWT_CLAIM_UNDEFINED.equals(issuer)) {
  837.             jwtPayload.put(Claims.OIDC_ID_TOKEN_ISSUER, issuer);
  838.         }
  839.        
  840.         // For client authentication, the subject MUST be the "client_id" of the OAuth client.
  841.         String clientId = dynamicParameters.getSignedJwtClientId();
  842.         if(clientId==null) {
  843.             throw new TokenException("ClientID undefined");
  844.         }
  845.         if(
  846.                 !Costanti.POLICY_RETRIEVE_TOKEN_JWT_CLAIM_UNDEFINED.equals(clientId)
  847.                 &&
  848.                 (!pdnd || op2Properties.isGestioneRetrieveTokenPdndPayloadClientId(protocolFactory!=null ? protocolFactory.getProtocol() : null, nomeSoggettoInterno))
  849.             ) {
  850.             jwtPayload.put(Claims.INTROSPECTION_RESPONSE_RFC_7662_CLIENT_ID, clientId);
  851.         }
  852.        
  853.         String subject = dynamicParameters.getSignedJwtSubject();
  854.         if(StringUtils.isNotEmpty(subject)) {
  855.             if(!Costanti.POLICY_RETRIEVE_TOKEN_JWT_CLAIM_UNDEFINED.equals(subject)) {
  856.                 jwtPayload.put(Claims.OIDC_ID_TOKEN_SUBJECT, subject);
  857.             }
  858.         }
  859.         else {
  860.             if(!Costanti.POLICY_RETRIEVE_TOKEN_JWT_CLAIM_UNDEFINED.equals(clientId)) {
  861.                 jwtPayload.put(Claims.OIDC_ID_TOKEN_SUBJECT, clientId);
  862.             }
  863.         }
  864.        
  865.         // The JWT MUST contain an "aud" (audience) claim containing a value that identifies the authorization server as an intended audience.
  866.         String jwtAudience = dynamicParameters.getSignedJwtAudience();
  867.         if(jwtAudience==null) {
  868.             throw new TokenException("JWT-Audience undefined");
  869.         }
  870.         if(!Costanti.POLICY_RETRIEVE_TOKEN_JWT_CLAIM_UNDEFINED.equals(jwtAudience)) {
  871.             jwtPayload.put(Claims.OIDC_ID_TOKEN_AUDIENCE, jwtAudience);
  872.         }
  873.        
  874.         // The JWT MAY contain an "iat" (issued at) claim that identifies the time at which the JWT was issued.
  875.         jwtPayload.put(Claims.JSON_WEB_TOKEN_RFC_7519_ISSUED_AT, nowSeconds);
  876.        
  877.         // The JWT MAY contain an "nbf" (not before) claim that identifies the time before which the token MUST NOT be accepted for processing.
  878.         if(!pdnd || op2Properties.isGestioneRetrieveTokenPdndPayloadNbf(protocolFactory!=null ? protocolFactory.getProtocol() : null, nomeSoggettoInterno)) {
  879.             jwtPayload.put(Claims.JSON_WEB_TOKEN_RFC_7519_NOT_TO_BE_USED_BEFORE, nowSeconds);
  880.         }
  881.        
  882.         // The JWT MUST contain an "exp" (expiration time) claim that limits the time window during which the JWT can be used.
  883.         int ttl = -1;
  884.         try {
  885.             ttl = policyNegoziazioneToken.getJwtTtlSeconds();
  886.         }catch(Exception e) {
  887.             throw new TokenException("Invalid JWT-TimeToLive value: "+e.getMessage(),e);
  888.         }
  889.         long expired = nowSeconds+ttl;
  890.         jwtPayload.put(Claims.JSON_WEB_TOKEN_RFC_7519_EXPIRED, expired);
  891.        
  892.         // The JWT MAY contain a "jti" (JWT ID) claim that provides a unique identifier for the token.
  893.         String jti = dynamicParameters.getSignedJwtJti();
  894.         if(StringUtils.isNotEmpty(jti)) {
  895.             if(!Costanti.POLICY_RETRIEVE_TOKEN_JWT_CLAIM_UNDEFINED.equals(jti)) {
  896.                 jwtPayload.put(Claims.JSON_WEB_TOKEN_RFC_7519_JWT_ID, jti);
  897.             }
  898.         }
  899.         else {
  900.             // per default genero un uuid
  901.             String uuid = null;
  902.             try {
  903.                 uuid = UniqueIdentifierManager.newUniqueIdentifier().toString();
  904.             }catch(Exception e) {
  905.                 throw new TokenException("Invalid JWT-TimeToLive value: "+e.getMessage(),e);
  906.             }
  907.             jwtPayload.put(Claims.JSON_WEB_TOKEN_RFC_7519_JWT_ID, uuid);
  908.         }
  909.        
  910.         if(policyNegoziazioneToken.isPDND()) {
  911.            
  912.             // purposeId
  913.             String jwtPurposeId = dynamicParameters.getSignedJwtPurposeId();
  914.             if(jwtPurposeId==null) {
  915.                 throw new TokenException("JWT-PurposeId undefined");
  916.             }
  917.             if(!Costanti.POLICY_RETRIEVE_TOKEN_JWT_CLAIM_UNDEFINED.equals(jwtPurposeId)) {
  918.                 jwtPayload.put(Costanti.PDND_PURPOSE_ID, jwtPurposeId);
  919.             }
  920.            
  921.             // sessionInfo
  922.             String sessionInfo = dynamicParameters.getSignedJwtSessionInfo();
  923.             if(sessionInfo!=null && !"".equals(sessionInfo)) {
  924.                 Properties convertTextToProperties = PropertiesUtilities.convertTextToProperties(sessionInfo);
  925.                 ObjectNode sessionInfoPayload = null;
  926.                 if(convertTextToProperties!=null && !convertTextToProperties.isEmpty()) {
  927.                     Enumeration<Object> keys = convertTextToProperties.keys();
  928.                     while (keys.hasMoreElements()) {
  929.                         String nome = (String) keys.nextElement();
  930.                         if(nome!=null && !"".equals(nome)) {
  931.                             String valore = convertTextToProperties.getProperty(nome);
  932.                             if(valore!=null) {
  933.                                 if(sessionInfoPayload ==null) {
  934.                                     sessionInfoPayload = jsonUtils.newObjectNode();
  935.                                 }
  936.                                 jsonUtils.putValue(sessionInfoPayload, nome, valore);
  937.                             }
  938.                         }
  939.                     }
  940.                 }
  941.                 if(sessionInfoPayload!=null) {
  942.                     jwtPayload.set(Costanti.PDND_SESSION_INFO, sessionInfoPayload);
  943.                 }
  944.             }
  945.         }
  946.        
  947.         // digest Audit
  948.         String digestAudit = dynamicParameters.getSignedJwtAuditDigest();
  949.         if(digestAudit!=null && StringUtils.isNotEmpty(digestAudit)) {
  950.             String algorithm = dynamicParameters.getSignedJwtAuditDigestAlgo();
  951.             if(algorithm==null || StringUtils.isEmpty(algorithm)) {
  952.                 algorithm = Costanti.PDND_DIGEST_ALG_DEFAULT_VALUE;
  953.             }
  954.            
  955.             ObjectNode digest = jsonUtils.newObjectNode();
  956.             digest.put(Costanti.PDND_DIGEST_ALG, algorithm);
  957.             digest.put(Costanti.PDND_DIGEST_VALUE, digestAudit);
  958.             jwtPayload.set(Costanti.PDND_DIGEST, digest);
  959.         }
  960.        
  961.         // claims
  962.         String claims = dynamicParameters.getSignedJwtClaims();
  963.         if(claims!=null && !"".equals(claims)) {
  964.             Properties convertTextToProperties = PropertiesUtilities.convertTextToProperties(claims);
  965.             if(convertTextToProperties!=null && !convertTextToProperties.isEmpty()) {
  966.                 Enumeration<Object> keys = convertTextToProperties.keys();
  967.                 while (keys.hasMoreElements()) {
  968.                     String nome = (String) keys.nextElement();
  969.                     if(nome!=null && !"".equals(nome)) {
  970.                         String valore = convertTextToProperties.getProperty(nome);
  971.                         if(valore!=null) {
  972.                             jsonUtils.putValue(jwtPayload, nome, valore);
  973.                         }
  974.                     }
  975.                 }
  976.             }
  977.         }
  978.        
  979.         return jsonUtils.toString(jwtPayload);
  980.     }
  981.    
  982.     public static KeystoreParams readKeystoreParams(PolicyNegoziazioneToken policyNegoziazioneToken) throws TokenException {
  983.        
  984.         KeystoreParams kp = new KeystoreParams();
  985.        
  986.         String keystoreType = policyNegoziazioneToken.getJwtSignKeystoreType();
  987.         if(keystoreType==null) {
  988.             throw new TokenException(GestoreToken.KEYSTORE_TYPE_UNDEFINED);
  989.         }
  990.         kp.setType(keystoreType);
  991.        
  992.         fillKeystoreParams(policyNegoziazioneToken, keystoreType, kp);
  993.                
  994.         String keyAlias = policyNegoziazioneToken.getJwtSignKeyAlias();
  995.         if(keyAlias==null &&
  996.                 !SecurityConstants.KEYSTORE_TYPE_KEY_PAIR_VALUE.equalsIgnoreCase(keystoreType) &&
  997.                 !SecurityConstants.KEYSTORE_TYPE_PUBLIC_KEY_VALUE.equalsIgnoreCase(keystoreType)) {
  998.             throw new TokenException(GestoreToken.KEY_ALIAS_UNDEFINED);
  999.         }
  1000.         kp.setKeyAlias(keyAlias);
  1001.        
  1002.         String keyPassword = policyNegoziazioneToken.getJwtSignKeyPassword();
  1003.         if(keyPassword==null &&
  1004.                 !SecurityConstants.KEYSTORE_TYPE_JWK_VALUE.equalsIgnoreCase(keystoreType) &&
  1005.                 !SecurityConstants.KEYSTORE_TYPE_KEY_PAIR_VALUE.equalsIgnoreCase(keystoreType) &&
  1006.                 !SecurityConstants.KEYSTORE_TYPE_PUBLIC_KEY_VALUE.equalsIgnoreCase(keystoreType)) {
  1007.             boolean required = true;
  1008.             if(KeystoreType.JKS.isType(keystoreType)) {
  1009.                 required = DBUtils.isKeystoreJksKeyPasswordRequired();
  1010.             }
  1011.             else if(KeystoreType.PKCS12.isType(keystoreType)) {
  1012.                 required = DBUtils.isKeystorePkcs12KeyPasswordRequired();
  1013.             }
  1014.             if(required) {
  1015.                 throw new TokenException(GestoreToken.KEY_PASSWORD_UNDEFINED);
  1016.             }
  1017.         }
  1018.         kp.setKeyPassword(keyPassword);
  1019.        
  1020.         return kp;
  1021.     }
  1022.     private static void fillKeystoreParams(PolicyNegoziazioneToken policyNegoziazioneToken, String keystoreType, KeystoreParams kp) throws TokenException {
  1023.         String keystoreFile = null;
  1024.         String keystoreFilePublicKey = null;
  1025.         String keyPairAlgorithm = null;
  1026.         if(SecurityConstants.KEYSTORE_TYPE_KEY_PAIR_VALUE.equalsIgnoreCase(keystoreType)) {
  1027.             keystoreFile = policyNegoziazioneToken.getJwtSignKeystoreFile();
  1028.             if(keystoreFile==null) {
  1029.                 throw new TokenException(GestoreToken.KEYSTORE_PRIVATE_KEY_UNDEFINED);
  1030.             }
  1031.             kp.setPath(keystoreFile);
  1032.            
  1033.             keystoreFilePublicKey = policyNegoziazioneToken.getJwtSignKeystoreFilePublicKey();
  1034.             if(keystoreFilePublicKey==null) {
  1035.                 throw new TokenException(GestoreToken.KEYSTORE_PUBLIC_KEY_UNDEFINED);
  1036.             }
  1037.             kp.setKeyPairPublicKeyPath(keystoreFilePublicKey);
  1038.            
  1039.             keyPairAlgorithm = policyNegoziazioneToken.getJwtSignKeyPairAlgorithm();
  1040.             if(keyPairAlgorithm==null) {
  1041.                 throw new TokenException(GestoreToken.KEYSTORE_KEY_PAIR_ALGORITHM_UNDEFINED);
  1042.             }
  1043.             kp.setKeyPairAlgorithm(keyPairAlgorithm);
  1044.         }
  1045.         else {
  1046.             keystoreFile = policyNegoziazioneToken.getJwtSignKeystoreFile();
  1047.             if(keystoreFile==null) {
  1048.                 throw new TokenException(GestoreToken.KEYSTORE_KEYSTORE_FILE_UNDEFINED);
  1049.             }
  1050.             kp.setPath(keystoreFile);
  1051.         }
  1052.        
  1053.         String keystorePassword = policyNegoziazioneToken.getJwtSignKeystorePassword();
  1054.         if(keystorePassword==null &&
  1055.                 !SecurityConstants.KEYSTORE_TYPE_JWK_VALUE.equalsIgnoreCase(keystoreType) &&
  1056.                 !SecurityConstants.KEYSTORE_TYPE_KEY_PAIR_VALUE.equalsIgnoreCase(keystoreType) &&
  1057.                 !SecurityConstants.KEYSTORE_TYPE_PUBLIC_KEY_VALUE.equalsIgnoreCase(keystoreType)) {
  1058.             boolean required = true;
  1059.             if(KeystoreType.JKS.isType(keystoreType)) {
  1060.                 required = DBUtils.isKeystoreJksPasswordRequired();
  1061.             }
  1062.             else if(KeystoreType.PKCS12.isType(keystoreType)) {
  1063.                 required = DBUtils.isKeystorePkcs12PasswordRequired();
  1064.             }
  1065.             if(required) {
  1066.                 throw new TokenException(GestoreToken.KEYSTORE_KEYSTORE_PASSWORD_UNDEFINED);
  1067.             }
  1068.         }
  1069.         kp.setPassword(keystorePassword);
  1070.        
  1071.         String keystoreByokPolicy = policyNegoziazioneToken.getJwtSignKeystoreByokPolicy();
  1072.         kp.setByokPolicy(keystoreByokPolicy);
  1073.     }
  1074.    
  1075.     private static String signJwt(PolicyNegoziazioneToken policyNegoziazioneToken, String payload, String contentType,
  1076.             NegoziazioneTokenDynamicParameters dynamicParameters,
  1077.             Busta busta, RequestInfo requestInfo, Logger log) throws TokenException, SecurityException, UtilsException {
  1078.        
  1079.         String signAlgo = policyNegoziazioneToken.getJwtSignAlgorithm();
  1080.         if(signAlgo==null) {
  1081.             throw new TokenException("SignAlgorithm undefined");
  1082.         }
  1083.        
  1084.         KeyStore ks = null;
  1085.         KeyPairStore keyPairStore = null;
  1086.         JWKSetStore jwtStore = null;
  1087.         String keyAlias = null;
  1088.         String keyPassword = null;
  1089.         if(policyNegoziazioneToken.isRfc7523x509Grant()) {
  1090.            
  1091.             if(policyNegoziazioneToken.isJwtSignKeystoreApplicativoModI()) {
  1092.                
  1093.                 Map<String, Object> dynamicMap = null;
  1094.                 if(dynamicParameters.isByokPolicyDefinedApplicativoModI()) {
  1095.                     dynamicMap = DynamicMapBuilderUtils.buildDynamicMap(busta,
  1096.                             requestInfo, dynamicParameters.getPddContext(), log);
  1097.                 }
  1098.                
  1099.                 String keystoreType = dynamicParameters.getTipoKeystoreApplicativoModI();
  1100.                 if(keystoreType==null) {
  1101.                     throw new TokenException(GestoreToken.KEYSTORE_TYPE_UNDEFINED);
  1102.                 }
  1103.                 if(SecurityConstants.KEYSTORE_TYPE_KEY_PAIR_VALUE.equalsIgnoreCase(keystoreType)) {
  1104.                     keyPairStore = dynamicParameters.getKeyPairStoreApplicativoModI(dynamicMap);
  1105.                     if(keyPairStore==null) {
  1106.                         throw new TokenException(GestoreToken.KEYSTORE_KEYPAIR_UNDEFINED);
  1107.                     }
  1108.                 }
  1109.                 else if(SecurityConstants.KEYSTORE_TYPE_JWK_VALUE.equalsIgnoreCase(keystoreType)) {
  1110.                     jwtStore =  dynamicParameters.getJWKSetStoreApplicativoModI(dynamicMap);
  1111.                     if(jwtStore==null) {
  1112.                         throw new TokenException(GestoreToken.KEYSTORE_KEYSTORE_UNDEFINED);
  1113.                     }
  1114.                 }
  1115.                 else {
  1116.                     ks = dynamicParameters.getKeystoreApplicativoModI(dynamicMap);
  1117.                     if(ks==null) {
  1118.                         throw new TokenException(GestoreToken.KEYSTORE_KEYSTORE_UNDEFINED);
  1119.                     }
  1120.                 }
  1121.                
  1122.                 keyAlias = dynamicParameters.getKeyAliasApplicativoModI();
  1123.                 if(keyAlias==null &&
  1124.                         !SecurityConstants.KEYSTORE_TYPE_KEY_PAIR_VALUE.equalsIgnoreCase(keystoreType) &&
  1125.                         !SecurityConstants.KEYSTORE_TYPE_PUBLIC_KEY_VALUE.equalsIgnoreCase(keystoreType)) {
  1126.                     throw new TokenException(GestoreToken.KEY_ALIAS_UNDEFINED);
  1127.                 }
  1128.                 keyPassword = dynamicParameters.getKeyPasswordApplicativoModI();
  1129.                 if(keyPassword==null &&
  1130.                         !SecurityConstants.KEYSTORE_TYPE_JWK_VALUE.equalsIgnoreCase(keystoreType) &&
  1131.                         !SecurityConstants.KEYSTORE_TYPE_KEY_PAIR_VALUE.equalsIgnoreCase(keystoreType) &&
  1132.                         !SecurityConstants.KEYSTORE_TYPE_PUBLIC_KEY_VALUE.equalsIgnoreCase(keystoreType)) {
  1133.                     throw new TokenException(GestoreToken.KEY_PASSWORD_UNDEFINED);
  1134.                 }
  1135.             }
  1136.             else if(policyNegoziazioneToken.isJwtSignKeystoreFruizioneModI()) {
  1137.                
  1138.                 Map<String, Object> dynamicMap = null;
  1139.                 if(dynamicParameters.isByokPolicyDefinedFruizioneModI()) {
  1140.                     dynamicMap = DynamicMapBuilderUtils.buildDynamicMap(busta,
  1141.                             requestInfo, dynamicParameters.getPddContext(), log);
  1142.                 }
  1143.                
  1144.                 String keystoreType = dynamicParameters.getTipoKeystoreFruizioneModI();
  1145.                 if(keystoreType==null) {
  1146.                     throw new TokenException(GestoreToken.KEYSTORE_TYPE_UNDEFINED);
  1147.                 }
  1148.                 if(SecurityConstants.KEYSTORE_TYPE_KEY_PAIR_VALUE.equalsIgnoreCase(keystoreType)) {
  1149.                     keyPairStore = dynamicParameters.getKeyPairStoreFruizioneModI(dynamicMap);
  1150.                     if(keyPairStore==null) {
  1151.                         throw new TokenException(GestoreToken.KEYSTORE_KEYPAIR_UNDEFINED);
  1152.                     }
  1153.                 }
  1154.                 else if(SecurityConstants.KEYSTORE_TYPE_JWK_VALUE.equalsIgnoreCase(keystoreType)) {
  1155.                     jwtStore =  dynamicParameters.getJWKSetStoreFruizioneModI(dynamicMap);
  1156.                     if(jwtStore==null) {
  1157.                         throw new TokenException(GestoreToken.KEYSTORE_KEYSTORE_UNDEFINED);
  1158.                     }
  1159.                 }
  1160.                 else {
  1161.                     ks = dynamicParameters.getKeystoreFruizioneModI(dynamicMap);
  1162.                     if(ks==null) {
  1163.                         throw new TokenException(GestoreToken.KEYSTORE_KEYSTORE_UNDEFINED);
  1164.                     }
  1165.                 }
  1166.                
  1167.                 keyAlias = dynamicParameters.getKeyAliasFruizioneModI();
  1168.                 if(keyAlias==null &&
  1169.                         !SecurityConstants.KEYSTORE_TYPE_KEY_PAIR_VALUE.equalsIgnoreCase(keystoreType) &&
  1170.                         !SecurityConstants.KEYSTORE_TYPE_PUBLIC_KEY_VALUE.equalsIgnoreCase(keystoreType)) {
  1171.                     throw new TokenException(GestoreToken.KEY_ALIAS_UNDEFINED);
  1172.                 }
  1173.                 keyPassword = dynamicParameters.getKeyPasswordFruizioneModI();
  1174.                 if(keyPassword==null &&
  1175.                         !SecurityConstants.KEYSTORE_TYPE_JWK_VALUE.equalsIgnoreCase(keystoreType) &&
  1176.                         !SecurityConstants.KEYSTORE_TYPE_KEY_PAIR_VALUE.equalsIgnoreCase(keystoreType) &&
  1177.                         !SecurityConstants.KEYSTORE_TYPE_PUBLIC_KEY_VALUE.equalsIgnoreCase(keystoreType)) {
  1178.                     throw new TokenException(GestoreToken.KEY_PASSWORD_UNDEFINED);
  1179.                 }
  1180.             }
  1181.             else {
  1182.                 KeystoreParams kp = readKeystoreParams(policyNegoziazioneToken);

  1183.                 String keystoreType = kp.getType();
  1184.                 String keystoreFile = kp.getPath();
  1185.                 String keystoreFilePublicKey = kp.getKeyPairPublicKeyPath();
  1186.                 String keyPairAlgorithm = kp.getKeyPairAlgorithm();
  1187.                 String keystorePassword = kp.getPassword();
  1188.                
  1189.                 keyAlias = kp.getKeyAlias();                
  1190.                 keyPassword = kp.getKeyPassword();
  1191.                
  1192.                 String keystoreByokPolicy = kp.getByokPolicy();
  1193.                 BYOKRequestParams byokParams = null;
  1194.                 if(BYOKProvider.isPolicyDefined(keystoreByokPolicy)) {
  1195.                     Map<String, Object> dynamicMap = DynamicMapBuilderUtils.buildDynamicMap(busta,
  1196.                             requestInfo, dynamicParameters.getPddContext(), log);
  1197.                     byokParams = BYOKProvider.getBYOKRequestParamsByUnwrapBYOKPolicy(keystoreByokPolicy,
  1198.                             dynamicMap );
  1199.                 }
  1200.                
  1201.                 if(SecurityConstants.KEYSTORE_TYPE_KEY_PAIR_VALUE.equalsIgnoreCase(keystoreType)) {
  1202.                     keyPairStore = GestoreKeystoreCache.getKeyPairStore(requestInfo, keystoreFile, keystoreFilePublicKey, keyPassword, keyPairAlgorithm, byokParams);
  1203.                 }
  1204.                 else if(SecurityConstants.KEYSTORE_TYPE_JWK_VALUE.equalsIgnoreCase(keystoreType)) {
  1205.                     jwtStore = GestoreKeystoreCache.getJwkSetStore(requestInfo, keystoreFile, byokParams);
  1206.                 }
  1207.                 else {
  1208.                     MerlinKeystore merlinKs = GestoreKeystoreCache.getMerlinKeystore(requestInfo, keystoreFile, keystoreType, keystorePassword, byokParams);
  1209.                     if(merlinKs==null) {
  1210.                         throw new TokenException("Accesso al keystore '"+keystoreFile+"' non riuscito");
  1211.                     }
  1212.                     ks = merlinKs.getKeyStore();
  1213.                 }
  1214.             }
  1215.         }
  1216.        
  1217.         JWSOptions options = new JWSOptions(JOSESerialization.COMPACT);
  1218.        
  1219.         JwtHeaders jwtHeaders = new JwtHeaders();
  1220.         if(policyNegoziazioneToken.isJwtSignIncludeKeyIdWithKeyAlias()) {
  1221.             jwtHeaders.setKid(keyAlias);
  1222.         }
  1223.         else if(policyNegoziazioneToken.isJwtSignIncludeKeyIdWithClientId()) {
  1224.             String clientId = dynamicParameters.getSignedJwtClientId();
  1225.             jwtHeaders.setKid(clientId);
  1226.         }
  1227.         else if(policyNegoziazioneToken.isJwtSignIncludeKeyIdCustom()) {
  1228.             String customId = dynamicParameters.getSignedJwtCustomId();
  1229.             jwtHeaders.setKid(customId);
  1230.         }
  1231.         else if(policyNegoziazioneToken.isJwtSignIncludeKeyIdApplicativoModI()) {
  1232.             String clientId = dynamicParameters.getKidApplicativoModI();
  1233.             jwtHeaders.setKid(clientId);
  1234.         }
  1235.         else if(policyNegoziazioneToken.isJwtSignIncludeKeyIdFruizioneModI()) {
  1236.             String clientId = dynamicParameters.getKidFruizioneModI();
  1237.             jwtHeaders.setKid(clientId);
  1238.         }
  1239.         if(policyNegoziazioneToken.isJwtSignIncludeX509Cert()) {
  1240.             jwtHeaders.setAddX5C(true);
  1241.         }
  1242.         String url = dynamicParameters.getSignedJwtX509Url();
  1243.         if(url!=null && !"".equals(url)) {
  1244.             try {
  1245.                 jwtHeaders.setX509Url(new URI(url));
  1246.             }catch(Exception e) {
  1247.                 throw new TokenException(e.getMessage(),e);
  1248.             }
  1249.         }
  1250.         if(policyNegoziazioneToken.isJwtSignIncludeX509CertSha1()) {
  1251.             jwtHeaders.setX509IncludeCertSha1(true);
  1252.         }
  1253.         if(policyNegoziazioneToken.isJwtSignIncludeX509CertSha256()) {
  1254.             jwtHeaders.setX509IncludeCertSha256(true);
  1255.         }
  1256.         if(policyNegoziazioneToken.isJwtSignJoseContentType() &&
  1257.             contentType!=null && !"".equals(contentType)) {
  1258.             jwtHeaders.setContentType(contentType);
  1259.         }
  1260.         String type = policyNegoziazioneToken.getJwtSignJoseType();
  1261.         if(type!=null && !"".equals(type) && !Costanti.POLICY_RETRIEVE_TOKEN_JWT_CLAIM_UNDEFINED.equals(type)) { // funzionalita' undefined undocumented
  1262.             jwtHeaders.setType(type);
  1263.         }
  1264.         if(ks!=null) {
  1265.             Certificate cert = ks.getCertificate(keyAlias);
  1266.             if(cert instanceof X509Certificate) {
  1267.                 jwtHeaders.addX509cert((X509Certificate)cert);
  1268.             }
  1269.         }
  1270.        
  1271.         if(policyNegoziazioneToken.isRfc7523ClientSecretGrant()) {
  1272.        
  1273.             String clientSecret = policyNegoziazioneToken.getJwtClientSecret();
  1274.             if(clientSecret==null) {
  1275.                 throw new TokenException("ClientSecret undefined");
  1276.             }
  1277.            
  1278.             JsonSignature jsonSignature = new JsonSignature(clientSecret, signAlgo, jwtHeaders, options);
  1279.             return jsonSignature.sign(payload);
  1280.         }
  1281.         else if(policyNegoziazioneToken.isRfc7523x509Grant()) {
  1282.                        
  1283.             JsonSignature jsonSignature = null;
  1284.             if(keyPairStore!=null || jwtStore!=null) {
  1285.                 JsonWebKeys jwk = null;
  1286.                 if(keyPairStore!=null) {
  1287.                     jwk = keyPairStore.getJwkSet().getJsonWebKeys();
  1288.                     keyAlias = keyPairStore.getJwkSetKid();
  1289.                 }
  1290.                 else {
  1291.                     jwk = jwtStore.getJwkSet().getJsonWebKeys();
  1292.                 }
  1293.                 jsonSignature = new JsonSignature(jwk, false, keyAlias, signAlgo, jwtHeaders, options);
  1294.             }
  1295.             else {
  1296.                 jsonSignature = new JsonSignature(ks, false, keyAlias,  keyPassword, signAlgo, jwtHeaders, options);
  1297.             }
  1298.             return jsonSignature.sign(payload);
  1299.         }
  1300.         else {
  1301.             throw new TokenException("JWT Signed mode unknown");
  1302.         }
  1303.        
  1304.     }
  1305.    
  1306.    
  1307.    
  1308.    
  1309.     // ********* [NEGOZIAZIONE-TOKEN] UTILITIES INTERNE ****************** */
  1310.    
  1311.     public static Date updateNowForExpire(String debugMetodoChiamante, Date nowParam, Date iat, Date exp, Integer refreshTokenBeforeExpirePercent, Integer refreshTokenBeforeExpireSeconds) {
  1312.         Date now = nowParam;
  1313.         int secondsPreExpire = -1;
  1314.         if(iat!=null && refreshTokenBeforeExpirePercent!=null && refreshTokenBeforeExpirePercent>0) {
  1315.             int percent = refreshTokenBeforeExpirePercent;
  1316.             long secondsExpire = exp.getTime() / 1000l;
  1317.             long secondsIat = iat.getTime() / 1000l;
  1318.             long secondsDiff = secondsExpire - secondsIat;
  1319.             if(secondsDiff>0) {
  1320.                 float perc1 = Float.parseFloat(secondsDiff+"") / 100f;
  1321.                 float perc2 = perc1 * Float.parseFloat(percent+"");
  1322.                 int s = Math.round(perc2);
  1323.                 if(s>0) {
  1324.                     secondsPreExpire = s;
  1325.                 }
  1326.             }
  1327.         }
  1328.         else if(refreshTokenBeforeExpireSeconds!=null && refreshTokenBeforeExpireSeconds>0) {
  1329.             secondsPreExpire = refreshTokenBeforeExpireSeconds;
  1330.         }
  1331.         if(secondsPreExpire>0) {
  1332.             now = new Date(now.getTime() + (secondsPreExpire*1000));
  1333.             if(debugMetodoChiamante!=null) {
  1334.                 /**System.out.println("Controllo scadenza per rinegoziazione '"+debugMetodoChiamante+"' now+tollerance("+secondsPreExpire+")["+org.openspcoop2.utils.date.DateUtils.getSimpleDateFormatMs().format(now)+"] exp["+
  1335.                     org.openspcoop2.utils.date.DateUtils.getSimpleDateFormatMs().format(exp)+"] isExpired["+!now.before(exp)+"]");*/
  1336.             }
  1337.         }
  1338.         return now;
  1339.     }
  1340. }