AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • Início
  • system&network
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • Início
  • system&network
    • Recentes
    • Highest score
    • tags
  • Ubuntu
    • Recentes
    • Highest score
    • tags
  • Unix
    • Recentes
    • tags
  • DBA
    • Recentes
    • tags
  • Computer
    • Recentes
    • tags
  • Coding
    • Recentes
    • tags
Início / server / Perguntas / 1179416
Accepted
Franck Dernoncourt
Franck Dernoncourt
Asked: 2025-04-19 06:38:53 +0800 CST2025-04-19 06:38:53 +0800 CST 2025-04-19 06:38:53 +0800 CST

Como posso alterar a duração da validade de um token obtido com `az account get-access-token`?

  • 772

Eu uso um token obtido com az account get-access-tokenpara implantar GPTs ajustados no Azure, atualizá-los (por exemplo, alterando sua taxa máxima de acerto) ou removê-los.

Li em https://learn.microsoft.com/en-us/cli/azure/account?view=azure-cli-latest :

az account get-access-token: Obtenha um token para que os utilitários acessem o Azure.

O token será válido por pelo menos 5 minutos e, no máximo, 60 minutos. Se o argumento de assinatura não for especificado, a conta corrente será usada.

Atualmente, os tokens que obtenho são válidos por 15 minutos.

Como posso alterar a duração da validade de um token obtido com az account get-access-token?

azure
  • 1 1 respostas
  • 87 Views

1 respostas

  • Voted
  1. Best Answer
    Franck Dernoncourt
    2025-04-19T11:38:05+08:002025-04-19T11:38:05+08:00

    Como solução alternativa, é possível efetuar login na Interface de Linha de Comando (CLI) do Azure por meio de az logine obter um token com o código Python abaixo. az loginpermaneceu conectado por mais tempo do que a duração da validade do token obtido com az account get-access-token, então o código Python solicita outro token quando o token está próximo de expirar.

    Para instalar a Interface de Linha de Comando (CLI) do Azure no Ubuntu:

    curl -sL https://aka.ms/InstallAzureCLIDeb | sudo bash
    

    Em seguida, faça login via az login. Em seguida, execute este script Python:

    import subprocess
    import json
    import os
    import sys
    from datetime import datetime, timedelta, timezone
    
    # --- Configuration ---
    TOKEN_FILE = "azure_token_info.json"  # File to cache the token and expiry
    EXPIRY_BUFFER_SECONDS = 300  # 5 minutes buffer before actual expiry
    # --- End Configuration ---
    
    def get_new_token():
        """
        Calls 'az account get-access-token' to fetch a new token and saves it.
        Returns the parsed token data (dict) or None on failure.
        """
        print("Getting new Azure access token...")
        try:
            # Command to get token and expiry in JSON format
            command = [
                "az", "account", "get-access-token",
                "--query", "{accessToken:accessToken, expiresOn:expiresOn, subscription:subscription, tenant:tenant, tokenType:tokenType}",
                "-o", "json"
            ]
            result = subprocess.run(command, capture_output=True, text=True, check=True, encoding='utf-8')
            token_data = json.loads(result.stdout)
    
            # Save the new token data to the file
            try:
                with open(TOKEN_FILE, 'w') as f:
                    json.dump(token_data, f)
                print(f"New token information saved to {TOKEN_FILE}")
                return token_data
            except IOError as e:
                print(f"Error saving token file {TOKEN_FILE}: {e}", file=sys.stderr)
                # Still return the token data even if saving failed, it's usable for now
                return token_data
    
        except subprocess.CalledProcessError as e:
            print(f"Error calling Azure CLI:", file=sys.stderr)
            print(f"Command: {' '.join(e.cmd)}", file=sys.stderr)
            print(f"Return Code: {e.returncode}", file=sys.stderr)
            print(f"Stderr: {e.stderr}", file=sys.stderr)
            print("Ensure you are logged in with 'az login' and the CLI is installed.", file=sys.stderr)
            return None
        except json.JSONDecodeError as e:
            print(f"Error parsing JSON output from Azure CLI: {e}", file=sys.stderr)
            print(f"Output was: {result.stdout}", file=sys.stderr)
            return None
        except FileNotFoundError:
            print("Error: 'az' command not found. Is Azure CLI installed and in PATH?", file=sys.stderr)
            return None
    
    
    def get_valid_token():
        """
        Checks the cached token's validity. If invalid, expired, or nearing
        expiry, fetches a new one.
        Returns the valid token data (dict) or None on failure.
        """
        token_data = None
        needs_refresh = False
    
        if not os.path.exists(TOKEN_FILE):
            print(f"Token file {TOKEN_FILE} not found.")
            needs_refresh = True
        else:
            try:
                with open(TOKEN_FILE, 'r') as f:
                    token_data = json.load(f)
    
                # --- Check expiry ---
                expires_on_str = token_data.get("expiresOn")
                if not expires_on_str:
                     print("Warning: 'expiresOn' field missing in cached token data.")
                     needs_refresh = True
                else:
                    try:
                        # Attempt to parse the timestamp. Azure CLI usually outputs
                        # a format like 'YYYY-MM-DD HH:MM:SS.ffffff'.
                        # It usually represents UTC time, even without explicit offset.
                        # We'll parse it assuming it's naive and then make it UTC aware.
                        expiry_datetime_naive = datetime.strptime(expires_on_str, '%Y-%m-%d %H:%M:%S.%f')
                        expiry_datetime_utc = expiry_datetime_naive.replace(tzinfo=timezone.utc) # Assume UTC
    
                        # Get current UTC time
                        now_utc = datetime.now(timezone.utc)
    
                        # Check if token is expired or within the buffer period
                        if now_utc + timedelta(seconds=EXPIRY_BUFFER_SECONDS) >= expiry_datetime_utc:
                            print("Token has expired or is nearing expiry.")
                            needs_refresh = True
                        else:
                            print("Loading cached token.")
    
                    except ValueError:
                        # Handle cases where the date format might be different
                        print(f"Warning: Could not parse expiresOn date '{expires_on_str}'. Refreshing token.")
                        needs_refresh = True
    
            except (IOError, json.JSONDecodeError) as e:
                print(f"Error reading or parsing token file {TOKEN_FILE}: {e}")
                needs_refresh = True
    
        if needs_refresh:
            token_data = get_new_token() 
    
        return token_data # Return current data (might be None if refresh failed)
    
    
    if __name__ == "__main__":
        print("--- Azure Token Refresh Script ---")
    
        # Get a valid token (fetches new one if necessary)
        valid_token_info = get_valid_token()
    
        if valid_token_info and "accessToken" in valid_token_info:
            access_token = valid_token_info["accessToken"]
            expires_on = valid_token_info.get("expiresOn", "N/A")
    
            # Use the access token for your API calls
            print("\nSuccessfully obtained valid access token.")
            print(f"Expires On: {expires_on}")
            # IMPORTANT: Avoid logging the full token in production environments!
            print(f"Token (first 10 chars): {access_token[:10]}...")
    
            # ---------------------------------------------------------------------
            # TODO: Insert your code here to use the 'access_token'
            # Example using requests library (install with: pip install requests)
            # ---------------------------------------------------------------------
            # import requests
            #
            # api_endpoint = "https://YOUR_AOAI_ENDPOINT/openai/deployments?api-version=YYYY-MM-DD"
            # headers = {
            #     "Authorization": f"Bearer {access_token}",
            #     "Content-Type": "application/json"
            # }
            # payload = {
            #     # Your deployment details here
            # }
            #
            # try:
            #     # response = requests.post(api_endpoint, headers=headers, json=payload)
            #     # response.raise_for_status() # Raise an exception for bad status codes (4xx or 5xx)
            #     # print("API call successful:")
            #     # print(response.json())
            #     print("\nPlaceholder: API call would be made here.")
            #
            # except requests.exceptions.RequestException as e:
            #     print(f"\nAPI call failed: {e}")
            # ---------------------------------------------------------------------
    
        else:
            print("\nFailed to obtain a valid Azure access token. Exiting.", file=sys.stderr)
            sys.exit(1)
    
        print("\n--- Script Finished ---")
    

    Para sua informação: fiz login na Interface de Linha de Comando (CLI) do Azure via `az login`: como posso ver quando ele vai me desconectar?

    Testado no Ubuntu 16.04.5 LTS e Python 3.12.

    • 0

relate perguntas

Sidebar

Stats

  • Perguntas 205573
  • respostas 270741
  • best respostas 135370
  • utilizador 68524
  • Highest score
  • respostas
  • Marko Smith

    Você pode passar usuário/passar para autenticação básica HTTP em parâmetros de URL?

    • 5 respostas
  • Marko Smith

    Ping uma porta específica

    • 18 respostas
  • Marko Smith

    Verifique se a porta está aberta ou fechada em um servidor Linux?

    • 7 respostas
  • Marko Smith

    Como automatizar o login SSH com senha?

    • 10 respostas
  • Marko Smith

    Como posso dizer ao Git para Windows onde encontrar minha chave RSA privada?

    • 30 respostas
  • Marko Smith

    Qual é o nome de usuário/senha de superusuário padrão para postgres após uma nova instalação?

    • 5 respostas
  • Marko Smith

    Qual porta o SFTP usa?

    • 6 respostas
  • Marko Smith

    Linha de comando para listar usuários em um grupo do Windows Active Directory?

    • 9 respostas
  • Marko Smith

    O que é um arquivo Pem e como ele difere de outros formatos de arquivo de chave gerada pelo OpenSSL?

    • 3 respostas
  • Marko Smith

    Como determinar se uma variável bash está vazia?

    • 15 respostas
  • Martin Hope
    Davie Ping uma porta específica 2009-10-09 01:57:50 +0800 CST
  • Martin Hope
    kernel O scp pode copiar diretórios recursivamente? 2011-04-29 20:24:45 +0800 CST
  • Martin Hope
    Robert ssh retorna "Proprietário incorreto ou permissões em ~/.ssh/config" 2011-03-30 10:15:48 +0800 CST
  • Martin Hope
    Eonil Como automatizar o login SSH com senha? 2011-03-02 03:07:12 +0800 CST
  • Martin Hope
    gunwin Como lidar com um servidor comprometido? 2011-01-03 13:31:27 +0800 CST
  • Martin Hope
    Tom Feiner Como posso classificar a saída du -h por tamanho 2009-02-26 05:42:42 +0800 CST
  • Martin Hope
    Noah Goodrich O que é um arquivo Pem e como ele difere de outros formatos de arquivo de chave gerada pelo OpenSSL? 2009-05-19 18:24:42 +0800 CST
  • Martin Hope
    Brent Como determinar se uma variável bash está vazia? 2009-05-13 09:54:48 +0800 CST

Hot tag

linux nginx windows networking ubuntu domain-name-system amazon-web-services active-directory apache-2.4 ssh

Explore

  • Início
  • Perguntas
    • Recentes
    • Highest score
  • tag
  • help

Footer

AskOverflow.Dev

About Us

  • About Us
  • Contact Us

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve