AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • 主页
  • 系统&网络
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • 主页
  • 系统&网络
    • 最新
    • 热门
    • 标签
  • Ubuntu
    • 最新
    • 热门
    • 标签
  • Unix
    • 最新
    • 标签
  • DBA
    • 最新
    • 标签
  • Computer
    • 最新
    • 标签
  • Coding
    • 最新
    • 标签
主页 / server / 问题 / 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

如何更改使用“az account get-access-token”获取的令牌的有效期?

  • 772

我使用获得的令牌az account get-access-token在 Azure 上部署经过微调的 GPT、更新它们(例如,更改它们的最大命中率)或删除它们。

我在https://learn.microsoft.com/en-us/cli/azure/account?view=azure-cli-latest上读到:

az account get-access-token:获取实用程序访问 Azure 的令牌。

令牌有效期至少为 5 分钟,最长为 60 分钟。如果未指定订阅参数,则使用当前帐户。

目前我获得的代币有效期为15分钟。

如何更改通过 获取的令牌的有效期az account get-access-token?

azure
  • 1 1 个回答
  • 87 Views

1 个回答

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

    作为一种解决方法,可以通过登录Azure 命令行界面 (CLI),az login并使用下面的 Python 代码获取令牌。az login登录时间超过了使用 获取的令牌的有效期az account get-access-token,因此当令牌即将到期时,Python 代码会请求另一个令牌。

    要在 Ubuntu 上安装 Azure 命令行界面 (CLI):

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

    然后通过 登录az login。然后运行此 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 ---")
    

    仅供参考:我已通过“az login”登录到 Azure 命令行界面 (CLI):我如何知道它何时会将我注销?

    在 Ubuntu 16.04.5 LTS 和 Python 3.12 上测试。

    • 0

相关问题

Sidebar

Stats

  • 问题 205573
  • 回答 270741
  • 最佳答案 135370
  • 用户 68524
  • 热门
  • 回答
  • Marko Smith

    新安装后 postgres 的默认超级用户用户名/密码是什么?

    • 5 个回答
  • Marko Smith

    SFTP 使用什么端口?

    • 6 个回答
  • Marko Smith

    命令行列出 Windows Active Directory 组中的用户?

    • 9 个回答
  • Marko Smith

    什么是 Pem 文件,它与其他 OpenSSL 生成的密钥文件格式有何不同?

    • 3 个回答
  • Marko Smith

    如何确定bash变量是否为空?

    • 15 个回答
  • Martin Hope
    Tom Feiner 如何按大小对 du -h 输出进行排序 2009-02-26 05:42:42 +0800 CST
  • Martin Hope
    Noah Goodrich 什么是 Pem 文件,它与其他 OpenSSL 生成的密钥文件格式有何不同? 2009-05-19 18:24:42 +0800 CST
  • Martin Hope
    Brent 如何确定bash变量是否为空? 2009-05-13 09:54:48 +0800 CST
  • Martin Hope
    cletus 您如何找到在 Windows 中打开文件的进程? 2009-05-01 16:47:16 +0800 CST

热门标签

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

Explore

  • 主页
  • 问题
    • 最新
    • 热门
  • 标签
  • 帮助

Footer

AskOverflow.Dev

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve