Abilitazione dell'accesso personalizzato da parte di un broker di identità alla AWS console - AWS Identity and Access Management

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à.

Abilitazione dell'accesso personalizzato da parte di un broker di identità alla AWS console

Puoi scrivere ed eseguire codice per creare un URL che permette agli utenti che accedono alla rete dell'organizzazione di accedere in modo sicuro alla AWS Management Console. L'URL include un token di accesso che viene inviato AWS e utilizzato per autenticare l'utente. AWS La sessione console risultante potrebbe includere una distinta AccessKeyId a causa della federazione. Per tracciare l'utilizzo delle chiavi di accesso per l'accesso alla federazione tramite CloudTrail eventi correlati, vedi Registrazione delle chiamate IAM e AWS STS API con AWS CloudTrail e accedi agli eventi.AWS Management Console

Nota

Se la tua organizzazione usa un provider di identità (IdP) compatibile con SAML, puoi configurare l'accesso alla console senza la necessità di scrivere codice. Ciò è possibile con provider come Microsoft Active Directory Federation Services oppure Shibboleth open source. Per informazioni dettagliate, vedi Consentire agli utenti federati SAML 2.0 di accedere a AWS Management Console.

Per consentire agli utenti dell'organizzazione di accedere a AWS Management Console, è possibile creare un broker di identità personalizzato che esegua i seguenti passaggi:

  1. Verifica che l'utente sia autenticato dal sistema di identità locale.

  2. Chiamate le operazioni AWS Security Token Service AssumeRole(AWS STS) (consigliato) o GetFederationTokenAPI per ottenere credenziali di sicurezza temporanee per l'utente. Per informazioni sui diversi metodi che si possono utilizzare per assumere un ruolo, consulta Utilizzo di ruoli IAM. Per informazioni su come passare i tag di sessione facoltativi quando si ottengono le credenziali di sicurezza, consulta Passare i tag di sessione AWS STS.

    • Se usi una delle operazioni API AssumeRole* per ottenere credenziali di sicurezza temporanee per un ruolo, puoi includere il parametro DurationSeconds nella chiamata. Questo parametro specifica la durata della sessione del ruolo, da 900 secondi (15 minuti) fino all'impostazione di durata massima della sessione per il ruolo. Quando si utilizza DurationSeconds in un'operazione AssumeRole*, è necessario chiamarlo come un utente IAM con credenziali a lungo termine. In caso contrario, la chiamata all'endpoint di federazione nella fase 3 ha esito negativo. Per informazioni su come visualizzare o modificare il valore massimo per un ruolo, consulta Visualizzazione dell'impostazione di durata massima della sessione per un ruolo.

    • Se usi l'operazione API GetFederationToken per ottenere le credenziali, puoi includere il parametro DurationSeconds nella chiamata. Questo parametro specifica la durata della sessione del ruolo. Il valore può variare da 900 secondi (15 minuti) a 129.600 secondi (36 ore). Puoi effettuare questa chiamata API solo utilizzando le credenziali di AWS sicurezza a lungo termine di un utente IAM. Puoi anche effettuare queste chiamate utilizzando Utente root dell'account AWS le credenziali, ma non è consigliabile. Se effettui la chiamata come utente root, la sessione di default dura un'ora. In alternativa, puoi specificare una sessione con durata compresa tra 900 secondi (15 minuti) e 3.600 secondi (un'ora).

  3. Chiama l'endpoint AWS della federazione e fornisci le credenziali di sicurezza temporanee per richiedere un token di accesso.

  4. Crea un URL per la console che include il token:

    • Se usi una delle operazioni API AssumeRole* nell'URL, puoi includere il parametro HTTP SessionDuration. Questo parametro specifica la durata della sessione della console, da 900 secondi (15 minuti) a 43.200 secondi (12 ore).

    • Se usi l'operazione API GetFederationToken nell'URL, puoi includere il parametro DurationSeconds. Questo parametro specifica la durata della sessione della console federata. Il valore può variare da 900 secondi (15 minuti) a 129.600 secondi (36 ore).

      Nota
      • Non usare il parametro HTTP SessionDuration se hai ottenuto le credenziali temporanee con GetFederationToken. Ciò causerebbe un errore dell'operazione.

      • L'utilizzo delle credenziali perché un ruolo assuma un ruolo diverso viene chiamato concatenamento dei ruoli. Quando si utilizza il concatenamento dei ruoli, le nuove credenziali sono limitate a una durata massima di un'ora. Quando si utilizzano i ruoli per concedere autorizzazioni alle applicazioni eseguite su istanze EC2, tali applicazioni non sono soggette a questa limitazione.

  5. Fornisce l'URL all'utente o richiama l'URL per conto dell'utente.

L'URL fornito dall'endpoint di federazione è valido per 15 minuti dopo la creazione. Questo intervallo di tempo è diverso dalla durata (in secondi) della sessione delle credenziali di sicurezza temporanee associata all'URL. Queste credenziali sono valide per la durata specificata al momento della creazione, a partire dal momento in cui sono state create.

Importante

L'URL concede l'accesso alle tue AWS risorse tramite, AWS Management Console se hai abilitato le autorizzazioni nelle credenziali di sicurezza temporanee associate. Per questo motivo, devi trattare l'URL come segreto. Ti consigliamo di restituire l'URL attraverso un reindirizzamento sicuro, ad esempio usando un codice di stato della risposta HTTP 302 in una connessione SSL. Per ulteriori informazioni sul codice di stato della risposta HTTP 302, consulta RFC 2616, sezione 10.3.3.

Per completare queste attività, puoi utilizzare l'API di query HTTPS per AWS Identity and Access Management (IAM) e AWS Security Token Service (AWS STS). In alternativa, puoi utilizzare linguaggi di programmazione come Java, Ruby o C # con l'SDK AWS appropriato. Ognuno di questi metodi è descritto negli argomenti seguenti.

Puoi creare un URL che fornisca agli utenti federati l'accesso diretto a. AWS Management Console Questa attività utilizza le API di interrogazione IAM e AWS STS HTTPS. Per ulteriori informazioni su come effettuare richieste di query, consulta Effettuare richieste di query.

Nota

La procedura seguente contiene esempi di stringhe di testo. Per migliorare la leggibilità, sono state aggiunte interruzioni di riga in alcuni degli esempi più lunghi. Quando crei queste stringhe per l'uso, ometti le interruzioni di riga.

Per consentire a un utente federato di accedere alle tue risorse dal AWS Management Console
  1. Autentica l'utente nel sistema di identità e autorizzazione.

  2. Ottieni credenziali di sicurezza temporanee per l'utente. Le credenziali temporanee sono costituite da un ID chiave di accesso, una chiave di accesso segreta e un token di sessione. Per ulteriori informazioni sulla creazione di credenziali temporanee, consulta Credenziali di sicurezza temporanee in IAM.

    Per ottenere credenziali temporanee, chiamate l' AWS STS AssumeRoleAPI (scelta consigliata) o l'GetFederationTokenAPI. Per ulteriori informazioni sulle differenze tra queste operazioni API, consulta Comprendere le opzioni API per delegare in modo sicuro l'accesso all' AWS account nel blog sulla AWS sicurezza.

    Importante

    Quando utilizzi l'GetFederationTokenAPI per creare credenziali di sicurezza temporanee, devi specificare le autorizzazioni che le credenziali concedono all'utente che assume il ruolo. Per le operazioni API che iniziano con AssumeRole*, è necessario usare un ruolo IAM per assegnare le autorizzazioni. Per le altre operazioni API, il meccanismo varia a seconda dell'API. Per ulteriori dettagli, consulta Controllo delle autorizzazioni per le credenziali di sicurezza temporanee. Inoltre, se usi le operazioni API AssumeRole*, devi chiamarle come utente IAM con credenziali a lungo termine. In caso contrario, la chiamata all'endpoint di federazione nella fase 3 ha esito negativo.

  3. Dopo aver ottenuto le credenziali di sicurezza temporanee, integrale in una stringa di sessione JSON per scambiarle con un token di accesso. Nell'esempio seguente viene illustrato come codificare le credenziali. Sostituisci il testo segnaposto con i valori appropriati delle credenziali ricevute nella fase precedente.

    {"sessionId":"*** temporary access key ID ***", "sessionKey":"*** temporary secret access key ***", "sessionToken":"*** session token ***"}
  4. Effettuare la codifica tramite URL della stringa di sessione della fase precedente. Poiché le informazioni codificate sono informazioni sensibili, ti consigliamo di evitare l'uso di un servizio Web per la codifica. Usa invece una funzione o una caratteristica installata in locale nel kit di strumenti di sviluppo per codificare queste informazioni in modo sicuro. Puoi usare la funzione urllib.quote_plus in Python, la funzione URLEncoder.encode in Java o la funzione CGI.escape in Ruby. Consulta gli esempi più avanti in questo argomento.

  5. Nota

    AWS supporta le richieste POST qui.

    Infine, crea l'URL che gli utenti federati possono usare per accedere alla AWS Management Console. L'URL corrisponde all'URL dell'endpoint di federazione usato in Passo 5, con l'aggiunta dei parametri seguenti:

    ?Action = login &Issuer = *** the form-urlencoded URL for your internal sign-in page *** &Destination = *** the form-urlencoded URL to the desired AWS console page *** &SigninToken = *** the value of SigninToken received in the previous step ***
    Nota

    Le seguenti istruzioni in questa fase funzionano solo con utilizzando l'API GET.

    L'esempio seguente mostra l'aspetto dell'URL finale. L'URL è valido per 15 minuti dal momento della creazione. Le credenziali di sicurezza temporanee e la sessione della console incorporate nell'URL sono valide per la durata specificata nel parametro HTTP SessionDuration al momento della richiesta iniziale.

    https://signin.aws.amazon.com/federation ?Action=login &Issuer=https%3A%2F%2Fexample.com &Destination=https%3A%2F%2Fconsole.aws.amazon.com%2F &SigninToken=VCQgs5qZZt3Q6fn8Tr5EXAMPLEmLnwB7JjUc-SHwnUUWabcRdnWsi4DBn-dvC CZ85wrD0nmldUcZEXAMPLE-vXYH4Q__mleuF_W2BE5HYexbe9y4Of-kje53SsjNNecATfjIzpW1 WibbnH6YcYRiBoffZBGExbEXAMPLE5aiKX4THWjQKC6gg6alHu6JFrnOJoK3dtP6I9a6hi6yPgm iOkPZMmNGmhsvVxetKzr8mx3pxhHbMEXAMPLETv1pij0rok3IyCR2YVcIjqwfWv32HU2Xlj471u 3fU6uOfUComeKiqTGX974xzJOZbdmX_t_lLrhEXAMPLEDDIisSnyHGw2xaZZqudm4mo2uTDk9Pv 9l5K0ZCqIgEXAMPLEcA6tgLPykEWGUyH6BdSC6166n4M4JkXIQgac7_7821YqixsNxZ6rsrpzwf nQoS14O7R0eJCCJ684EXAMPLEZRdBNnuLbUYpz2Iw3vIN0tQgOujwnwydPscM9F7foaEK3jwMkg Apeb1-6L_OB12MZhuFxx55555EXAMPLEhyETEd4ZulKPdXHkgl6T9ZkIlHz2Uy1RUTUhhUxNtSQ nWc5xkbBoEcXqpoSIeK7yhje9Vzhd61AEXAMPLElbWeouACEMG6-Vd3dAgFYd6i5FYoyFrZLWvm 0LSG7RyYKeYN5VIzUk3YWQpyjP0RiT5KUrsUi-NEXAMPLExMOMdoODBEgKQsk-iu2ozh6r8bxwC RNhujg

Gli esempi seguenti mostrano come utilizzare Python a livello di programmazione per formulare un URL che conceda agli utenti federati l'accesso diretto alla AWS Management Console. Gli esempi sono due:

  • Federa tramite richieste GET a AWS

  • Federate tramite richieste POST a AWS

Entrambi gli esempi utilizzano l'AssumeRoleAPI AWS SDK for Python (Boto3)and per ottenere credenziali di sicurezza temporanee.

Utilizzo delle richieste GET

import urllib, json, sys import requests # 'pip install requests' import boto3 # AWS SDK for Python (Boto3) 'pip install boto3' # Step 1: Authenticate user in your own identity system. # Step 2: Using the access keys for an IAM user in your Account AWS, # call "AssumeRole" to get temporary access keys for the federated user # Note: Calls to AWS STS AssumeRole must be signed using the access key ID # and secret access key of an IAM user or using existing temporary credentials. # The credentials can be in Amazon EC2 instance metadata, in environment variables, # or in a configuration file, and will be discovered automatically by the # client('sts') function. For more information, see the Python SDK docs: # http://boto3.readthedocs.io/en/latest/reference/services/sts.html # http://boto3.readthedocs.io/en/latest/reference/services/sts.html#STS.Client.assume_role sts_connection = boto3.client('sts') assumed_role_object = sts_connection.assume_role( RoleArn="arn:aws:iam::account-id:role/ROLE-NAME", RoleSessionName="AssumeRoleSession", ) # Step 3: Format resulting temporary credentials into JSON url_credentials = {} url_credentials['sessionId'] = assumed_role_object.get('Credentials').get('AccessKeyId') url_credentials['sessionKey'] = assumed_role_object.get('Credentials').get('SecretAccessKey') url_credentials['sessionToken'] = assumed_role_object.get('Credentials').get('SessionToken') json_string_with_temp_credentials = json.dumps(url_credentials) # Step 4. Make request to AWS federation endpoint to get sign-in token. Construct the parameter string with # the sign-in action request, a 12-hour session duration, and the JSON document with temporary credentials # as parameters. request_parameters = "?Action=getSigninToken" request_parameters += "&SessionDuration=43200" if sys.version_info[0] < 3: def quote_plus_function(s): return urllib.quote_plus(s) else: def quote_plus_function(s): return urllib.parse.quote_plus(s) request_parameters += "&Session=" + quote_plus_function(json_string_with_temp_credentials) request_url = "https://signin.aws.amazon.com/federation" + request_parameters r = requests.get(request_url) # Returns a JSON document with a single element named SigninToken. signin_token = json.loads(r.text) # Step 5: Create URL where users can use the sign-in token to sign in to # the console. This URL must be used within 15 minutes after the # sign-in token was issued. request_parameters = "?Action=login" request_parameters += "&Issuer=Example.org" request_parameters += "&Destination=" + quote_plus_function("https://console.aws.amazon.com/") request_parameters += "&SigninToken=" + signin_token["SigninToken"] request_url = "https://signin.aws.amazon.com/federation" + request_parameters # Send final URL to stdout print (request_url)

Utilizzo delle richieste POST

import urllib, json, sys import requests # 'pip install requests' import boto3 # AWS SDK for Python (Boto3) 'pip install boto3' import os from selenium import webdriver # 'pip install selenium', 'brew install chromedriver' # Step 1: Authenticate user in your own identity system. # Step 2: Using the access keys for an IAM user in your A Account AWS, # call "AssumeRole" to get temporary access keys for the federated user # Note: Calls to AWS STS AssumeRole must be signed using the access key ID # and secret access key of an IAM user or using existing temporary credentials. # The credentials can be in Amazon EC2 instance metadata, in environment variables, # or in a configuration file, and will be discovered automatically by the # client('sts') function. For more information, see the Python SDK docs: # http://boto3.readthedocs.io/en/latest/reference/services/sts.html # http://boto3.readthedocs.io/en/latest/reference/services/sts.html#STS.Client.assume_role if sys.version_info[0] < 3: def quote_plus_function(s): return urllib.quote_plus(s) else: def quote_plus_function(s): return urllib.parse.quote_plus(s) sts_connection = boto3.client('sts') assumed_role_object = sts_connection.assume_role( RoleArn="arn:aws:iam::account-id:role/ROLE-NAME", RoleSessionName="AssumeRoleDemoSession", ) # Step 3: Format resulting temporary credentials into JSON url_credentials = {} url_credentials['sessionId'] = assumed_role_object.get('Credentials').get('AccessKeyId') url_credentials['sessionKey'] = assumed_role_object.get('Credentials').get('SecretAccessKey') url_credentials['sessionToken'] = assumed_role_object.get('Credentials').get('SessionToken') json_string_with_temp_credentials = json.dumps(url_credentials) # Step 4. Make request to AWS federation endpoint to get sign-in token. Construct the parameter string with # the sign-in action request, a 12-hour session duration, and the JSON document with temporary credentials # as parameters. request_parameters = {} request_parameters['Action'] = 'getSigninToken' request_parameters['SessionDuration'] = '43200' request_parameters['Session'] = json_string_with_temp_credentials request_url = "https://signin.aws.amazon.com/federation" r = requests.post( request_url, data=request_parameters) # Returns a JSON document with a single element named SigninToken. signin_token = json.loads(r.text) # Step 5: Create a POST request where users can use the sign-in token to sign in to # the console. The POST request must be made within 15 minutes after the # sign-in token was issued. request_parameters = {} request_parameters['Action'] = 'login' request_parameters['Issuer']='Example.org' request_parameters['Destination'] = 'https://console.aws.amazon.com/' request_parameters['SigninToken'] =signin_token['SigninToken'] jsrequest = ''' var form = document.createElement('form'); form.method = 'POST'; form.action = '{request_url}'; request_parameters = {request_parameters} for (var param in request_parameters) {{ if (request_parameters.hasOwnProperty(param)) {{ const hiddenField = document.createElement('input'); hiddenField.type = 'hidden'; hiddenField.name = param; hiddenField.value = request_parameters[param]; form.appendChild(hiddenField); }} }} document.body.appendChild(form); form.submit(); '''.format(request_url=request_url, request_parameters=request_parameters) driver = webdriver.Chrome() driver.execute_script(jsrequest);

L'esempio seguente mostra come usare Java a livello di programmazione per creare un URL che concede agli utenti federati l'accesso diretto alla AWS Management Console. Nel frammento di codice seguente viene utilizzato AWS SDK for Java.

import java.net.URLEncoder; import java.net.URL; import java.net.URLConnection; import java.io.BufferedReader; import java.io.InputStreamReader; // Available at http://www.json.org/java/index.html import org.json.JSONObject; import com.amazonaws.auth.AWSCredentials; import com.amazonaws.auth.BasicAWSCredentials; import com.amazonaws.services.securitytoken.AWSSecurityTokenServiceClient; import com.amazonaws.services.securitytoken.model.Credentials; import com.amazonaws.services.securitytoken.model.GetFederationTokenRequest; import com.amazonaws.services.securitytoken.model.GetFederationTokenResult; /* Calls to AWS STS API operations must be signed using the access key ID and secret access key of an IAM user or using existing temporary credentials. The credentials should not be embedded in code. For this example, the code looks for the credentials in a standard configuration file. */ AWSCredentials credentials = new PropertiesCredentials( AwsConsoleApp.class.getResourceAsStream("AwsCredentials.properties")); AWSSecurityTokenServiceClient stsClient = new AWSSecurityTokenServiceClient(credentials); GetFederationTokenRequest getFederationTokenRequest = new GetFederationTokenRequest(); getFederationTokenRequest.setDurationSeconds(1800); getFederationTokenRequest.setName("UserName"); // A sample policy for accessing Amazon Simple Notification Service (Amazon SNS) in the console. String policy = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Action\":\"sns:*\"," + "\"Effect\":\"Allow\",\"Resource\":\"*\"}]}"; getFederationTokenRequest.setPolicy(policy); GetFederationTokenResult federationTokenResult = stsClient.getFederationToken(getFederationTokenRequest); Credentials federatedCredentials = federationTokenResult.getCredentials(); // The issuer parameter specifies your internal sign-in // page, for example https://mysignin.internal.mycompany.com/. // The console parameter specifies the URL to the destination console of the // AWS Management Console. This example goes to Amazon SNS. // The signin parameter is the URL to send the request to. String issuerURL = "https://mysignin.internal.mycompany.com/"; String consoleURL = "https://console.aws.amazon.com/sns"; String signInURL = "https://signin.aws.amazon.com/federation"; // Create the sign-in token using temporary credentials, // including the access key ID, secret access key, and session token. String sessionJson = String.format( "{\"%1$s\":\"%2$s\",\"%3$s\":\"%4$s\",\"%5$s\":\"%6$s\"}", "sessionId", federatedCredentials.getAccessKeyId(), "sessionKey", federatedCredentials.getSecretAccessKey(), "sessionToken", federatedCredentials.getSessionToken()); // Construct the sign-in request with the request sign-in token action, a // 12-hour console session duration, and the JSON document with temporary // credentials as parameters. String getSigninTokenURL = signInURL + "?Action=getSigninToken" + "&DurationSeconds=43200" + "&SessionType=json&Session=" + URLEncoder.encode(sessionJson,"UTF-8"); URL url = new URL(getSigninTokenURL); // Send the request to the AWS federation endpoint to get the sign-in token URLConnection conn = url.openConnection (); BufferedReader bufferReader = new BufferedReader(new InputStreamReader(conn.getInputStream())); String returnContent = bufferReader.readLine(); String signinToken = new JSONObject(returnContent).getString("SigninToken"); String signinTokenParameter = "&SigninToken=" + URLEncoder.encode(signinToken,"UTF-8"); // The issuer parameter is optional, but recommended. Use it to direct users // to your sign-in page when their session expires. String issuerParameter = "&Issuer=" + URLEncoder.encode(issuerURL, "UTF-8"); // Finally, present the completed URL for the AWS console session to the user String destinationParameter = "&Destination=" + URLEncoder.encode(consoleURL,"UTF-8"); String loginURL = signInURL + "?Action=login" + signinTokenParameter + issuerParameter + destinationParameter;

L'esempio seguente mostra come usare Ruby a livello di programmazione per creare un URL che concede agli utenti federati l'accesso diretto alla AWS Management Console. In questo frammento di codice viene utilizzato AWS SDK for Ruby.

require 'rubygems' require 'json' require 'open-uri' require 'cgi' require 'aws-sdk' # Create a new STS instance # # Note: Calls to AWS STS API operations must be signed using an access key ID # and secret access key. The credentials can be in EC2 instance metadata # or in environment variables and will be automatically discovered by # the default credentials provider in the AWS Ruby SDK. sts = Aws::STS::Client.new() # The following call creates a temporary session that returns # temporary security credentials and a session token. # The policy grants permissions to work # in the AWS SNS console. session = sts.get_federation_token({ duration_seconds: 1800, name: "UserName", policy: "{\"Version\":\"2012-10-17\",\"Statement\":{\"Effect\":\"Allow\",\"Action\":\"sns:*\",\"Resource\":\"*\"}}", }) # The issuer value is the URL where users are directed (such as # to your internal sign-in page) when their session expires. # # The console value specifies the URL to the destination console. # This example goes to the Amazon SNS console. # # The sign-in value is the URL of the AWS STS federation endpoint. issuer_url = "https://mysignin.internal.mycompany.com/" console_url = "https://console.aws.amazon.com/sns" signin_url = "https://signin.aws.amazon.com/federation" # Create a block of JSON that contains the temporary credentials # (including the access key ID, secret access key, and session token). session_json = { :sessionId => session.credentials[:access_key_id], :sessionKey => session.credentials[:secret_access_key], :sessionToken => session.credentials[:session_token] }.to_json # Call the federation endpoint, passing the parameters # created earlier and the session information as a JSON block. # The request returns a sign-in token that's valid for 15 minutes. # Signing in to the console with the token creates a session # that is valid for 12 hours. get_signin_token_url = signin_url + "?Action=getSigninToken" + "&SessionType=json&Session=" + CGI.escape(session_json) returned_content = URI.parse(get_signin_token_url).read # Extract the sign-in token from the information returned # by the federation endpoint. signin_token = JSON.parse(returned_content)['SigninToken'] signin_token_param = "&SigninToken=" + CGI.escape(signin_token) # Create the URL to give to the user, which includes the # sign-in token and the URL of the console to open. # The "issuer" parameter is optional but recommended. issuer_param = "&Issuer=" + CGI.escape(issuer_url) destination_param = "&Destination=" + CGI.escape(console_url) login_url = signin_url + "?Action=login" + signin_token_param + issuer_param + destination_param