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.pd;

  21. import org.openspcoop2.core.id.IDServizioApplicativo;
  22. import org.openspcoop2.core.id.IDSoggetto;
  23. import org.openspcoop2.message.OpenSPCoop2Message;
  24. import org.openspcoop2.pdd.config.ConfigurazionePdDManager;
  25. import org.openspcoop2.pdd.config.OpenSPCoop2Properties;
  26. import org.openspcoop2.pdd.core.autenticazione.ApiKeyUtilities;
  27. import org.openspcoop2.pdd.core.autenticazione.AutenticazioneException;
  28. import org.openspcoop2.pdd.core.autenticazione.AutenticazioneUtils;
  29. import org.openspcoop2.pdd.core.autenticazione.ParametriAutenticazione;
  30. import org.openspcoop2.pdd.core.autenticazione.ParametriAutenticazioneApiKey;
  31. import org.openspcoop2.pdd.core.autenticazione.WWWAuthenticateConfig;
  32. import org.openspcoop2.pdd.logger.OpenSPCoop2Logger;
  33. import org.openspcoop2.protocol.sdk.constants.CodiceErroreIntegrazione;
  34. import org.openspcoop2.protocol.sdk.constants.CostantiProtocollo;
  35. import org.openspcoop2.protocol.sdk.constants.ErroriIntegrazione;
  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.         ParametriAutenticazioneApiKey authApiKey = new ParametriAutenticazioneApiKey(this.parametri);
  74.        
  75.         BooleanNullable bNullable = authApiKey.getHeader();
  76.         if(bNullable!=null && bNullable.getValue()!=null) {
  77.             this.header = bNullable.getValue();
  78.         }
  79.        
  80.         bNullable = authApiKey.getCookie();
  81.         if(bNullable!=null && bNullable.getValue()!=null) {
  82.             this.cookie = bNullable.getValue();
  83.         }
  84.        
  85.         bNullable = authApiKey.getQueryParameter();
  86.         if(bNullable!=null && bNullable.getValue()!=null) {
  87.             this.queryParameter = bNullable.getValue();
  88.         }
  89.                
  90.         this.nomeHeaderApiKey = authApiKey.getNomeHeaderApiKey();
  91.         this.nomeCookieApiKey = authApiKey.getNomeCookieApiKey();
  92.         this.nomeQueryParameterApiKey = authApiKey.getNomeQueryParameterApiKey();
  93.        
  94.         bNullable = authApiKey.getAppId();
  95.         if(bNullable!=null && bNullable.getValue()!=null) {
  96.             this.appId = bNullable.getValue();
  97.         }
  98.                
  99.         if(this.appId) {
  100.             this.nomeHeaderAppId = authApiKey.getNomeHeaderAppId();
  101.             this.nomeCookieAppId = authApiKey.getNomeCookieAppId();
  102.             this.nomeQueryParameterAppId = authApiKey.getNomeQueryParameterAppId();
  103.         }
  104.        
  105.         bNullable = authApiKey.getCleanApiKey();
  106.         if(bNullable!=null && bNullable.getValue()!=null) {
  107.             this.cleanApiKey = bNullable.getValue();
  108.         }
  109.        
  110.         if(this.appId) {
  111.             bNullable = authApiKey.getCleanAppId();
  112.             if(bNullable!=null && bNullable.getValue()!=null) {
  113.                 this.cleanAppId = bNullable.getValue();
  114.             }
  115.         }
  116.        
  117.     }
  118.    
  119.     @Override
  120.     public String getSuffixKeyAuthenticationResultInCache(DatiInvocazionePortaDelegata datiInvocazione) {
  121.         if(datiInvocazione==null) {
  122.             return null;
  123.         }
  124.         try {
  125.             String apiKey = ApiKeyUtilities.getKey(true, this.header, this.cookie, this.queryParameter,
  126.                     this.nomeHeaderApiKey, this.nomeCookieApiKey, this.nomeQueryParameterApiKey,
  127.                     datiInvocazione.getInfoConnettoreIngresso(), this.getPddContext(), false,
  128.                     new StringBuilder());
  129.             if(apiKey==null) {
  130.                 return null;
  131.             }
  132.             if(this.appId) {
  133.                 String appId = ApiKeyUtilities.getKey(false, this.header, this.cookie, this.queryParameter,
  134.                         this.nomeHeaderAppId, this.nomeCookieAppId, this.nomeQueryParameterAppId,
  135.                         datiInvocazione.getInfoConnettoreIngresso(), this.getPddContext(), false,
  136.                         new StringBuilder());
  137.                 if(appId==null) {
  138.                     return null;
  139.                 }
  140.                 return "multipleApiKey-"+appId+"."+apiKey;
  141.             }
  142.             else {
  143.                 return "apiKey-"+apiKey;
  144.             }
  145.         }catch(Exception e) {
  146.             return null;
  147.         }
  148.     }
  149.    
  150.     @Override
  151.     public EsitoAutenticazionePortaDelegata process(DatiInvocazionePortaDelegata datiInvocazione) throws AutenticazioneException{

  152.         EsitoAutenticazionePortaDelegata esito = new EsitoAutenticazionePortaDelegata();
  153.        
  154.         IDSoggetto soggettoFruitore = null;
  155.         if(datiInvocazione!=null && datiInvocazione.getPd()!=null) {
  156.             soggettoFruitore = new IDSoggetto(datiInvocazione.getPd().getTipoSoggettoProprietario(), datiInvocazione.getPd().getNomeSoggettoProprietario());
  157.         }
  158.        
  159.         StringBuilder fullCredential= new StringBuilder();
  160.        
  161.         OpenSPCoop2Properties op2Properties = OpenSPCoop2Properties.getInstance();
  162.         WWWAuthenticateConfig wwwAuthenticateConfig = op2Properties.getRealmAutenticazioneApiKeyWWWAuthenticateConfig();
  163.        
  164.         // Controllo apiKey fornite
  165.         String apiKey = null;
  166.         try {
  167.             apiKey = ApiKeyUtilities.getKey(true, this.header, this.cookie, this.queryParameter,
  168.                     this.nomeHeaderApiKey, this.nomeCookieApiKey, this.nomeQueryParameterApiKey,
  169.                     datiInvocazione!=null ? datiInvocazione.getInfoConnettoreIngresso() : null, this.getPddContext(), true,
  170.                     fullCredential);
  171.         }catch(Exception e) {
  172.             if(this.logError) {
  173.                 OpenSPCoop2Logger.getLoggerOpenSPCoopCore().error("AutenticazioneApiKey non riuscita",e);
  174.             }
  175.             esito.setErroreIntegrazione(IntegrationFunctionError.AUTHENTICATION_CREDENTIALS_NOT_FOUND, ErroriIntegrazione.ERRORE_402_AUTENTICAZIONE_FALLITA.getErrore402_AutenticazioneFallitaPrincipal(CostantiProtocollo.CREDENZIALI_NON_FORNITE,apiKey));
  176.             esito.setClientAuthenticated(false);
  177.             esito.setClientIdentified(false);
  178.             if(wwwAuthenticateConfig!=null) {
  179.                 esito.setWwwAuthenticateErrorHeader(wwwAuthenticateConfig.buildWWWAuthenticateHeaderValue_notFound());
  180.             }
  181.             return esito;
  182.         }
  183.         if( apiKey==null || "".equals(apiKey) ){
  184.             esito.setErroreIntegrazione(IntegrationFunctionError.AUTHENTICATION_CREDENTIALS_NOT_FOUND, ErroriIntegrazione.ERRORE_402_AUTENTICAZIONE_FALLITA.getErrore402_AutenticazioneFallitaPrincipal(CostantiProtocollo.CREDENZIALI_NON_FORNITE,apiKey));
  185.             esito.setClientAuthenticated(false);
  186.             esito.setClientIdentified(false);
  187.             if(wwwAuthenticateConfig!=null) {
  188.                 esito.setWwwAuthenticateErrorHeader(wwwAuthenticateConfig.buildWWWAuthenticateHeaderValue_notFound());
  189.             }
  190.             return esito;
  191.         }
  192.        
  193.         String appId = null;
  194.         if(this.appId) {
  195.             try {
  196.                 appId = ApiKeyUtilities.getKey(false, this.header, this.cookie, this.queryParameter,
  197.                         this.nomeHeaderAppId, this.nomeCookieAppId, this.nomeQueryParameterAppId,
  198.                         datiInvocazione!=null ? datiInvocazione.getInfoConnettoreIngresso() : null, this.getPddContext(), true,
  199.                         fullCredential);
  200.             }catch(Exception e) {
  201.                 if(this.logError) {
  202.                     OpenSPCoop2Logger.getLoggerOpenSPCoopCore().error("AutenticazioneApiKey (AppId) non riuscita",e);
  203.                 }
  204.                 esito.setErroreIntegrazione(IntegrationFunctionError.AUTHENTICATION_CREDENTIALS_NOT_FOUND, ErroriIntegrazione.ERRORE_402_AUTENTICAZIONE_FALLITA.getErrore402_AutenticazioneFallitaPrincipal(CostantiProtocollo.CREDENZIALI_NON_FORNITE,appId));
  205.                 esito.setClientAuthenticated(false);
  206.                 esito.setClientIdentified(false);
  207.                 esito.setFullCredential(fullCredential.toString());
  208.                 if(wwwAuthenticateConfig!=null) {
  209.                     esito.setWwwAuthenticateErrorHeader(wwwAuthenticateConfig.buildWWWAuthenticateHeaderValue_notFound());
  210.                 }
  211.                 return esito;
  212.             }
  213.             if( appId==null || "".equals(appId) ){
  214.                 esito.setErroreIntegrazione(IntegrationFunctionError.AUTHENTICATION_CREDENTIALS_NOT_FOUND, ErroriIntegrazione.ERRORE_402_AUTENTICAZIONE_FALLITA.getErrore402_AutenticazioneFallitaPrincipal(CostantiProtocollo.CREDENZIALI_NON_FORNITE,appId));
  215.                 esito.setClientAuthenticated(false);
  216.                 esito.setClientIdentified(false);
  217.                 esito.setFullCredential(fullCredential.toString());
  218.                 if(wwwAuthenticateConfig!=null) {
  219.                     esito.setWwwAuthenticateErrorHeader(wwwAuthenticateConfig.buildWWWAuthenticateHeaderValue_notFound());
  220.                 }
  221.                 return esito;
  222.             }
  223.         }
  224.        
  225.         // per conoscere la credenziale passata anche in caso di autenticazione fallita
  226.         esito.setFullCredential(fullCredential.toString());
  227.        
  228.         String identitaAutenticata = null;
  229.         String password = null;
  230.         try {
  231.             if(this.appId) {
  232.                 identitaAutenticata = appId;
  233.                 password = ApiKeyUtilities.decodeMultipleApiKey(apiKey);
  234.             }
  235.             else {
  236.                 String [] decodedApiKey = ApiKeyUtilities.decodeApiKey(apiKey);
  237.                 identitaAutenticata = decodedApiKey[0];
  238.                 password = decodedApiKey[1];
  239.             }
  240.         }catch(Exception e) {
  241.             if(this.logError) {
  242.                 OpenSPCoop2Logger.getLoggerOpenSPCoopCore().error("AutenticazioneApiKey (appId:"+this.appId+") fallita",e);
  243.             }
  244.             esito.setErroreIntegrazione(IntegrationFunctionError.AUTHENTICATION_INVALID_CREDENTIALS, ErroriIntegrazione.ERRORE_402_AUTENTICAZIONE_FALLITA.getErrore402_AutenticazioneFallitaBasic(CostantiProtocollo.CREDENZIALI_FORNITE_NON_CORRETTE,identitaAutenticata,apiKey));
  245.             esito.setClientAuthenticated(false);
  246.             esito.setClientIdentified(false);
  247.             if(wwwAuthenticateConfig!=null) {
  248.                 esito.setWwwAuthenticateErrorHeader(wwwAuthenticateConfig.buildWWWAuthenticateHeaderValue_invalid());
  249.             }
  250.             return esito;
  251.         }
  252.                
  253.         CryptConfig cryptConfigApplicativi = op2Properties.getCryptConfigAutenticazioneApplicativi();
  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.         IDServizioApplicativo idServizioApplicativo = null;
  260.         try{
  261.             ConfigurazionePdDManager configurazionePdDManager = datiInvocazione!=null ? ConfigurazionePdDManager.getInstance(datiInvocazione.getState()) : ConfigurazionePdDManager.getInstance();
  262.             idServizioApplicativo = configurazionePdDManager.
  263.                         getIdServizioApplicativoByCredenzialiApiKey(identitaAutenticata, password, this.appId, cryptConfigApplicativi);
  264.             if(idServizioApplicativo!=null && soggettoFruitore==null) {
  265.                 soggettoFruitore = idServizioApplicativo.getIdSoggettoProprietario();
  266.             }
  267.         }catch(Exception e){
  268.             if(this.logError) {
  269.                 OpenSPCoop2Logger.getLoggerOpenSPCoopCore().error("AutenticazioneApiKey (appId:"+this.appId+") non riuscita",e);
  270.             }
  271.             esito.setErroreIntegrazione(IntegrationFunctionError.INTERNAL_REQUEST_ERROR, ErroriIntegrazione.ERRORE_5XX_GENERICO_PROCESSAMENTO_MESSAGGIO.
  272.                     get5XX_ErroreProcessamento(CodiceErroreIntegrazione.CODICE_536_CONFIGURAZIONE_NON_DISPONIBILE));
  273.             esito.setClientIdentified(false);
  274.             esito.setEccezioneProcessamento(e);
  275.             return esito;
  276.         }
  277.        
  278.         if(idServizioApplicativo == null){
  279.             esito.setErroreIntegrazione(IntegrationFunctionError.AUTHENTICATION_INVALID_CREDENTIALS, ErroriIntegrazione.ERRORE_402_AUTENTICAZIONE_FALLITA.getErrore402_AutenticazioneFallitaBasic(CostantiProtocollo.CREDENZIALI_FORNITE_NON_CORRETTE,identitaAutenticata,apiKey));
  280.             esito.setClientAuthenticated(false);
  281.             esito.setClientAuthenticated(false);
  282.             esito.setClientIdentified(false);
  283.             if(wwwAuthenticateConfig!=null) {
  284.                 esito.setWwwAuthenticateErrorHeader(wwwAuthenticateConfig.buildWWWAuthenticateHeaderValue_invalid());
  285.             }
  286.             return esito;
  287.         }
  288.         else if(idServizioApplicativo.getIdSoggettoProprietario().equals(soggettoFruitore)==false) {
  289.             esito.setErroreIntegrazione(IntegrationFunctionError.AUTHENTICATION_INVALID_CREDENTIALS,
  290.                     ErroriIntegrazione.ERRORE_402_AUTENTICAZIONE_FALLITA.
  291.                         getErrore402_AutenticazioneFallitaBasic("soggetto proprietario ("+idServizioApplicativo.getIdSoggettoProprietario()+") dell'applicativo identificato ("+idServizioApplicativo.getNome()+") differente dal soggetto proprietario della porta invocata ("+soggettoFruitore+")",identitaAutenticata,apiKey));
  292.             esito.setClientAuthenticated(false);
  293.             esito.setClientAuthenticated(false);
  294.             esito.setClientIdentified(false);
  295.             if(wwwAuthenticateConfig!=null) {
  296.                 esito.setWwwAuthenticateErrorHeader(wwwAuthenticateConfig.buildWWWAuthenticateHeaderValue_invalid());
  297.             }
  298.             return esito;
  299.         }
  300.         else {
  301.             esito.setClientAuthenticated(true);
  302.             esito.setClientIdentified(true);
  303.             esito.setIdServizioApplicativo(idServizioApplicativo);
  304.         }
  305.        
  306.         return esito;
  307.        
  308.     }

  309.     @Override
  310.     public void cleanPostAuth(OpenSPCoop2Message message) throws AutenticazioneException {
  311.        
  312.         AutenticazioneUtils.finalizeProcessApiKey(message,
  313.                 this.header, this.cookie, this.queryParameter,
  314.                 this.nomeHeaderApiKey, this.nomeCookieApiKey, this.nomeQueryParameterApiKey,
  315.                 this.cleanApiKey);
  316.        
  317.         if(this.appId) {
  318.             AutenticazioneUtils.finalizeProcessApiKey(message,
  319.                     this.header, this.cookie, this.queryParameter,
  320.                     this.nomeHeaderAppId, this.nomeCookieAppId, this.nomeQueryParameterAppId,
  321.                     this.cleanAppId);
  322.         }
  323.        
  324.     }
  325. }