Esempi di codice per AWS WAF cellulare SDK - AWS WAF, AWS Firewall Manager e AWS Shield Advanced

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 AWS WAF cellulare SDK

Questa sezione fornisce esempi di codice per l'utilizzo del cellulareSDK.

Inizializzazione del fornitore di token e ottenimento dei token

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: "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 = "Web ACL integration URL"; //Or URL applicationIntegrationURL = new URL("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 = "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) } } }

In caso setTokenCookie affermativoTRUE, il fornitore del token include il cookie del token nelle richieste Web a tutte le posizioni nel percorso specificato intokenCookiePath. 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, verifica che il tuo AWS WAF le regole non controllano la presenza di token nelle richieste inviate ad altri percorsi. Quando si utilizza il gruppo di AWSManagedRulesACFPRuleSet regole, si configurano 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 ACFP gestito al tuo Web ACL. 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 ATP gestito al tuo Web ACL.

iOS

Quando setTokenCookie è cosìTRUE, il fornitore di token memorizza il AWS WAF token in a HTTPCookieStorage.shared e include automaticamente il cookie nelle richieste al dominio specificato inWAFConfiguration.

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

Quando setTokenCookie è cosìTRUE, il fornitore del token memorizza il AWS WAF token in un'CookieHandleristanza condivisa a livello di applicazione. Il fornitore di token include automaticamente il cookie nelle richieste al dominio specificato inWAFConfiguration.

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 imposta questa nuova istanza come istanza predefinita inCookieHandler.

Il codice seguente mostra come 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) }

Se lo impostiFALSE, setTokenCookie devi fornire il cookie token manualmente, come intestazione della HTTP richiesta Cookie, nelle 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