

**Ti presentiamo una nuova esperienza di console per AWS WAF**

Ora puoi utilizzare l'esperienza aggiornata per accedere alle AWS WAF funzionalità da qualsiasi punto della console. Per ulteriori dettagli, consulta [Lavorare con la console](https://docs.aws.amazon.com/waf/latest/developerguide/working-with-console.html). 

Le traduzioni sono generate tramite traduzione automatica. In caso di conflitto tra il contenuto di una traduzione e la versione originale in Inglese, quest'ultima prevarrà.

# Esempi di codice per l'SDK AWS WAF mobile
<a name="waf-mobile-sdk-coding-examples"></a>

Questa sezione fornisce esempi di codice per l'utilizzo dell'SDK per dispositivi mobili. 

## Inizializzazione del fornitore di token e ottenimento dei token
<a name="waf-mobile-sdk-coding-basic"></a>

Si avvia l'istanza del provider di token utilizzando un oggetto di configurazione. Quindi puoi recuperare i token utilizzando le operazioni disponibili. Di seguito vengono illustrati i componenti di base del codice richiesto.

------
#### [ iOS ]

```
let url: URL = URL(string: "protection pack (web ACL) integration URL")!
let configuration = WAFConfiguration(applicationIntegrationUrl: url, domainName: "Domain name")
let tokenProvider = WAFTokenProvider(configuration)

//onTokenReady can be add as an observer for UIApplication.willEnterForegroundNotification
self.tokenProvider.onTokenReady() { token, error in
	if let token = token {
	//token available
	}

	if let error = error {
	//error occurred after exhausting all retries
	}
}

//getToken()
let token = tokenProvider.getToken()
```

------
#### [ Android ]

Esempio di Java:

```
String applicationIntegrationURL = "protection pack (web ACL) integration URL";
//Or
URL applicationIntegrationURL = new URL("protection pack (web ACL) integration URL");

String domainName = "Domain name";

WAFConfiguration configuration = WAFConfiguration.builder().applicationIntegrationURL(applicationIntegrationURL).domainName(domainName).build();
WAFTokenProvider tokenProvider = new WAFTokenProvider(Application context, configuration);

// implement a token result callback
WAFTokenResultCallback callback = (wafToken, error) -> {
	if (wafToken != null) {
	// token available
	} else {  
	// error occurred in token refresh  
	}
};

// Add this callback to application creation or activity creation where token will be used
tokenProvider.onTokenReady(callback);

// Once you have token in token result callback
// if background refresh is enabled you can call getToken() from same tokenprovider object
// if background refresh is disabled you can directly call getToken()(blocking call) for new token
WAFToken token = tokenProvider.getToken();
```

Esempio di Kotlin:

```
import com.amazonaws.waf.mobilesdk.token.WAFConfiguration
import com.amazonaws.waf.mobilesdk.token.WAFTokenProvider

private lateinit var wafConfiguration: WAFConfiguration
private lateinit var wafTokenProvider: WAFTokenProvider

private val WAF_INTEGRATION_URL = "protection pack (web ACL) integration URL"
private val WAF_DOMAIN_NAME = "Domain name"

fun initWaf() {
	// Initialize the tokenprovider instance
	val applicationIntegrationURL = URL(WAF_INTEGRATION_URL)
	wafConfiguration =
		WAFConfiguration.builder().applicationIntegrationURL(applicationIntegrationURL)
			.domainName(WAF_DOMAIN_NAME).backgroundRefreshEnabled(true).build()
	wafTokenProvider = WAFTokenProvider(getApplication(), wafConfiguration)
	
		// getToken from tokenprovider object
		println("WAF: "+ wafTokenProvider.token.value)
	
		// implement callback for where token will be used
		wafTokenProvider.onTokenReady {
			wafToken, sdkError ->
		run {
			println("WAF Token:" + wafToken.value)
		}
	}
}
```

------

## Consentire all'SDK di fornire il cookie del token nelle richieste HTTP
<a name="waf-mobile-sdk-coding-auto-token-cookie"></a>

In caso `setTokenCookie` affermativo`TRUE`, il fornitore del token include il cookie del token nelle richieste web a tutte le località nel percorso specificato in`tokenCookiePath`. Per impostazione predefinita, `setTokenCookie` è `TRUE` ed `tokenCookiePath` è`/`. 

È possibile restringere l'ambito delle richieste che includono un cookie token specificando il percorso del cookie del token, `/web/login` ad esempio. Se lo fai, controlla che AWS WAF le tue regole non controllino la presenza di token nelle richieste che invii ad altri percorsi. Quando utilizzi il gruppo di `AWSManagedRulesACFPRuleSet` regole, configuri i percorsi di registrazione e creazione dell'account e il gruppo di regole verifica la presenza di token nelle richieste inviate a tali percorsi. Per ulteriori informazioni, consulta [Aggiungere il gruppo di regole gestite ACFP all'ACL Web](waf-acfp-rg-using.md). Allo stesso modo, quando si utilizza il gruppo di `AWSManagedRulesATPRuleSet` regole, si configura il percorso di accesso e il gruppo di regole verifica la presenza di token nelle richieste inviate a quel percorso. Per ulteriori informazioni, consulta [Aggiungere il gruppo di regole gestite ATP al pacchetto di protezione (Web ACL)](waf-atp-rg-using.md). 

------
#### [ iOS ]

In caso `setTokenCookie` `TRUE` affermativo, il fornitore del AWS WAF token memorizza il token in un file `HTTPCookieStorage.shared` e lo include automaticamente nelle richieste al dominio specificato in`WAFConfiguration`.

```
let request = URLRequest(url: URL(string: domainEndpointUrl)!)
//The token cookie is set automatically as cookie header
let task = URLSession.shared.dataTask(with: request) { data, urlResponse, error  in
}.resume()
```

------
#### [ Android ]

In caso `setTokenCookie` `TRUE` affermativo, il provider del token archivia il AWS WAF token in un'`CookieHandler`istanza condivisa a livello di applicazione. Il provider di token include automaticamente il cookie nelle richieste al dominio specificato dall'utente`WAFConfiguration`.

Esempio di Java:

```
URL url = new URL("Domain name");
//The token cookie is set automatically as cookie header
HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
connection.getResponseCode();
```

Esempio di Kotlin:

```
val url = URL("Domain name")
//The token cookie is set automatically as cookie header
val connection = (url.openConnection() as HttpsURLConnection)
connection.responseCode
```

Se hai già inizializzato l'istanza `CookieHandler` predefinita, il fornitore del token la utilizzerà per gestire i cookie. In caso contrario, il fornitore del token inizializzerà una nuova `CookieManager` istanza con il AWS WAF token `CookiePolicy.ACCEPT_ORIGINAL_SERVER` e quindi imposterà questa nuova istanza come istanza predefinita in. `CookieHandler`

Il codice seguente mostra come l'SDK inizializza il gestore dei cookie e il gestore dei cookie quando non sono disponibili nell'app. 

Esempio di Java:

```
CookieManager cookieManager = (CookieManager) CookieHandler.getDefault();
if (cookieManager == null) {
	// Cookie manager is initialized with CookiePolicy.ACCEPT_ORIGINAL_SERVER
	cookieManager = new CookieManager();
	CookieHandler.setDefault(cookieManager);
}
```

Esempio di Kotlin:

```
var cookieManager = CookieHandler.getDefault() as? CookieManager
if (cookieManager == null) {
	// Cookie manager is initialized with CookiePolicy.ACCEPT_ORIGINAL_SERVER
	cookieManager = CookieManager()
	CookieHandler.setDefault(cookieManager)
}
```

------

## Fornitura manuale del cookie token nelle richieste HTTP
<a name="waf-mobile-sdk-coding-manual-token-cookie"></a>

Se lo `setTokenCookie` imposti`FALSE`, devi fornire il cookie token manualmente, come intestazione della richiesta Cookie HTTP, nelle tue richieste all'endpoint protetto. Il codice seguente mostra come eseguire questa operazione.

------
#### [ iOS ]

```
var request = URLRequest(url: wafProtectedEndpoint)
request.setValue("aws-waf-token=token from token provider", forHTTPHeaderField: "Cookie")
request.httpShouldHandleCookies = true
URLSession.shared.dataTask(with: request) { data, response, error in }
```

------
#### [ Android ]

Esempio di Java:

```
URL url = new URL("Domain name");
HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
String wafTokenCookie = "aws-waf-token=token from token provider";
connection.setRequestProperty("Cookie", wafTokenCookie);
connection.getInputStream();
```

Esempio di Kotlin:

```
val url = URL("Domain name")
val connection = (url.openConnection() as HttpsURLConnection)
val wafTokenCookie = "aws-waf-token=token from token provider"
connection.setRequestProperty("Cookie", wafTokenCookie)
connection.inputStream
```

------