AutenticazioneApiKey.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.autenticazione.pa;

  21. import org.openspcoop2.core.id.IDServizioApplicativo;
  22. import org.openspcoop2.core.id.IDSoggetto;
  23. import org.openspcoop2.core.registry.driver.DriverRegistroServiziNotFound;
  24. import org.openspcoop2.message.OpenSPCoop2Message;
  25. import org.openspcoop2.pdd.config.ConfigurazionePdDManager;
  26. import org.openspcoop2.pdd.config.OpenSPCoop2Properties;
  27. import org.openspcoop2.pdd.core.autenticazione.ApiKeyUtilities;
  28. import org.openspcoop2.pdd.core.autenticazione.AutenticazioneException;
  29. import org.openspcoop2.pdd.core.autenticazione.AutenticazioneUtils;
  30. import org.openspcoop2.pdd.core.autenticazione.ParametriAutenticazione;
  31. import org.openspcoop2.pdd.core.autenticazione.ParametriAutenticazioneApiKey;
  32. import org.openspcoop2.pdd.core.autenticazione.WWWAuthenticateConfig;
  33. import org.openspcoop2.pdd.logger.OpenSPCoop2Logger;
  34. import org.openspcoop2.protocol.registry.RegistroServiziManager;
  35. import org.openspcoop2.protocol.sdk.constants.ErroriCooperazione;
  36. import org.openspcoop2.protocol.sdk.constants.IntegrationFunctionError;
  37. import org.openspcoop2.utils.BooleanNullable;
  38. import org.openspcoop2.utils.crypt.CryptConfig;

  39. /**
  40.  * Classe che implementa una autenticazione API-Key.
  41.  *
  42.  * @author Andrea Poli (apoli@link.it)
  43.  * @author $Author$
  44.  * @version $Rev$, $Date$
  45.  */

  46. public class AutenticazioneApiKey extends AbstractAutenticazioneBase {

  47.     private boolean header = true;
  48.     private boolean cookie = true;
  49.     private boolean queryParameter = true;
  50.    
  51.     private String nomeHeaderApiKey = null;
  52.     private String nomeCookieApiKey = null;
  53.     private String nomeQueryParameterApiKey = null;
  54.    
  55.     private boolean appId = false;
  56.    
  57.     private String nomeHeaderAppId = null;
  58.     private String nomeCookieAppId = null;
  59.     private String nomeQueryParameterAppId = null;
  60.    
  61.     private boolean cleanApiKey = true;
  62.     private boolean cleanAppId = true;
  63.    
  64.     private boolean logError = true;
  65.     @Override
  66.     public void setLogError(boolean logError) {
  67.         this.logError = logError;
  68.     }
  69.    
  70.     @Override
  71.     public void initParametri(ParametriAutenticazione parametri) throws AutenticazioneException {
  72.         super.initParametri(parametri);
  73.        
  74.         ParametriAutenticazioneApiKey authApiKey = new ParametriAutenticazioneApiKey(this.parametri);
  75.        
  76.         BooleanNullable bNullable = authApiKey.getHeader();
  77.         if(bNullable!=null && bNullable.getValue()!=null) {
  78.             this.header = bNullable.getValue();
  79.         }
  80.        
  81.         bNullable = authApiKey.getCookie();
  82.         if(bNullable!=null && bNullable.getValue()!=null) {
  83.             this.cookie = bNullable.getValue();
  84.         }
  85.        
  86.         bNullable = authApiKey.getQueryParameter();
  87.         if(bNullable!=null && bNullable.getValue()!=null) {
  88.             this.queryParameter = bNullable.getValue();
  89.         }
  90.                
  91.         this.nomeHeaderApiKey = authApiKey.getNomeHeaderApiKey();
  92.         this.nomeCookieApiKey = authApiKey.getNomeCookieApiKey();
  93.         this.nomeQueryParameterApiKey = authApiKey.getNomeQueryParameterApiKey();
  94.        
  95.         bNullable = authApiKey.getAppId();
  96.         if(bNullable!=null && bNullable.getValue()!=null) {
  97.             this.appId = bNullable.getValue();
  98.         }
  99.                
  100.         if(this.appId) {
  101.             this.nomeHeaderAppId = authApiKey.getNomeHeaderAppId();
  102.             this.nomeCookieAppId = authApiKey.getNomeCookieAppId();
  103.             this.nomeQueryParameterAppId = authApiKey.getNomeQueryParameterAppId();
  104.         }
  105.        
  106.         bNullable = authApiKey.getCleanApiKey();
  107.         if(bNullable!=null && bNullable.getValue()!=null) {
  108.             this.cleanApiKey = bNullable.getValue();
  109.         }
  110.        
  111.         if(this.appId) {
  112.             bNullable = authApiKey.getCleanAppId();
  113.             if(bNullable!=null && bNullable.getValue()!=null) {
  114.                 this.cleanAppId = bNullable.getValue();
  115.             }
  116.         }
  117.                
  118.     }
  119.    
  120.     @Override
  121.     public String getSuffixKeyAuthenticationResultInCache(DatiInvocazionePortaApplicativa datiInvocazione) {
  122.        
  123.         if(datiInvocazione==null) {
  124.             return null;
  125.         }
  126.         try {
  127.             String apiKey = ApiKeyUtilities.getKey(true, this.header, this.cookie, this.queryParameter,
  128.                     this.nomeHeaderApiKey, this.nomeCookieApiKey, this.nomeQueryParameterApiKey,
  129.                     datiInvocazione.getInfoConnettoreIngresso(), this.getPddContext(), false,
  130.                     new StringBuilder());
  131.             if(apiKey==null) {
  132.                 return null;
  133.             }
  134.             if(this.appId) {
  135.                 String appId = ApiKeyUtilities.getKey(false, this.header, this.cookie, this.queryParameter,
  136.                         this.nomeHeaderAppId, this.nomeCookieAppId, this.nomeQueryParameterAppId,
  137.                         datiInvocazione.getInfoConnettoreIngresso(), this.getPddContext(), false,
  138.                         new StringBuilder());
  139.                 if(appId==null) {
  140.                     return null;
  141.                 }
  142.                 return "multipleApiKey-"+appId+"."+apiKey;
  143.             }
  144.             else {
  145.                 return "apiKey-"+apiKey;
  146.             }
  147.         }catch(Exception e) {
  148.             return null;
  149.         }
  150.        
  151.     }
  152.    
  153.     @Override
  154.     public EsitoAutenticazionePortaApplicativa process(DatiInvocazionePortaApplicativa datiInvocazione) throws AutenticazioneException{

  155.         EsitoAutenticazionePortaApplicativa esito = new EsitoAutenticazionePortaApplicativa();
  156.        
  157.         StringBuilder fullCredential= new StringBuilder();
  158.        
  159.         OpenSPCoop2Properties op2Properties = OpenSPCoop2Properties.getInstance();
  160.         WWWAuthenticateConfig wwwAuthenticateConfig = op2Properties.getRealmAutenticazioneApiKeyWWWAuthenticateConfig();    
  161.        
  162.         // Controllo apiKey fornite
  163.         String apiKey = null;
  164.         try {
  165.             apiKey = ApiKeyUtilities.getKey(true, this.header, this.cookie, this.queryParameter,
  166.                     this.nomeHeaderApiKey, this.nomeCookieApiKey, this.nomeQueryParameterApiKey,
  167.                     datiInvocazione!=null ? datiInvocazione.getInfoConnettoreIngresso() : null, this.getPddContext(), true,
  168.                     fullCredential);
  169.         }catch(Exception e) {
  170.             if(this.logError) {
  171.                 OpenSPCoop2Logger.getLoggerOpenSPCoopCore().error("AutenticazioneApiKey non riuscita",e);
  172.             }
  173.             esito.setErroreCooperazione(IntegrationFunctionError.AUTHENTICATION_CREDENTIALS_NOT_FOUND, ErroriCooperazione.AUTENTICAZIONE_FALLITA_CREDENZIALI_NON_FORNITE.getErroreCooperazione());
  174.             esito.setClientAuthenticated(false);
  175.             esito.setClientIdentified(false);
  176.             if(wwwAuthenticateConfig!=null) {
  177.                 esito.setWwwAuthenticateErrorHeader(wwwAuthenticateConfig.buildWWWAuthenticateHeaderValue_notFound());
  178.             }
  179.             return esito;
  180.         }
  181.         if( apiKey==null || "".equals(apiKey) ){
  182.             esito.setErroreCooperazione(IntegrationFunctionError.AUTHENTICATION_CREDENTIALS_NOT_FOUND, ErroriCooperazione.AUTENTICAZIONE_FALLITA_CREDENZIALI_NON_FORNITE.getErroreCooperazione());
  183.             esito.setClientAuthenticated(false);
  184.             esito.setClientIdentified(false);
  185.             if(wwwAuthenticateConfig!=null) {
  186.                 esito.setWwwAuthenticateErrorHeader(wwwAuthenticateConfig.buildWWWAuthenticateHeaderValue_notFound());
  187.             }
  188.             return esito;
  189.         }
  190.        
  191.         String appId = null;
  192.         if(this.appId) {
  193.             try {
  194.                 appId = ApiKeyUtilities.getKey(false, this.header, this.cookie, this.queryParameter,
  195.                         this.nomeHeaderAppId, this.nomeCookieAppId, this.nomeQueryParameterAppId,
  196.                         datiInvocazione!=null ? datiInvocazione.getInfoConnettoreIngresso() : null, this.getPddContext(), true,
  197.                         fullCredential);
  198.             }catch(Exception e) {
  199.                 if(this.logError) {
  200.                     OpenSPCoop2Logger.getLoggerOpenSPCoopCore().error("AutenticazioneApiKey (AppId) non riuscita",e);
  201.                 }
  202.                 esito.setErroreCooperazione(IntegrationFunctionError.AUTHENTICATION_CREDENTIALS_NOT_FOUND, ErroriCooperazione.AUTENTICAZIONE_FALLITA_CREDENZIALI_NON_FORNITE.getErroreCooperazione());
  203.                 esito.setClientAuthenticated(false);
  204.                 esito.setClientIdentified(false);
  205.                 esito.setFullCredential(fullCredential.toString());
  206.                 if(wwwAuthenticateConfig!=null) {
  207.                     esito.setWwwAuthenticateErrorHeader(wwwAuthenticateConfig.buildWWWAuthenticateHeaderValue_notFound());
  208.                 }
  209.                 return esito;
  210.             }
  211.             if( appId==null || "".equals(appId) ){
  212.                 esito.setErroreCooperazione(IntegrationFunctionError.AUTHENTICATION_CREDENTIALS_NOT_FOUND, ErroriCooperazione.AUTENTICAZIONE_FALLITA_CREDENZIALI_NON_FORNITE.getErroreCooperazione());
  213.                 esito.setClientAuthenticated(false);
  214.                 esito.setClientIdentified(false);
  215.                 esito.setFullCredential(fullCredential.toString());
  216.                 if(wwwAuthenticateConfig!=null) {
  217.                     esito.setWwwAuthenticateErrorHeader(wwwAuthenticateConfig.buildWWWAuthenticateHeaderValue_notFound());
  218.                 }
  219.                 return esito;
  220.             }
  221.         }
  222.        
  223.         // per conoscere la credenziale passata anche in caso di autenticazione fallita
  224.         esito.setFullCredential(fullCredential.toString());
  225.                
  226.         String identitaAutenticata = null;
  227.         String password = null;
  228.         try {
  229.             if(this.appId) {
  230.                 identitaAutenticata = appId;
  231.                 password = ApiKeyUtilities.decodeMultipleApiKey(apiKey);
  232.             }
  233.             else {
  234.                 String [] decodedApiKey = ApiKeyUtilities.decodeApiKey(apiKey);
  235.                 identitaAutenticata = decodedApiKey[0];
  236.                 password = decodedApiKey[1];
  237.             }
  238.         }catch(Exception e) {
  239.             if(this.logError) {
  240.                 OpenSPCoop2Logger.getLoggerOpenSPCoopCore().error("AutenticazioneApiKey (appId:"+this.appId+") fallita",e);
  241.             }
  242.             esito.setErroreCooperazione(IntegrationFunctionError.AUTHENTICATION_INVALID_CREDENTIALS, ErroriCooperazione.AUTENTICAZIONE_FALLITA_CREDENZIALI_FORNITE_NON_CORRETTE.getErroreCooperazione());
  243.             esito.setClientAuthenticated(false);
  244.             esito.setClientIdentified(false);
  245.             if(wwwAuthenticateConfig!=null) {
  246.                 esito.setWwwAuthenticateErrorHeader(wwwAuthenticateConfig.buildWWWAuthenticateHeaderValue_invalid());
  247.             }
  248.             return esito;
  249.         }
  250.        
  251.        
  252.         CryptConfig cryptConfigApplicativi = op2Properties.getCryptConfigAutenticazioneApplicativi();
  253.         CryptConfig cryptConfigSoggetti = op2Properties.getCryptConfigAutenticazioneSoggetti();
  254.                    
  255.         // !NO!: Essendoci il principal del chiamante, il client e' stato autenticato dal container
  256.         //esito.setClientAuthenticated(true); come per il basic, per poter essere autenticato bisogna verificare che sia registrato sulla base dati
  257.         esito.setCredential(identitaAutenticata);
  258.        
  259.         IDSoggetto idSoggetto = null;
  260.         try{
  261.             RegistroServiziManager registroServiziManager = datiInvocazione!=null ? RegistroServiziManager.getInstance(datiInvocazione.getState()) : RegistroServiziManager.getInstance();
  262.             idSoggetto = registroServiziManager.getIdSoggettoByCredenzialiApiKey(identitaAutenticata, password, this.appId, cryptConfigSoggetti, null); // all registry
  263.         }
  264.         catch(DriverRegistroServiziNotFound notFound){
  265.             OpenSPCoop2Logger.getLoggerOpenSPCoopCore().debug("AutenticazioneApiKey (appId:"+this.appId+") non ha trovato risultati",notFound);
  266.         }
  267.         catch(Exception e){
  268.             if(this.logError) {
  269.                 OpenSPCoop2Logger.getLoggerOpenSPCoopCore().error("AutenticazioneApiKey (appId:"+this.appId+") non riuscita",e);
  270.             }
  271.             esito.setErroreCooperazione(IntegrationFunctionError.INTERNAL_REQUEST_ERROR, ErroriCooperazione.ERRORE_GENERICO_PROCESSAMENTO_MESSAGGIO.getErroreCooperazione());
  272.             esito.setClientIdentified(false);
  273.             esito.setEccezioneProcessamento(e);
  274.             return esito;
  275.         }
  276.        
  277.         IDServizioApplicativo idServizioApplicativo = null;
  278.         try {
  279.             if(idSoggetto==null && this.getProtocolFactory().createProtocolConfiguration().isSupportoAutenticazioneApplicativiErogazioni()) {
  280.                 ConfigurazionePdDManager configurazionePdDManager = datiInvocazione!=null ? ConfigurazionePdDManager.getInstance(datiInvocazione.getState()) : ConfigurazionePdDManager.getInstance();
  281.                 idServizioApplicativo = configurazionePdDManager.
  282.                         getIdServizioApplicativoByCredenzialiApiKey(identitaAutenticata, password, this.appId, cryptConfigApplicativi);
  283.                 if(idServizioApplicativo!=null) {
  284.                     if(idSoggetto==null) {
  285.                         idSoggetto = idServizioApplicativo.getIdSoggettoProprietario();
  286.                     }
  287.                     // Non ha senso poter identificare entrambi con le stesse credenziali
  288. //                  else if(idServizioApplicativo.getIdSoggettoProprietario().equals(idSoggetto)==false) {
  289. //                      throw new Exception("Identificato sia un soggetto che un applicativo. Il soggetto ["+idSoggetto+
  290. //                              "] identificato รจ differente dal proprietario dell'applicativo identificato ["+idServizioApplicativo.getIdSoggettoProprietario()+"]");
  291. //                  }
  292.                 }
  293.             }
  294.         }
  295.         catch(Exception e){
  296.             if(this.logError) {
  297.                 OpenSPCoop2Logger.getLoggerOpenSPCoopCore().error("AutenticazioneApiKey (appId:"+this.appId+") (Applicativi) non riuscita",e);
  298.             }
  299.             esito.setErroreCooperazione(IntegrationFunctionError.INTERNAL_REQUEST_ERROR, ErroriCooperazione.ERRORE_GENERICO_PROCESSAMENTO_MESSAGGIO.getErroreCooperazione());
  300.             esito.setClientAuthenticated(false);
  301.             esito.setClientIdentified(false);
  302.             esito.setEccezioneProcessamento(e);
  303.             return esito;
  304.         }
  305.        
  306.         if(idSoggetto == null){
  307.             esito.setErroreCooperazione(IntegrationFunctionError.AUTHENTICATION_INVALID_CREDENTIALS, ErroriCooperazione.AUTENTICAZIONE_FALLITA_CREDENZIALI_FORNITE_NON_CORRETTE.getErroreCooperazione());
  308.             esito.setClientAuthenticated(false);
  309.             esito.setClientIdentified(false);
  310.             if(wwwAuthenticateConfig!=null) {
  311.                 esito.setWwwAuthenticateErrorHeader(wwwAuthenticateConfig.buildWWWAuthenticateHeaderValue_invalid());
  312.             }
  313.             return esito;
  314.         }
  315.         else {
  316.             esito.setClientAuthenticated(true);
  317.             esito.setClientIdentified(true);
  318.             esito.setIdSoggetto(idSoggetto);
  319.             esito.setIdServizioApplicativo(idServizioApplicativo);
  320.         }
  321.        
  322.         return esito;
  323.        
  324.     }

  325.     @Override
  326.     public void cleanPostAuth(OpenSPCoop2Message message) throws AutenticazioneException {
  327.        
  328.         AutenticazioneUtils.finalizeProcessApiKey(message,
  329.                 this.header, this.cookie, this.queryParameter,
  330.                 this.nomeHeaderApiKey, this.nomeCookieApiKey, this.nomeQueryParameterApiKey,
  331.                 this.cleanApiKey);
  332.        
  333.         if(this.appId) {
  334.             AutenticazioneUtils.finalizeProcessApiKey(message,
  335.                     this.header, this.cookie, this.queryParameter,
  336.                     this.nomeHeaderAppId, this.nomeCookieAppId, this.nomeQueryParameterAppId,
  337.                     this.cleanAppId);
  338.         }
  339.        
  340.     }
  341. }