令牌刷新到 Azure KeyVault 访问

Token Refresh to Azure KeyVault Access

当我尝试通过

从我的本地计算机访问 Key Vault 时出现以下错误
DefaultAzureCredential()

我是运行下面两行,但是我一直报错。

client = SecretClient(vault_url=<URL>, credential=DefaultAzureCredential())
secret = client.get_secret(<SECRET NAME>).value
azure.core.exceptions.ClientAuthenticationError: DefaultAzureCredential failed to retrieve a token from the included credentials.
Attempted credentials:
EnvironmentCredential: EnvironmentCredential authentication unavailable. Environment variables are not fully configured.
ManagedIdentityCredential: ManagedIdentityCredential authentication unavailable, no managed identity endpoint found.
SharedTokenCacheCredential: SharedTokenCacheCredential authentication unavailable. No accounts were found in the cache.
VisualStudioCodeCredential: Azure Active Directory error '(invalid_grant) AADSTS700082: The refresh token has expired due to inactivity. The token was issued on 2020-06-07T03:58:48.4708462Z and was inactive for 90.00:00:00.

我尝试通过以下方式登录到 Azure az login 但这不会刷新凭据。

编辑: 我尝试了 documentation 中的一些其他配置。 Azure CLI 凭据的工作似乎很奇怪,因为它看起来像是默认凭据处理的场景之一。

如果您使用 az login 访问 Key Vault,理论上 AzureCliCredential()DefaultAzureCredential() 都可以正常工作。但是错误显示在您的问题中的 VisualStudioCodeCredential() 中。

VisualStudioCodeCredential:如果用户已登录 Visual Studio Code Azure 帐户扩展,DefaultAzureCredential 将作为该用户进行身份验证。

DefaultAzureCredential 尝试按此顺序通过以下机制进行身份验证,成功时停止:

因此,您需要使用 AzureCliCredential() 或设置 exclude_visual_studio_code_credential=true 以确保跳过 VisualStudioCode。

有关 Azure 身份的更多详细信息,请参阅 here

如果您希望它与 DefaultAzureCredential() 一起使用,您需要以下内容:-

  • 服务主体
  • 在 KeyVault 访问策略中授予对服务主体的访问权限。

完成上述操作后,您需要设置以下环境变量:-

  • AZURE_CLIENT_ID(这是上述服务主体(sp)的clientID)
  • AZURE_CLIENT_SECRET(这是上面sp的client secret key)
  • AZURE_SUBSCRIPTION_ID(这是 Azure 中的订阅 ID。)
  • AZURE_TENANT_ID(这是活动目录 ID)

要查看 windows 上的所有环境变量,请打开命令提示符键入命令“set”并按回车键。

要在 windows 上设置环境变量,例如您要设置 AZURE_CLIENT_ID 变量值为 jbfdshfbsdfbdsbdgbdjgbdfjbdfj,打开命令提示符键入命令“setx AZURE_CLIENT_ID jbfdshfbsdfbdsbdgbdjgbdfjbdfj”并按回车键

在您重新启动命令提示符之前,它不会显示更新。

然后在您使用 DefaultAzureCredentials()

的地方重新启动 visual studio/ vs 代码

这已经晚了,但也许它可以帮助其他人避免花费数小时来解决这个问题。我主要使用 Intellij 在 Java 工作,无论我做什么,我都会不断收到以下错误。我已经登录,通过 web、cli、intellij 插件、清除身份缓存,随你便。

com.azure.core.exception.ClientAuthenticationException: DefaultAzureCredential authentication failed. ---> VisualStudioCodeCredential authentication failed. Error Details: AADSTS50173: The provided grant has expired due to it being revoked, a fresh auth token is needed. The user might have changed or reset their password. The grant was issued on '2021-10-15T12:45:38.0655988Z' and the TokensValidFrom date (before which tokens are not valid) for this user is '2021-11-29T19:36:56.0000000Z'.

虽然我没有 'solve' 这个问题,但我的解决方法是打开 VS Code 并使用 Azure 帐户插件登录。然后我在 Intellij 中没有问题。请注意,VSCode 中也没有加载任何项目或代码。

我在尝试从 Azure Linux 跳转箱连接到 Key Vault 时收到类似的错误。自从我上次从这个盒子访问保险库已经 90 多天了。事实证明,我需要执行一个新的 az 登录请求来刷新我的令牌,尽管错误本身并没有具体指出这一点。