Repository: Azure/azure-sdk-for-python (Python)

Issue:
DefaultAzureCredential: Re-enable SSO with VSCode on Windows
Now that WAM is the default authN mechanism in VS Code desktop, we can explore restoration of SSO with VS Code for Windows customers. Such a feature would fill the gap left behind with the deprecation of VisualStudioCodeCredential. One idea is to use a silent, broker-enabled instance of InteractiveBrowserCredential.


Discussion:
Gist for April Beta release https://gist.github.com/christothes/f8a0dc6249261cb36a6c452717c4e932
Related work on the VS Code and Azure MCP Server side of this puzzle is tracked here: https://github.com/Azure/azure-mcp-pr/issues/245



Patch:
diff --git a/sdk/identity/azure-identity/CHANGELOG.md b/sdk/identity/azure-identity/CHANGELOG.md
index 2356c3952b4a..93bffec18471 100644
--- a/sdk/identity/azure-identity/CHANGELOG.md
+++ b/sdk/identity/azure-identity/CHANGELOG.md
@@ -6,6 +6,9 @@
 
 - Expanded the set of acceptable values for environment variable `AZURE_TOKEN_CREDENTIALS` to allow for selection of a specific credential in the `DefaultAzureCredential` chain. At runtime, only the specified credential will be used when acquiring tokens with `DefaultAzureCredential`. For example, setting `AZURE_TOKEN_CREDENTIALS=WorkloadIdentityCredential` will make `DefaultAzureCredential` use only `WorkloadIdentityCredential`.
   - Valid values are `EnvironmentCredential`, `WorkloadIdentityCredential`, `ManagedIdentityCredential`, `AzureCliCredential`, `AzurePowershellCredential`, `AzureDeveloperCliCredential`, and `InteractiveBrowserCredential`. ([#41709](https://github.com/Azure/azure-sdk-for-python/pull/41709))
+- Re-enabled `VisualStudioCodeCredential` - Previously deprecated `VisualStudioCodeCredential` has been re-implemented to work with the VS Code Azure Resources extension instead of the deprecated Azure Account extension. This requires the `azure-identity-broker` package to be installed for authentication. ([#41822](https://github.com/Azure/azure-sdk-for-python/pull/41822))
+  - `VisualStudioCodeCredential` is now included in the `DefaultAzureCredential` token chain by default.
+
 
 ### Breaking Changes
 
diff --git a/sdk/identity/azure-identity/README.md b/sdk/identity/azure-identity/README.md
index 1670aa4d464e..49a4c39b6037 100644
--- a/sdk/identity/azure-identity/README.md
+++ b/sdk/identity/azure-identity/README.md
@@ -108,6 +108,14 @@ DefaultAzureCredential(managed_identity_client_id=client_id)
 
 Alternatively, set the environment variable `AZURE_CLIENT_ID` to the identity's client ID.
 
+#### Authenticate Using Visual Studio Code with `DefaultAzureCredential`
+
+To authenticate using Visual Studio Code, ensure you have signed in through the **Azure Resources** extension. The signed-in user is then picked up automatically by `DefaultAzureCredential`. Currently, this is only supported on Windows and WSL. To use this method of authentication, ensure the following prerequisites are met:
+
+- [Azure Resources Extension](https://marketplace.visualstudio.com/items?itemName=ms-azuretools.vscode-azureresourcegroups) is installed in Visual Studio Code.
+- You are signed in using the `Azure: Sign In` command in VS Code.
+- You have the [`azure-identity-broker`][azure_identity_broker] package installed.
+
 ### Define a custom authentication flow with `ChainedTokenCredential`
 
 While `DefaultAzureCredential` is generally the quickest way to authenticate apps for Azure, you can create a customized chain of credentials to be considered. `ChainedTokenCredential` enables users to combine multiple credential instances to define a customized chain of credentials. For more information, see [ChainedTokenCredential overview][ctc_overview].
diff --git a/sdk/identity/azure-identity/TROUBLESHOOTING.md b/sdk/identity/azure-identity/TROUBLESHOOTING.md
index 84811ce4d3e9..3817a30c858d 100644
--- a/sdk/identity/azure-identity/TROUBLESHOOTING.md
+++ b/sdk/identity/azure-identity/TROUBLESHOOTING.md
@@ -19,6 +19,7 @@ This troubleshooting guide covers failure investigation techniques, common error
   - [Azure Virtual Machine managed identity](#azure-virtual-machine-managed-identity)
   - [Azure App Service and Azure Functions managed identity](#azure-app-service-and-azure-functions-managed-identity)
   - [Azure Kubernetes Service managed identity](#azure-kubernetes-service-managed-identity)
+- [Troubleshoot VisualStudioCodeCredential authentication issues](#troubleshoot-visualstudiocodecredential-authentication-issues)
 - [Troubleshoot AzureCliCredential authentication issues](#troubleshoot-azureclicredential-authentication-issues)
 - [Troubleshoot AzureDeveloperCliCredential authentication issues](#troubleshoot-azuredeveloperclicredential-authentication-issues)
 - [Troubleshoot AzurePowerShellCredential authentication issues](#troubleshoot-azurepowershellcredential-authentication-issues)
@@ -182,6 +183,26 @@ curl 'http://169.254.169.254/metadata/identity/oauth2/token?resource=https://man
 |---|---|---|
 |No managed identity endpoint found|The application attempted to authenticate before an identity was assigned to its pod|Verify the pod is labeled correctly. This also occurs when a correctly labeled pod authenticates before the identity is ready. To prevent initialization races, configure NMI to set the Retry-After header in its responses (see [Pod Identity documentation](https://azure.github.io/aad-pod-identity/docs/configure/feature_flags/#set-retry-after-header-in-nmi-response)).
 
+## Troubleshoot `VisualStudioCodeCredential` authentication issues
+
+> **Applies to:** Version 1.24.0b1 and later
+
+As of version 1.24.0b1, `VisualStudioCodeCredential` uses brokered authentication to sign in using the Azure Resources extension in Visual Studio Code. This approach requires the `azure-identity-broker` dependency and currently only works on Windows or WSL.
+
+### Platform support
+
+**Note:** `VisualStudioCodeCredential` with brokered authentication is currently only supported on Windows and WSL. Linux and macOS are not yet supported.
+
+### Common errors
+
+`CredentialUnavailableError`
+
+| Error Message | Description | Mitigation |
+|---|---|---|
+| VisualStudioCodeCredential requires the 'azure-identity-broker' package to be installed. You must also ensure you have the Azure Resources extension installed and have signed in to Azure via Visual Studio Code.` | Brokered authentication is not available, which may be due to missing dependencies, not being signed in to Azure in VS Code, or the Azure Resources extension not being installed. | <ul><li>Ensure your project includes the <code>azure-identity-broker</code> dependency.</li><li>In Visual Studio Code, install the <a href="https://marketplace.visualstudio.com/items?itemName=ms-azuretools.vscode-azureresourcegroups">Azure Resources extension</a>.</li><li>Sign in to Azure using the "Azure: Sign In" command in VS Code.</li><li>Restart your application after signing in.</li></ul> |
+
+> VisualStudioCodeCredential is intended for local development scenarios and is not recommended for production environments.
+
 ## Troubleshoot `AzureCliCredential` authentication issues
 
 `CredentialUnavailableError`
diff --git a/sdk/identity/azure-identity/azure/identity/_credentials/default.py b/sdk/identity/azure-identity/azure/identity/_credentials/default.py
index 798afb842846..316b202d0771 100644
--- a/sdk/identity/azure-identity/azure/identity/_credentials/default.py
+++ b/sdk/identity/azure-identity/azure/identity/_credentials/default.py
@@ -80,9 +80,8 @@ class DefaultAzureCredential(ChainedTokenCredential):
     :keyword str shared_cache_tenant_id: Preferred tenant for :class:`~azure.identity.SharedTokenCacheCredential`.
         Defaults to the value of environment variable AZURE_TENANT_ID, if any.
     :keyword str visual_studio_code_tenant_id: Tenant ID to use when authenticating with
-        :class:`~azure.identity.VisualStudioCodeCredential`. Defaults to the "Azure: Tenant" setting in VS Code's user
-        settings or, when that setting has no value, the "organizations" tenant, which supports only Azure Active
-        Directory work or school accounts.
+        :class:`~azure.identity.VisualStudioCodeCredential`. Defaults to the tenant specified in the authentication
+        record file used by the Azure Resources extension.
     :keyword int process_timeout: The timeout in seconds to use for developer credentials that run
         subprocesses (e.g. AzureCliCredential, AzurePowerShellCredential). Defaults to **10** seconds.
 
@@ -101,18 +100,10 @@ def __init__(self, **kwargs: Any) -> None:  # pylint: disable=too-many-statement
             raise TypeError("'tenant_id' is not supported in DefaultAzureCredential.")
 
         authority = kwargs.pop("authority", None)
-
-        vscode_tenant_id = kwargs.pop(
-            "visual_studio_code_tenant_id", os.environ.get(EnvironmentVariables.AZURE_TENANT_ID)
-        )
-        vscode_args = dict(kwargs)
-        if authority:
-            vscode_args["authority"] = authority
-        if vscode_tenant_id:
-            vscode_args["tenant_id"] = vscode_tenant_id
-
         authority = normalize_authority(authority) if authority else get_default_authority()
 
+        vscode_tenant_id = kwargs.pop("visual_studio_code_tenant_id", None)
+
         interactive_browser_tenant_id = kwargs.pop(
             "interactive_browser_tenant_id", os.environ.get(EnvironmentVariables.AZURE_TENANT_ID)
         )
@@ -156,7 +147,7 @@ def __init__(self, **kwargs: Any) -> None:  # pylint: disable=too-many-statement
             },
             "visual_studio_code": {
                 "exclude_param": "exclude_visual_studio_code_credential",
-                "default_exclude": True,
+                "default_exclude": False,
             },
             "cli": {
                 "exclude_param": "exclude_cli_credential",
@@ -235,7 +226,7 @@ def __init__(self, **kwargs: Any) -> None:  # pylint: disable=too-many-statement
             except Exception as ex:  # pylint:disable=broad-except
                 _LOGGER.info("Shared token cache is unavailable: '%s'", ex)
         if not exclude_visual_studio_code_credential:
-            credentials.append(VisualStudioCodeCredential(**vscode_args))
+            credentials.append(VisualStudioCodeCredential(tenant_id=vscode_tenant_id))
         if not exclude_cli_credential:
             credentials.append(AzureCliCredential(process_timeout=process_timeout))
         if not exclude_powershell_credential:
diff --git a/sdk/identity/azure-identity/azure/identity/_credentials/vscode.py b/sdk/identity/azure-identity/azure/identity/_credentials/vscode.py
index 79f126064046..b2b8944e69f4 100644
--- a/sdk/identity/azure-identity/azure/identity/_credentials/vscode.py
+++ b/sdk/identity/azure-identity/azure/identity/_credentials/vscode.py
@@ -2,149 +2,186 @@
 # Copyright (c) Microsoft Corporation.
 # Licensed under the MIT License.
 # ------------------------------------
-import abc
 import os
-import sys
-from typing import cast, Any, Dict, Optional
-import warnings
+import json
+from typing import Any, Optional
 
+import msal
 from azure.core.credentials import AccessToken, TokenRequestOptions, AccessTokenInfo
 from azure.core.exceptions import ClientAuthenticationError
+
+from .._auth_record import AuthenticationRecord
 from .._exceptions import CredentialUnavailableError
-from .._constants import AzureAuthorityHosts, AZURE_VSCODE_CLIENT_ID, EnvironmentVariables
-from .._internal import normalize_authority, validate_tenant_id, within_dac
-from .._internal.aad_client import AadClient, AadClientBase
-from .._internal.get_token_mixin import GetTokenMixin
+from .._constants import AZURE_VSCODE_CLIENT_ID
+from .._internal import within_dac
+
 from .._internal.decorators import log_get_token
+from .._internal.utils import get_broker_credential, validate_tenant_id
 
-if sys.platform.startswith("win"):
-    from .._internal.win_vscode_adapter import get_refresh_token, get_user_settings
-elif sys.platform.startswith("darwin"):
-    from .._internal.macos_vscode_adapter import get_refresh_token, get_user_settings
-else:
-    from .._internal.linux_vscode_adapter import get_refresh_token, get_user_settings
+MAX_AUTH_RECORD_SIZE = 10 * 1024  # 10KB - more than enough for a small auth record
+VSCODE_AUTH_RECORD_PATHS = [
+    "~/.azure/ms-azuretools.vscode-azureresourcegroups/authRecord.json",
+    "~/.Azure/ms-azuretools.vscode-azureresourcegroups/authRecord.json",
+]
 
 
-class _VSCodeCredentialBase(abc.ABC):
-    def __init__(self, **kwargs: Any) -> None:
-        warnings.warn(
-            "This credential is deprecated because the Azure Account extension for Visual Studio Code, which this "
-            "credential relies on, has been deprecated. See the Azure Account extension deprecation notice here: "
-            "https://github.com/microsoft/vscode-azure-account/issues/964. Consider using other developer credentials "
-            "such as AzureCliCredential, AzureDeveloperCliCredential, or AzurePowerShellCredential.",
-            DeprecationWarning,
-            stacklevel=2,
-        )
-        super(_VSCodeCredentialBase, self).__init__()
-
-        user_settings = get_user_settings()
-        self._cloud = user_settings.get("azure.cloud", "AzureCloud")
-        self._refresh_token = None
-        self._unavailable_reason = ""
-
-        self._client = kwargs.get("_client")
-        if not self._client:
-            self._initialize(user_settings, **kwargs)
-        if not (self._client or self._unavailable_reason):
-            self._unavailable_reason = "Initialization failed"
-
-    @abc.abstractmethod
-    def _get_client(self, **kwargs: Any) -> AadClientBase:
-        pass
-
-    def _get_refresh_token(self) -> str:
-        if not self._refresh_token:
-            self._refresh_token = get_refresh_token(self._cloud)
-            if not self._refresh_token:
-                message = (
-                    "Failed to get Azure user details from Visual Studio Code. "
-                    "Currently, the VisualStudioCodeCredential only works with the Azure "
-                    "Account extension version 0.9.11 and earlier. A long-term fix is in "
-                    "progress, see https://github.com/Azure/azure-sdk-for-python/issues/25713"
-                )
-                raise CredentialUnavailableError(message=message)
-        return self._refresh_token
-
-    def _initialize(self, vscode_user_settings: Dict, **kwargs: Any) -> None:
-        """Build a client from kwargs merged with VS Code user settings.
+def load_vscode_auth_record() -> Optional[AuthenticationRecord]:
+    """Load the authentication record corresponding to a known location.
 
-        The first stable version of this credential defaulted to Public Cloud and the "organizations"
-        tenant when it failed to read VS Code user settings. That behavior is preserved here.
+    This will load from ~/.azure/ms-azuretools.vscode-azureresourcegroups/authRecord.json
+    or ~/.Azure/ms-azuretools.vscode-azureresourcegroups/authRecord.json
 
-        :param dict vscode_user_settings: VS Code user settings
-        """
+    :return: The authentication record if it exists, otherwise None.
+    :rtype: Optional[AuthenticationRecord]
+    :raises: ValueError if the authentication record is not in the expected format
+    """
 
-        # Precedence for authority:
-        #  1) VisualStudioCodeCredential(authority=...)
-        #  2) $AZURE_AUTHORITY_HOST
-        #  3) authority matching VS Code's "azure.cloud" setting
-        #  4) default: Public Cloud
-        authority = kwargs.pop("authority", None) or os.environ.get(EnvironmentVariables.AZURE_AUTHORITY_HOST)
-        if not authority:
-            # the application didn't specify an authority, so we figure it out from VS Code settings
-            if self._cloud == "AzureCloud":
-                authority = AzureAuthorityHosts.AZURE_PUBLIC_CLOUD
-            elif self._cloud == "AzureChinaCloud":
-                authority = AzureAuthorityHosts.AZURE_CHINA
-            elif self._cloud == "AzureUSGovernment":
-                authority = AzureAuthorityHosts.AZURE_GOVERNMENT
-            else:
-                # If the value is anything else ("AzureCustomCloud" is the only other known value),
-                # we need the user to provide the authority because VS Code has no setting for it and
-                # we can't guess confidently.
-                self._unavailable_reason = (
-                    'VS Code is configured to use a custom cloud. Set keyword argument "authority"'
-                    + ' with the Microsoft Entra endpoint for cloud "{}"'.format(self._cloud)
+    # Try each possible auth record path
+    for auth_record_path in VSCODE_AUTH_RECORD_PATHS:
+        expanded_path = os.path.expanduser(auth_record_path)
+        if os.path.exists(expanded_path):
+            file_size = os.path.getsize(expanded_path)
+            if file_size > MAX_AUTH_RECORD_SIZE:
+                error_message = (
+                    "VS Code auth record file is unexpectedly large. "
+                    "Please check the file for corruption or unexpected content."
                 )
-                return
-
-        # Precedence for tenant ID:
-        #  1) VisualStudioCodeCredential(tenant_id=...)
-        #  2) "azure.tenant" in VS Code user settings
-        #  3) default: organizations
-        tenant_id = kwargs.pop("tenant_id", None) or vscode_user_settings.get("azure.tenant", "organizations")
-        validate_tenant_id(tenant_id)
-        if tenant_id.lower() == "adfs":
-            self._unavailable_reason = "VisualStudioCodeCredential authentication unavailable. ADFS is not supported."
-            return
-
-        self._client = self._get_client(
-            authority=normalize_authority(authority), client_id=AZURE_VSCODE_CLIENT_ID, tenant_id=tenant_id, **kwargs
-        )
+                raise ValueError(error_message)
+            with open(expanded_path, "r", encoding="utf-8") as f:
+                deserialized = json.load(f)
+
+            # Validate the authentication record for security and structural integrity
+            _validate_auth_record_json(deserialized)
+
+            # Deserialize the authentication record
+            auth_record = AuthenticationRecord(
+                authority=deserialized["authority"],
+                client_id=deserialized["clientId"],
+                home_account_id=deserialized["homeAccountId"],
+                tenant_id=deserialized["tenantId"],
+                username=deserialized["username"],
+            )
+
+            return auth_record
 
+    # No auth record found in any of the expected locations
+    return None
 
-class VisualStudioCodeCredential(_VSCodeCredentialBase, GetTokenMixin):
-    """Authenticates as the Azure user signed in to Visual Studio Code via the 'Azure Account' extension.
 
-    **Deprecated**: This credential is deprecated because the Azure Account extension for Visual Studio Code, which
-    this credential relies on, has been deprecated. See the Azure Account extension deprecation notice here:
-    https://github.com/microsoft/vscode-azure-account/issues/964. Consider using other developer credentials such as
-    AzureCliCredential, AzureDeveloperCliCredential, or AzurePowerShellCredential.
+def _validate_auth_record_json(data: dict) -> None:
+    """Validate the authentication record.
 
-    :keyword str authority: Authority of a Microsoft Entra endpoint, for example "login.microsoftonline.com".
-        This argument is required for a custom cloud and usually unnecessary otherwise. Defaults to the authority
-        matching the "Azure: Cloud" setting in VS Code's user settings or, when that setting has no value, the
-        authority for Azure Public Cloud.
-    :keyword str tenant_id: ID of the tenant the credential should authenticate in. Defaults to the "Azure: Tenant"
-        setting in VS Code's user settings or, when that setting has no value, the "organizations" tenant, which
-        supports only Microsoft Entra work or school accounts.
+    :param dict data: The authentication record data to validate.
+    :raises ValueError: If the authentication record fails validation checks.
+    """
+    errors = []
+
+    # Schema Validation - Required Fields
+    try:
+        tenant_id = data["tenantId"]
+        if not tenant_id or not isinstance(tenant_id, str):
+            errors.append("tenantId must be a non-empty string")
+        else:
+            try:
+                validate_tenant_id(tenant_id)
+            except ValueError as e:
+                errors.append(f"tenantId validation failed: {e}")
+    except KeyError:
+        errors.append("tenantId field is missing")
+
+    try:
+        client_id = data["clientId"]
+        if not client_id or not isinstance(client_id, str):
+            errors.append("clientId must be a non-empty string")
+        elif client_id != AZURE_VSCODE_CLIENT_ID:
+            errors.append(
+                f"clientId must match expected VS Code Azure Resources extension client ID: {AZURE_VSCODE_CLIENT_ID}"
+            )
+    except KeyError:
+        errors.append("clientId field is missing")
+
+    try:
+        username = data["username"]
+        if not username or not isinstance(username, str):
+            errors.append("username must be a non-empty string")
+    except KeyError:
+        errors.append("username field is missing")
+
+    try:
+        home_account_id = data["homeAccountId"]
+        if not home_account_id or not isinstance(home_account_id, str):
+            errors.append("homeAccountId must be a non-empty string")
+    except KeyError:
+        errors.append("homeAccountId field is missing")
+
+    try:
+        authority = data["authority"]
+        if not authority or not isinstance(authority, str):
+            errors.append("authority must be a non-empty string")
+    except KeyError:
+        errors.append("authority field is missing")
+
+    if errors:
+        error_message = "Authentication record validation failed: " + "; ".join(errors)
+        raise ValueError(error_message)
+
+
+class VisualStudioCodeCredential:
+    """Authenticates as the Azure user signed in to Visual Studio Code via the 'Azure Resources' extension.
+
+    :keyword str tenant_id: A Microsoft Entra tenant ID. Defaults to the tenant specified in the authentication
+        record file used by the Azure Resources extension.
     :keyword List[str] additionally_allowed_tenants: Specifies tenants in addition to the specified "tenant_id"
         for which the credential may acquire tokens. Add the wildcard value "*" to allow the credential to
         acquire tokens for any tenant the application can access.
     """
 
+    def __init__(self, **kwargs: Any) -> None:
+
+        self._broker_credential = None
+        self._unavailable_message = (
+            "VisualStudioCodeCredential requires the 'azure-identity-broker' package to be installed. "
+            "You must also ensure you have the Azure Resources extension installed and have "
+            "signed in to Azure via Visual Studio Code."
+        )
+
+        broker_credential_class = get_broker_credential()
+        if broker_credential_class:
+            try:
+                # Load the authentication record from the VS Code extension
+                authentication_record = load_vscode_auth_record()
+                if not authentication_record:
+                    self._unavailable_message = (
+                        "VisualStudioCodeCredential requires the user to be signed in to Azure via Visual Studio Code. "
+                        "Please ensure you have the Azure Resources extension installed and have signed in."
+                    )
+                    return
+                self._broker_credential = broker_credential_class(
+                    client_id=AZURE_VSCODE_CLIENT_ID,
+                    authentication_record=authentication_record,
+                    parent_window_handle=msal.PublicClientApplication.CONSOLE_WINDOW_HANDLE,
+                    use_default_broker_account=True,
+                    **kwargs,
+                )
+            except ValueError as ex:
+                self._unavailable_message = (
+                    "Failed to load authentication record from Visual Studio Code: "
+                    f"{ex}. Please ensure you have the Azure Resources extension installed and signed in."
+                )
+
     def __enter__(self) -> "VisualStudioCodeCredential":
-        if self._client:
-            self._client.__enter__()
+        if self._broker_credential:
+            self._broker_credential.__enter__()
         return self
 
     def __exit__(self, *args: Any) -> None:
-        if self._client:
-            self._client.__exit__(*args)
+        if self._broker_credential:
+            self._broker_credential.__exit__(*args)
 
     def close(self) -> None:
         """Close the credential's transport session."""
-        self.__exit__()
+        if self._broker_credential:
+            self._broker_credential.close()
 
     @log_get_token
     def get_token(
@@ -166,20 +203,15 @@ def get_token(
         :raises ~azure.identity.CredentialUnavailableError: the credential cannot retrieve user details from Visual
           Studio Code
         """
-        if self._unavailable_reason:
-            error_message = (
-                self._unavailable_reason + "\n"
-                "Visit https://aka.ms/azsdk/python/identity/vscodecredential/troubleshoot"
-                " to troubleshoot this issue."
-            )
-            raise CredentialUnavailableError(message=error_message)
+        if not self._broker_credential:
+            raise CredentialUnavailableError(message=self._unavailable_message)
         if within_dac.get():
             try:
-                token = super().get_token(*scopes, claims=claims, tenant_id=tenant_id, **kwargs)
+                token = self._broker_credential.get_token(*scopes, claims=claims, tenant_id=tenant_id, **kwargs)
                 return token
             except ClientAuthenticationError as ex:
                 raise CredentialUnavailableError(message=ex.message) from ex
-        return super().get_token(*scopes, claims=claims, tenant_id=tenant_id, **kwargs)
+        return self._broker_credential.get_token(*scopes, claims=claims, tenant_id=tenant_id, **kwargs)
 
     def get_token_info(self, *scopes: str, options: Optional[TokenRequestOptions] = None) -> AccessTokenInfo:
         """Request an access token for `scopes` as the user currently signed in to Visual Studio Code.
@@ -197,29 +229,12 @@ def get_token_info(self, *scopes: str, options: Optional[TokenRequestOptions] =
         :raises ~azure.identity.CredentialUnavailableError: the credential cannot retrieve user details from Visual
           Studio Code.
         """
-        if self._unavailable_reason:
-            error_message = (
-                self._unavailable_reason + "\n"
-                "Visit https://aka.ms/azsdk/python/identity/vscodecredential/troubleshoot"
-                " to troubleshoot this issue."
-            )
-            raise CredentialUnavailableError(message=error_message)
+        if not self._broker_credential:
+            raise CredentialUnavailableError(message=self._unavailable_message)
         if within_dac.get():
             try:
-                token = super().get_token_info(*scopes, options=options)
+                token = self._broker_credential.get_token_info(*scopes, options=options)
                 return token
             except ClientAuthenticationError as ex:
                 raise CredentialUnavailableError(message=ex.message) from ex
-        return super().get_token_info(*scopes, options=options)
-
-    def _acquire_token_silently(self, *scopes: str, **kwargs: Any) -> Optional[AccessTokenInfo]:
-        self._client = cast(AadClient, self._client)
-        return self._client.get_cached_access_token(scopes, **kwargs)
-
-    def _request_token(self, *scopes: str, **kwargs: Any) -> AccessTokenInfo:
-        refresh_token = self._get_refresh_token()
-        self._client = cast(AadClient, self._client)
-        return self._client.obtain_token_by_refresh_token(scopes, refresh_token, **kwargs)
-
-    def _get_client(self, **kwargs: Any) -> AadClient:
-        return AadClient(**kwargs)
+        return self._broker_credential.get_token_info(*scopes, options=options)
diff --git a/sdk/identity/azure-identity/azure/identity/_internal/linux_vscode_adapter.py b/sdk/identity/azure-identity/azure/identity/_internal/linux_vscode_adapter.py
deleted file mode 100644
index d0be19f13133..000000000000
--- a/sdk/identity/azure-identity/azure/identity/_internal/linux_vscode_adapter.py
+++ /dev/null
@@ -1,100 +0,0 @@
-# ------------------------------------
-# Copyright (c) Microsoft Corporation.
-# Licensed under the MIT License.
-# ------------------------------------
-import os
-import json
-import logging
-import ctypes as ct
-from .._constants import VSCODE_CREDENTIALS_SECTION
-
-_LOGGER = logging.getLogger(__name__)
-
-
-def _c_str(string):
-    return ct.c_char_p(string.encode("utf-8"))
-
-
-class _SECRET_SCHEMA_ATTRIBUTE(ct.Structure):
-    _fields_ = [
-        ("name", ct.c_char_p),
-        ("type", ct.c_uint),
-    ]
-
-
-class _SECRET_SCHEMA(ct.Structure):
-    _fields_ = [
-        ("name", ct.c_char_p),
-        ("flags", ct.c_uint),
-        ("attributes", _SECRET_SCHEMA_ATTRIBUTE * 2),
-    ]
-
-
-_PSECRET_SCHEMA = ct.POINTER(_SECRET_SCHEMA)
-
-
-try:
-    _libsecret = ct.cdll.LoadLibrary("libsecret-1.so.0")
-    _libsecret.secret_password_lookup_sync.argtypes = [
-        ct.c_void_p,
-        ct.c_void_p,
-        ct.c_void_p,
-        ct.c_char_p,
-        ct.c_char_p,
-        ct.c_char_p,
-        ct.c_char_p,
-        ct.c_void_p,
-    ]
-    _libsecret.secret_password_lookup_sync.restype = ct.c_char_p
-    _libsecret.secret_password_free.argtypes = [ct.c_char_p]
-except OSError:
-    _libsecret = None  # type: ignore
-
-
-def _get_refresh_token(service_name, account_name):
-    if not _libsecret:
-        return None
-
-    err = ct.c_int()
-    attributes = [_SECRET_SCHEMA_ATTRIBUTE(_c_str("service"), 0), _SECRET_SCHEMA_ATTRIBUTE(_c_str("account"), 0)]
-    pattributes = (_SECRET_SCHEMA_ATTRIBUTE * 2)(*attributes)
-    schema = _SECRET_SCHEMA()
-    pschema = _PSECRET_SCHEMA(schema)
-    ct.memset(pschema, 0, ct.sizeof(schema))
-    schema.name = _c_str("org.freedesktop.Secret.Generic")  # pylint: disable=attribute-defined-outside-init
-    schema.flags = 2  # pylint: disable=attribute-defined-outside-init
-    schema.attributes = pattributes  # pylint: disable=attribute-defined-outside-init
-    p_str = _libsecret.secret_password_lookup_sync(
-        pschema,
-        None,
-        ct.byref(err),
-        _c_str("service"),
-        _c_str(service_name),
-        _c_str("account"),
-        _c_str(account_name),
-        None,
-    )
-    if err.value == 0 and p_str:
-        return p_str.decode("utf-8")
-
-    return None
-
-
-def get_user_settings():
-    try:
-        path = os.path.join(os.environ["HOME"], ".config", "Code", "User", "settings.json")
-        with open(path, encoding="utf-8") as file:
-            return json.load(file)
-    except Exception as ex:  # pylint:disable=broad-except
-        _LOGGER.debug('Exception reading VS Code user settings: "%s"', ex, exc_info=_LOGGER.isEnabledFor(logging.DEBUG))
-        return {}
-
-
-def get_refresh_token(cloud_name):
-    try:
-        return _get_refresh_token(VSCODE_CREDENTIALS_SECTION, cloud_name)
-    except Exception as ex:  # pylint:disable=broad-except
-        _LOGGER.debug(
-            'Exception retrieving VS Code credentials: "%s"', ex, exc_info=_LOGGER.isEnabledFor(logging.DEBUG)
-        )
-        return None
diff --git a/sdk/identity/azure-identity/azure/identity/_internal/macos_vscode_adapter.py b/sdk/identity/azure-identity/azure/identity/_internal/macos_vscode_adapter.py
deleted file mode 100644
index 96643cd10d5e..000000000000
--- a/sdk/identity/azure-identity/azure/identity/_internal/macos_vscode_adapter.py
+++ /dev/null
@@ -1,34 +0,0 @@
-# ------------------------------------
-# Copyright (c) Microsoft Corporation.
-# Licensed under the MIT License.
-# ------------------------------------
-import os
-import json
-import logging
-from msal_extensions.osx import Keychain, KeychainError
-from .._constants import VSCODE_CREDENTIALS_SECTION
-
-_LOGGER = logging.getLogger(__name__)
-
-
-def get_user_settings():
-    try:
-        path = os.path.join(os.environ["HOME"], "Library", "Application Support", "Code", "User", "settings.json")
-        with open(path, encoding="utf-8") as file:
-            return json.load(file)
-    except Exception as ex:  # pylint:disable=broad-except
-        _LOGGER.debug('Exception reading VS Code user settings: "%s"', ex, exc_info=_LOGGER.isEnabledFor(logging.DEBUG))
-        return {}
-
-
-def get_refresh_token(cloud_name):
-    try:
-        key_chain = Keychain()
-        return key_chain.get_generic_password(VSCODE_CREDENTIALS_SECTION, cloud_name)
-    except KeychainError:
-        return None
-    except Exception as ex:  # pylint:disable=broad-except
-        _LOGGER.debug(
-            'Exception retrieving VS Code credentials: "%s"', ex, exc_info=_LOGGER.isEnabledFor(logging.DEBUG)
-        )
-        return None
diff --git a/sdk/identity/azure-identity/azure/identity/_internal/utils.py b/sdk/identity/azure-identity/azure/identity/_internal/utils.py
index b18393965c05..2303906ec4eb 100644
--- a/sdk/identity/azure-identity/azure/identity/_internal/utils.py
+++ b/sdk/identity/azure-identity/azure/identity/_internal/utils.py
@@ -195,3 +195,17 @@ def process_credential_exclusions(credential_config: dict, exclude_flags: dict,
             exclude_flags[cred_key] = user_value
 
     return exclude_flags
+
+
+def get_broker_credential() -> Optional[type]:
+    """Return the InteractiveBrowserBrokerCredential class if available, otherwise None.
+
+    :return: InteractiveBrowserBrokerCredential class or None
+    :rtype: Optional[type]
+    """
+    try:
+        from azure.identity.broker import InteractiveBrowserBrokerCredential
+
+        return InteractiveBrowserBrokerCredential
+    except ImportError:
+        return None
diff --git a/sdk/identity/azure-identity/azure/identity/_internal/win_vscode_adapter.py b/sdk/identity/azure-identity/azure/identity/_internal/win_vscode_adapter.py
deleted file mode 100644
index 2cec7ba49e97..000000000000
--- a/sdk/identity/azure-identity/azure/identity/_internal/win_vscode_adapter.py
+++ /dev/null
@@ -1,77 +0,0 @@
-# ------------------------------------
-# Copyright (c) Microsoft Corporation.
-# Licensed under the MIT License.
-# ------------------------------------
-import os
-import json
-import logging
-import ctypes as ct
-from .._constants import VSCODE_CREDENTIALS_SECTION
-
-try:
-    import ctypes.wintypes as wt
-except (IOError, ValueError):
-    pass
-
-_LOGGER = logging.getLogger(__name__)
-
-SUPPORTED_CREDKEYS = set(("Type", "TargetName", "Persist", "UserName", "Comment", "CredentialBlob"))
-
-_PBYTE = ct.POINTER(ct.c_byte)
-
-
-class _CREDENTIAL(ct.Structure):
-    _fields_ = [
-        ("Flags", wt.DWORD),
-        ("Type", wt.DWORD),
-        ("TargetName", ct.c_wchar_p),
-        ("Comment", ct.c_wchar_p),
-        ("LastWritten", wt.FILETIME),
-        ("CredentialBlobSize", wt.DWORD),
-        ("CredentialBlob", _PBYTE),
-        ("Persist", wt.DWORD),
-        ("AttributeCount", wt.DWORD),
-        ("Attributes", ct.c_void_p),
-        ("TargetAlias", ct.c_wchar_p),
-        ("UserName", ct.c_wchar_p),
-    ]
-
-
-_PCREDENTIAL = ct.POINTER(_CREDENTIAL)
-
-_advapi = ct.WinDLL("advapi32")  # type: ignore
-_advapi.CredReadW.argtypes = [wt.LPCWSTR, wt.DWORD, wt.DWORD, ct.POINTER(_PCREDENTIAL)]
-_advapi.CredReadW.restype = wt.BOOL
-_advapi.CredFree.argtypes = [_PCREDENTIAL]
-
-
-def _read_credential(service_name, account_name):
-    target = "{}/{}".format(service_name, account_name)
-    cred_ptr = _PCREDENTIAL()
-    if _advapi.CredReadW(target, 1, 0, ct.byref(cred_ptr)):
-        cred_blob = cred_ptr.contents.CredentialBlob
-        cred_blob_size = cred_ptr.contents.CredentialBlobSize
-        cred = "".join(map(chr, cred_blob[:cred_blob_size]))
-        _advapi.CredFree(cred_ptr)
-        return cred
-    return None
-
-
-def get_user_settings():
-    try:
-        path = os.path.join(os.environ["APPDATA"], "Code", "User", "settings.json")
-        with open(path, encoding="utf-8") as file:
-            return json.load(file)
-    except Exception as ex:  # pylint:disable=broad-except
-        _LOGGER.debug('Exception reading VS Code user settings: "%s"', ex, exc_info=_LOGGER.isEnabledFor(logging.DEBUG))
-        return {}
-
-
-def get_refresh_token(cloud_name):
-    try:
-        return _read_credential(VSCODE_CREDENTIALS_SECTION, cloud_name)
-    except Exception as ex:  # pylint: disable=broad-except
-        _LOGGER.debug(
-            'Exception retrieving VS Code credentials: "%s"', ex, exc_info=_LOGGER.isEnabledFor(logging.DEBUG)
-        )
-        return None
diff --git a/sdk/identity/azure-identity/azure/identity/aio/_credentials/default.py b/sdk/identity/azure-identity/azure/identity/aio/_credentials/default.py
index 2445db573ed0..c07e6b466757 100644
--- a/sdk/identity/azure-identity/azure/identity/aio/_credentials/default.py
+++ b/sdk/identity/azure-identity/azure/identity/aio/_credentials/default.py
@@ -73,9 +73,8 @@ class DefaultAzureCredential(ChainedTokenCredential):
     :keyword str shared_cache_tenant_id: Preferred tenant for :class:`~azure.identity.aio.SharedTokenCacheCredential`.
         Defaults to the value of environment variable AZURE_TENANT_ID, if any.
     :keyword str visual_studio_code_tenant_id: Tenant ID to use when authenticating with
-        :class:`~azure.identity.aio.VisualStudioCodeCredential`. Defaults to the "Azure: Tenant" setting in VS Code's
-        user settings or, when that setting has no value, the "organizations" tenant, which supports only Azure Active
-        Directory work or school accounts.
+        :class:`~azure.identity.VisualStudioCodeCredential`. Defaults to the tenant specified in the authentication
+        record file used by the Azure Resources extension.
     :keyword int process_timeout: The timeout in seconds to use for developer credentials that run
         subprocesses (e.g. AzureCliCredential, AzurePowerShellCredential). Defaults to **10** seconds.
 
@@ -94,18 +93,10 @@ def __init__(self, **kwargs: Any) -> None:  # pylint: disable=too-many-statement
             raise TypeError("'tenant_id' is not supported in DefaultAzureCredential.")
 
         authority = kwargs.pop("authority", None)
-
-        vscode_tenant_id = kwargs.pop(
-            "visual_studio_code_tenant_id", os.environ.get(EnvironmentVariables.AZURE_TENANT_ID)
-        )
-        vscode_args = dict(kwargs)
-        if authority:
-            vscode_args["authority"] = authority
-        if vscode_tenant_id:
-            vscode_args["tenant_id"] = vscode_tenant_id
-
         authority = normalize_authority(authority) if authority else get_default_authority()
 
+        vscode_tenant_id = kwargs.pop("visual_studio_code_tenant_id", None)
+
         shared_cache_username = kwargs.pop("shared_cache_username", os.environ.get(EnvironmentVariables.AZURE_USERNAME))
         shared_cache_tenant_id = kwargs.pop(
             "shared_cache_tenant_id", os.environ.get(EnvironmentVariables.AZURE_TENANT_ID)
@@ -119,10 +110,6 @@ def __init__(self, **kwargs: Any) -> None:  # pylint: disable=too-many-statement
             "workload_identity_tenant_id", os.environ.get(EnvironmentVariables.AZURE_TENANT_ID)
         )
 
-        vscode_tenant_id = kwargs.pop(
-            "visual_studio_code_tenant_id", os.environ.get(EnvironmentVariables.AZURE_TENANT_ID)
-        )
-
         process_timeout = kwargs.pop("process_timeout", 10)
 
         # Define credential configuration mapping (async version)
@@ -148,7 +135,7 @@ def __init__(self, **kwargs: Any) -> None:  # pylint: disable=too-many-statement
             },
             "visual_studio_code": {
                 "exclude_param": "exclude_visual_studio_code_credential",
-                "default_exclude": True,
+                "default_exclude": False,
             },
             "cli": {
                 "exclude_param": "exclude_cli_credential",
@@ -221,7 +208,7 @@ def __init__(self, **kwargs: Any) -> None:  # pylint: disable=too-many-statement
             except Exception as ex:  # pylint:disable=broad-except
                 _LOGGER.info("Shared token cache is unavailable: '%s'", ex)
         if not exclude_visual_studio_code_credential:
-            credentials.append(VisualStudioCodeCredential(**vscode_args))
+            credentials.append(VisualStudioCodeCredential(tenant_id=vscode_tenant_id))
         if not exclude_cli_credential:
             credentials.append(AzureCliCredential(process_timeout=process_timeout))
         if not exclude_powershell_credential:
diff --git a/sdk/identity/azure-identity/azure/identity/aio/_credentials/vscode.py b/sdk/identity/azure-identity/azure/identity/aio/_credentials/vscode.py
index fa5aab6a29a2..8384d5b03468 100644
--- a/sdk/identity/azure-identity/azure/identity/aio/_credentials/vscode.py
+++ b/sdk/identity/azure-identity/azure/identity/aio/_credentials/vscode.py
@@ -2,49 +2,34 @@
 # Copyright (c) Microsoft Corporation.
 # Licensed under the MIT License.
 # ------------------------------------
-from typing import cast, Optional, Any
+from typing import Optional, Any
 
 from azure.core.credentials import AccessToken, AccessTokenInfo, TokenRequestOptions
-from azure.core.exceptions import ClientAuthenticationError
-from ..._exceptions import CredentialUnavailableError
 from .._internal import AsyncContextManager
-from .._internal.aad_client import AadClient
-from .._internal.get_token_mixin import GetTokenMixin
 from .._internal.decorators import log_get_token_async
-from ..._credentials.vscode import _VSCodeCredentialBase
-from ..._internal import within_dac
+from ..._credentials.vscode import VisualStudioCodeCredential as SyncVSCodeCredential
 
 
-class VisualStudioCodeCredential(_VSCodeCredentialBase, AsyncContextManager, GetTokenMixin):
-    """Authenticates as the Azure user signed in to Visual Studio Code via the 'Azure Account' extension.
+class VisualStudioCodeCredential(AsyncContextManager):
+    """Authenticates as the Azure user signed in to Visual Studio Code via the 'Azure Resources' extension.
 
-    **Deprecated**: This credential is deprecated because the Azure Account extension for Visual Studio Code, which
-    this credential relies on, has been deprecated. See the Azure Account extension deprecation notice here:
-    https://github.com/microsoft/vscode-azure-account/issues/964. Consider using other developer credentials such as
-    AzureCliCredential, AzureDeveloperCliCredential, or AzurePowerShellCredential.
-
-    :keyword str authority: Authority of a Microsoft Entra endpoint, for example "login.microsoftonline.com".
-        This argument is required for a custom cloud and usually unnecessary otherwise. Defaults to the authority
-        matching the "Azure: Cloud" setting in VS Code's user settings or, when that setting has no value, the
-        authority for Azure Public Cloud.
-    :keyword str tenant_id: ID of the tenant the credential should authenticate in. Defaults to the "Azure: Tenant"
-        setting in VS Code's user settings or, when that setting has no value, the "organizations" tenant, which
-        supports only Microsoft Entra work or school accounts.
+    :keyword str tenant_id: A Microsoft Entra tenant ID. Defaults to the tenant specified in the authentication
+        record file used by the Azure Resources extension.
     :keyword List[str] additionally_allowed_tenants: Specifies tenants in addition to the specified "tenant_id"
         for which the credential may acquire tokens. Add the wildcard value "*" to allow the credential to
         acquire tokens for any tenant the application can access.
     """
 
+    def __init__(self, **kwargs: Any) -> None:
+        self._sync_credential = SyncVSCodeCredential(**kwargs)
+
     async def __aenter__(self) -> "VisualStudioCodeCredential":
-        if self._client:
-            await self._client.__aenter__()
+        self._sync_credential.__enter__()
         return self
 
     async def close(self) -> None:
         """Close the credential's transport session."""
-
-        if self._client:
-            await self._client.__aexit__()
+        self._sync_credential.close()
 
     @log_get_token_async
     async def get_token(
@@ -66,22 +51,7 @@ async def get_token(
         :raises ~azure.identity.CredentialUnavailableError: the credential cannot retrieve user details from Visual
             Studio Code
         """
-        if self._unavailable_reason:
-            error_message = (
-                self._unavailable_reason + "\n"
-                "Visit https://aka.ms/azsdk/python/identity/vscodecredential/troubleshoot"
-                " to troubleshoot this issue."
-            )
-            raise CredentialUnavailableError(message=error_message)
-        if not self._client:
-            raise CredentialUnavailableError("Initialization failed")
-        if within_dac.get():
-            try:
-                token = await super().get_token(*scopes, claims=claims, tenant_id=tenant_id, **kwargs)
-                return token
-            except ClientAuthenticationError as ex:
-                raise CredentialUnavailableError(message=ex.message) from ex
-        return await super().get_token(*scopes, claims=claims, tenant_id=tenant_id, **kwargs)
+        return self._sync_credential.get_token(*scopes, claims=claims, tenant_id=tenant_id, **kwargs)
 
     async def get_token_info(self, *scopes: str, options: Optional[TokenRequestOptions] = None) -> AccessTokenInfo:
         """Request an access token for `scopes` as the user currently signed in to Visual Studio Code.
@@ -99,29 +69,4 @@ async def get_token_info(self, *scopes: str, options: Optional[TokenRequestOptio
         :raises ~azure.identity.CredentialUnavailableError: the credential cannot retrieve user details from Visual
           Studio Code.
         """
-        if self._unavailable_reason:
-            error_message = (
-                self._unavailable_reason + "\n"
-                "Visit https://aka.ms/azsdk/python/identity/vscodecredential/troubleshoot"
-                " to troubleshoot this issue."
-            )
-            raise CredentialUnavailableError(message=error_message)
-        if within_dac.get():
-            try:
-                token = await super().get_token_info(*scopes, options=options)
-                return token
-            except ClientAuthenticationError as ex:
-                raise CredentialUnavailableError(message=ex.message) from ex
-        return await super().get_token_info(*scopes, options=options)
-
-    async def _acquire_token_silently(self, *scopes: str, **kwargs: Any) -> Optional[AccessTokenInfo]:
-        self._client = cast(AadClient, self._client)
-        return self._client.get_cached_access_token(scopes, **kwargs)
-
-    async def _request_token(self, *scopes: str, **kwargs: Any) -> AccessTokenInfo:
-        refresh_token = self._get_refresh_token()
-        self._client = cast(AadClient, self._client)
-        return await self._client.obtain_token_by_refresh_token(scopes, refresh_token, **kwargs)
-
-    def _get_client(self, **kwargs: Any) -> AadClient:
-        return AadClient(**kwargs)
+        return self._sync_credential.get_token_info(*scopes, options=options)
diff --git a/sdk/identity/azure-identity/dev_requirements.txt b/sdk/identity/azure-identity/dev_requirements.txt
index ac8662e232da..4ae29e0b192d 100644
--- a/sdk/identity/azure-identity/dev_requirements.txt
+++ b/sdk/identity/azure-identity/dev_requirements.txt
@@ -1,4 +1,5 @@
 ../../core/azure-core
+azure-identity-broker>=1.1.0 ; platform.python_implementation != "PyPy"
 aiohttp>=3.0
 typing_extensions>=3.7.2
 -e ../../../tools/azure-sdk-tools


Test patch:
diff --git a/sdk/identity/azure-identity/tests/test_context_manager.py b/sdk/identity/azure-identity/tests/test_context_manager.py
index fed0035d07b7..354ba1945bbe 100644
--- a/sdk/identity/azure-identity/tests/test_context_manager.py
+++ b/sdk/identity/azure-identity/tests/test_context_manager.py
@@ -24,7 +24,6 @@
 import pytest
 
 from test_certificate_credential import PEM_CERT_PATH
-from test_vscode_credential import GET_USER_SETTINGS
 
 
 class CredentialFixture:
@@ -62,7 +61,6 @@ def get_credential(self, **kwargs):
         {kwarg: "..." for kwarg in ("tenant_id", "client_id", "client_secret", "user_assertion")},
     ),
     CredentialFixture(UsernamePasswordCredential, {"client_id": "...", "username": "...", "password": "..."}),
-    CredentialFixture(VisualStudioCodeCredential, ctor_patch_factory=lambda: patch(GET_USER_SETTINGS, lambda: {})),
 )
 
 all_fixtures = pytest.mark.parametrize("fixture", FIXTURES, ids=lambda fixture: fixture.cls.__name__)
diff --git a/sdk/identity/azure-identity/tests/test_vscode_credential.py b/sdk/identity/azure-identity/tests/test_vscode_credential.py
index 4fb643d3ec92..f23086d82223 100644
--- a/sdk/identity/azure-identity/tests/test_vscode_credential.py
+++ b/sdk/identity/azure-identity/tests/test_vscode_credential.py
@@ -2,366 +2,188 @@
 # Copyright (c) Microsoft Corporation.
 # Licensed under the MIT License.
 # ------------------------------------
-import sys
-import time
-from unittest import mock
-from urllib.parse import urlparse
+import json
+import os
+import platform
+import tempfile
+from unittest.mock import patch
 
-from azure.core.credentials import AccessToken
-from azure.core.exceptions import ClientAuthenticationError
-from azure.identity import AzureAuthorityHosts, CredentialUnavailableError, VisualStudioCodeCredential
-from azure.core.pipeline.policies import SansIOHTTPPolicy
-from azure.identity._constants import EnvironmentVariables
-from azure.identity._internal.user_agent import USER_AGENT
 import pytest
 
-from helpers import build_aad_response, mock_response, Request, validating_transport
-
-
-GET_REFRESH_TOKEN = VisualStudioCodeCredential.__module__ + ".get_refresh_token"
-GET_USER_SETTINGS = VisualStudioCodeCredential.__module__ + ".get_user_settings"
-
-
-def get_credential(user_settings=None, **kwargs):
-    # defaulting to empty user settings ensures tests work when real user settings are available
-    with mock.patch(GET_USER_SETTINGS, lambda: user_settings or {}):
-        return VisualStudioCodeCredential(**kwargs)
-
-
-@pytest.mark.skip(reason="VS code credential is disabled")
-def test_tenant_id():
-    def get_transport(expected_tenant):
-        return validating_transport(
-            requests=[
-                Request(base_url="https://{}/{}".format(AzureAuthorityHosts.AZURE_PUBLIC_CLOUD, expected_tenant))
-            ],
-            responses=[mock_response(json_payload=build_aad_response(access_token="**"))],
-        )
-
-    # credential should default to "organizations" tenant
-    transport = get_transport("organizations")
-    credential = get_credential(transport=transport)
-    with mock.patch(GET_REFRESH_TOKEN, lambda _: "**"):
-        credential.get_token("scope")
-    assert transport.send.call_count == 1
-
-    # ... unless VS Code has a tenant configured
-    user_settings = {"azure.tenant": "vs-code-setting"}
-    transport = get_transport(user_settings["azure.tenant"])
-    credential = get_credential(user_settings, transport=transport)
-    with mock.patch(GET_REFRESH_TOKEN, lambda _: "**"):
-        credential.get_token("scope")
-    assert transport.send.call_count == 1
-
-    # ... and a tenant specified by the application prevails over VS Code configuration
-    transport = get_transport("from-application")
-    credential = get_credential(user_settings, tenant_id="from-application", transport=transport)
-    with mock.patch(GET_REFRESH_TOKEN, lambda _: "**"):
-        credential.get_token("scope")
-    assert transport.send.call_count == 1
-
+from azure.core.exceptions import ClientAuthenticationError
+from azure.identity import AuthenticationRecord, CredentialUnavailableError
+from azure.identity._constants import AZURE_VSCODE_CLIENT_ID, KnownAuthorities
+from azure.identity._credentials.vscode import VisualStudioCodeCredential, load_vscode_auth_record
 
-@pytest.mark.skip(reason="VS code credential is disabled")
-def test_tenant_id_validation():
-    """The credential should raise ValueError when given an invalid tenant_id"""
-
-    valid_ids = {"c878a2ab-8ef4-413b-83a0-199afb84d7fb", "contoso.onmicrosoft.com", "organizations", "common"}
-    for tenant in valid_ids:
-        get_credential(tenant_id=tenant)
-
-    invalid_ids = {"my tenant", "my_tenant", "/", "\\", '"my-tenant"', "'my-tenant'"}
-    for tenant in invalid_ids:
-        with pytest.raises(ValueError):
-            get_credential(tenant_id=tenant)
-
-
-@pytest.mark.skip(reason="VS code credential is disabled")
-def test_no_scopes():
-    """The credential should raise ValueError when get_token is called with no scopes"""
-
-    credential = get_credential()
-    with pytest.raises(ValueError):
-        credential.get_token()
-
-
-@pytest.mark.skip(reason="VS code credential is disabled")
-def test_policies_configurable():
-    policy = mock.Mock(spec_set=SansIOHTTPPolicy, on_request=mock.Mock())
-
-    def send(*_, **kwargs):
-        # ensure the `claims` and `tenant_id` keywords from credential's `get_token` method don't make it to transport
-        assert "claims" not in kwargs
-        assert "tenant_id" not in kwargs
-        return mock_response(json_payload=build_aad_response(access_token="**"))
-
-    credential = get_credential(policies=[policy], transport=mock.Mock(send=send))
-    with mock.patch(GET_REFRESH_TOKEN, lambda _: "**"):
-        credential.get_token("scope")
-
-    assert policy.on_request.called
-
-
-@pytest.mark.skip(reason="VS code credential is disabled")
-def test_user_agent():
-    transport = validating_transport(
-        requests=[Request(required_headers={"User-Agent": USER_AGENT})],
-        responses=[mock_response(json_payload=build_aad_response(access_token="**"))],
-    )
-    credential = get_credential(transport=transport)
-    with mock.patch(GET_REFRESH_TOKEN, lambda _: "**"):
-        credential.get_token("scope")
-
-
-@pytest.mark.skip(reason="VS code credential is disabled")
-@pytest.mark.parametrize("authority", ("localhost", "https://localhost"))
-def test_request_url(authority):
-    """the credential should accept an authority, with or without scheme, as an argument or environment variable"""
-
-    tenant_id = "expected-tenant"
-    access_token = "***"
-    parsed_authority = urlparse(authority)
-    expected_netloc = parsed_authority.netloc or authority  # "localhost" parses to netloc "", path "localhost"
-    expected_refresh_token = "refresh-token"
-
-    def mock_send(request, **kwargs):
-        actual = urlparse(request.url)
-        assert actual.scheme == "https"
-        assert actual.netloc == expected_netloc
-        assert actual.path.startswith("/" + tenant_id)
-        assert request.body["refresh_token"] == expected_refresh_token
-        return mock_response(json_payload={"token_type": "Bearer", "expires_in": 42, "access_token": access_token})
-
-    credential = get_credential(tenant_id=tenant_id, transport=mock.Mock(send=mock_send), authority=authority)
-    with mock.patch(GET_REFRESH_TOKEN, return_value=expected_refresh_token):
-        token = credential.get_token("scope")
-    assert token.token == access_token
-
-    # authority can be configured via environment variable
-    with mock.patch.dict("os.environ", {EnvironmentVariables.AZURE_AUTHORITY_HOST: authority}):
-        credential = get_credential(tenant_id=tenant_id, transport=mock.Mock(send=mock_send))
-        with mock.patch(GET_REFRESH_TOKEN, return_value=expected_refresh_token):
-            credential.get_token("scope")
-    assert token.token == access_token
-
-
-@pytest.mark.skip(reason="VS code credential is disabled")
-def test_credential_unavailable_error():
-    credential = get_credential()
-    with mock.patch(GET_REFRESH_TOKEN, return_value=None):
-        with pytest.raises(CredentialUnavailableError):
-            credential.get_token("scope")
-
-
-@pytest.mark.skip(reason="VS code credential is disabled")
-def test_redeem_token():
-    expected_token = AccessToken("token", 42)
-    expected_value = "value"
-
-    mock_client = mock.Mock(spec=object)
-    mock_client.obtain_token_by_refresh_token = mock.Mock(return_value=expected_token)
-    mock_client.get_cached_access_token = mock.Mock(return_value=None)
-
-    with mock.patch(GET_REFRESH_TOKEN, return_value=expected_value):
-        credential = get_credential(_client=mock_client)
-        token = credential.get_token("scope")
-        assert token is expected_token
-        mock_client.obtain_token_by_refresh_token.assert_called_with(
-            ("scope",), expected_value, claims=None, tenant_id=None
-        )
-        assert mock_client.obtain_token_by_refresh_token.call_count == 1
-
-
-@pytest.mark.skip(reason="VS code credential is disabled")
-def test_cache_refresh_token():
-    expected_token = AccessToken("token", 42)
-
-    mock_client = mock.Mock(spec=object)
-    mock_client.obtain_token_by_refresh_token = mock.Mock(return_value=expected_token)
-    mock_client.get_cached_access_token = mock.Mock(return_value=None)
-    mock_get_credentials = mock.Mock(return_value="VALUE")
-
-    with mock.patch(GET_REFRESH_TOKEN, mock_get_credentials):
-        credential = get_credential(_client=mock_client)
-        token = credential.get_token("scope")
-        assert token is expected_token
-        assert mock_get_credentials.call_count == 1
-        token = credential.get_token("scope")
-        assert token is expected_token
-        assert mock_get_credentials.call_count == 1
-
-
-@pytest.mark.skip(reason="VS code credential is disabled")
-def test_no_obtain_token_if_cached():
-    expected_token = AccessToken("token", time.time() + 3600)
-
-    mock_client = mock.Mock(
-        obtain_token_by_refresh_token=mock.Mock(return_value=expected_token),
-        get_cached_access_token=mock.Mock(return_value=expected_token),
-    )
-
-    credential = get_credential(_client=mock_client)
-    with mock.patch(
-        GET_REFRESH_TOKEN,
-        mock.Mock(side_effect=Exception("credential should not acquire a new token")),
-    ):
-        token = credential.get_token("scope")
-
-    assert mock_client.obtain_token_by_refresh_token.call_count == 0
-    assert token.token == expected_token.token
-    assert token.expires_on == expected_token.expires_on
-
-
-@pytest.mark.skip(reason="VS code credential is disabled")
-def test_native_adapter():
-    """Exercise the native adapter for the current OS"""
-
-    if sys.platform.startswith("darwin"):
-        from azure.identity._internal.macos_vscode_adapter import get_refresh_token
-    elif sys.platform.startswith("linux"):
-        from azure.identity._internal.linux_vscode_adapter import get_refresh_token
-    elif sys.platform.startswith("win"):
-        from azure.identity._internal.win_vscode_adapter import get_refresh_token
-    else:
-        pytest.skip('unsupported platform "{}"'.format(sys.platform))
-
-    # the return value (None in CI, possibly something else on a dev machine) is irrelevant
-    # because the goal is simply to expose a native interop problem like a segfault
-    get_refresh_token("AzureCloud")
-
-
-@pytest.mark.skip(reason="VS code credential is disabled")
-def test_adfs():
-    """The credential should raise CredentialUnavailableError when configured for ADFS"""
-
-    credential = get_credential(tenant_id="adfs")
-    with pytest.raises(CredentialUnavailableError) as ex:
-        credential.get_token("scope")
-    assert "adfs" in ex.value.message.lower()
-
-
-@pytest.mark.skip(reason="VS code credential is disabled")
-def test_custom_cloud_no_authority():
-    """The credential is unavailable when VS Code is configured to use a custom cloud with no known authority"""
-
-    cloud_name = "AzureCustomCloud"
-    credential = get_credential({"azure.cloud": cloud_name})
-    with pytest.raises(CredentialUnavailableError, match="authority.*" + cloud_name):
-        credential.get_token("scope")
-
-
-@pytest.mark.skip(reason="VS code credential is disabled")
-@pytest.mark.parametrize(
-    "cloud,authority",
-    (
-        ("AzureCloud", AzureAuthorityHosts.AZURE_PUBLIC_CLOUD),
-        ("AzureChinaCloud", AzureAuthorityHosts.AZURE_CHINA),
-        ("AzureUSGovernment", AzureAuthorityHosts.AZURE_GOVERNMENT),
-    ),
+# Skip all tests in this module when running on PyPy
+pytestmark = pytest.mark.skipif(
+    platform.python_implementation() == "PyPy", reason="Broker tests are not supported on PyPy"
 )
-def test_reads_cloud_settings(cloud, authority):
-    """the credential should read authority and tenant from VS Code settings when an application doesn't specify them"""
-
-    expected_tenant = "tenant-id"
-    user_settings = {"azure.cloud": cloud, "azure.tenant": expected_tenant}
-
-    transport = validating_transport(
-        requests=[Request(base_url="https://{}/{}".format(authority, expected_tenant))],
-        responses=[mock_response(json_payload=build_aad_response(access_token="**"))],
-    )
-
-    credential = get_credential(user_settings, transport=transport)
-
-    with mock.patch(GET_REFRESH_TOKEN, lambda _: "**"):
-        credential.get_token("scope")
-
-    assert transport.send.call_count == 1
-
-
-@pytest.mark.skip(reason="VS code credential is disabled")
-def test_no_user_settings():
-    """the credential should default to Public Cloud and "organizations" tenant when it can't read VS Code settings"""
-
-    transport = validating_transport(
-        requests=[Request(base_url="https://{}/{}".format(AzureAuthorityHosts.AZURE_PUBLIC_CLOUD, "organizations"))],
-        responses=[mock_response(json_payload=build_aad_response(access_token="**"))],
-    )
-
-    credential = get_credential(transport=transport)
-    with mock.patch(GET_REFRESH_TOKEN, lambda _: "**"):
-        credential.get_token("scope")
-
-    assert transport.send.call_count == 1
-
-
-@pytest.mark.skip(reason="VS code credential is disabled")
-def test_multitenant_authentication():
-    first_tenant = "first-tenant"
-    first_token = "***"
-    second_tenant = "second-tenant"
-    second_token = first_token * 2
-
-    def send(request, **kwargs):
-        # ensure the `claims` and `tenant_id` keywords from credential's `get_token` method don't make it to transport
-        assert "claims" not in kwargs
-        assert "tenant_id" not in kwargs
-        parsed = urlparse(request.url)
-        tenant = parsed.path.split("/")[1]
-        assert tenant in (first_tenant, second_tenant), 'unexpected tenant "{}"'.format(tenant)
-        token = first_token if tenant == first_tenant else second_token
-        return mock_response(json_payload=build_aad_response(access_token=token))
-
-    credential = get_credential(
-        tenant_id=first_tenant, transport=mock.Mock(send=send), additionally_allowed_tenants=["*"]
-    )
-    with mock.patch(GET_REFRESH_TOKEN, lambda _: "**"):
-        token = credential.get_token("scope")
-    assert token.token == first_token
-
-    token = credential.get_token("scope", tenant_id=first_tenant)
-    assert token.token == first_token
-
-    with mock.patch(GET_REFRESH_TOKEN, lambda _: "**"):
-        token = credential.get_token("scope", tenant_id=second_tenant)
-    assert token.token == second_token
-
-    # should still default to the first tenant
-    token = credential.get_token("scope")
-    assert token.token == first_token
-
-
-@pytest.mark.skip(reason="VS code credential is disabled")
-def test_multitenant_authentication_not_allowed():
-    expected_tenant = "expected-tenant"
-    expected_token = "***"
-
-    def send(request, **kwargs):
-        # ensure the `claims` and `tenant_id` keywords from credential's `get_token` method don't make it to transport
-        assert "claims" not in kwargs
-        assert "tenant_id" not in kwargs
-        parsed = urlparse(request.url)
-        tenant = parsed.path.split("/")[1]
-        token = expected_token if tenant == expected_tenant else expected_token * 2
-        return mock_response(json_payload=build_aad_response(access_token=token))
-
-    credential = get_credential(
-        tenant_id=expected_tenant, transport=mock.Mock(send=send), additionally_allowed_tenants=["*"]
-    )
-
-    with mock.patch(GET_REFRESH_TOKEN, lambda _: "**"):
-        token = credential.get_token("scope")
-    assert token.token == expected_token
-
-    token = credential.get_token("scope", tenant_id=expected_tenant)
-    assert token.token == expected_token
-
-    token = credential.get_token("scope", tenant_id="un" + expected_tenant)
-    assert token.token == expected_token * 2
-
-    with mock.patch.dict("os.environ", {EnvironmentVariables.AZURE_IDENTITY_DISABLE_MULTITENANTAUTH: "true"}):
-        token = credential.get_token("scope", tenant_id="un" + expected_tenant)
-        assert token.token == expected_token
 
 
-def test_deprecation_warning():
-    with pytest.deprecated_call():
-        get_credential()
+class TestVisualStudioCodeCredential:
+    """Test cases for VisualStudioCodeCredential"""
+
+    def test_get_token_info(self):
+        """Test getting a token from the credential."""
+        valid_data = {
+            "tenantId": "12345678-1234-1234-1234-123456789012",
+            "clientId": AZURE_VSCODE_CLIENT_ID,
+            "username": "user@example.com",
+            "homeAccountId": "user.tenant",
+            "authority": KnownAuthorities.AZURE_PUBLIC_CLOUD,
+        }
+
+        with tempfile.NamedTemporaryFile(mode="w", suffix=".json", delete=False) as tmp_file:
+            json.dump(valid_data, tmp_file)
+            tmp_file.flush()
+
+        try:
+            with patch("os.path.expanduser", return_value=tmp_file.name):
+                with patch("msal.PublicClientApplication"):
+                    with patch("msal.PublicClientApplication.acquire_token_interactive"):
+                        credential = VisualStudioCodeCredential()
+                        with pytest.raises(ClientAuthenticationError):
+                            credential.get_token_info("https://management.azure.com/.default")
+        finally:
+            os.unlink(tmp_file.name)
+
+    def test_invalid_auth_record(self):
+        """Test that an error is raised if the auth record is nonexistent/invalid."""
+
+        # Test with a nonexistent file
+        with patch("os.path.expanduser", return_value="nonexistent_file.json"):
+            with pytest.raises(CredentialUnavailableError):
+                VisualStudioCodeCredential().get_token_info("https://management.azure.com/.default")
+
+        # Test with invalid data (incorrect client ID)
+        invalid_data = {
+            "tenantId": "12345678-1234-1234-1234-123456789012",
+            "clientId": "12345-123456",
+            "username": "user@example.com",
+            "homeAccountId": "user.tenant",
+            "authority": KnownAuthorities.AZURE_PUBLIC_CLOUD,
+        }
+        with tempfile.NamedTemporaryFile(mode="w", suffix=".json", delete=False) as tmp_file:
+            json.dump(invalid_data, tmp_file)
+            tmp_file.flush()
+
+        try:
+            with patch("os.path.expanduser", return_value=tmp_file.name):
+                with pytest.raises(CredentialUnavailableError):
+                    VisualStudioCodeCredential().get_token_info("https://management.azure.com/.default")
+        finally:
+            os.unlink(tmp_file.name)
+
+    def test_broker_credential_requirements_not_installed(self):
+        """Test that the credential w"""
+
+        with patch.dict("sys.modules", {"azure.identity.broker": None}):
+            with patch("azure.identity.broker.InteractiveBrowserBrokerCredential") as mock_credential:
+                with pytest.raises(CredentialUnavailableError):
+                    # This should raise an error because the broker requirements are not installed.
+                    VisualStudioCodeCredential().get_token_info("https://management.azure.com/.default")
+
+        assert mock_credential.call_count == 0, "InteractiveBrowserBrokerCredential should not be instantiated"
+
+
+class TestLoadVSCodeAuthRecord:
+    """Test cases for loading VS Code authentication records."""
+
+    def test_load_nonexistent_file(self):
+        """Test loading returns None when auth record file doesn't exist."""
+        with patch("os.path.exists", return_value=False):
+            result = load_vscode_auth_record()
+            assert result is None
+
+    def test_load_valid_record(self):
+        """Test loading a valid authentication record."""
+        valid_data = {
+            "tenantId": "12345678-1234-1234-1234-123456789012",
+            "clientId": AZURE_VSCODE_CLIENT_ID,
+            "username": "user@example.com",
+            "homeAccountId": "user.tenant",
+            "authority": KnownAuthorities.AZURE_PUBLIC_CLOUD,
+        }
+
+        with tempfile.NamedTemporaryFile(mode="w", suffix=".json", delete=False) as tmp_file:
+            json.dump(valid_data, tmp_file)
+            tmp_file.flush()
+
+        try:
+            with patch("os.path.expanduser", return_value=tmp_file.name):
+                with patch("os.path.exists", return_value=True):
+                    result = load_vscode_auth_record()
+
+                    assert result is not None
+                    assert isinstance(result, AuthenticationRecord)
+                    assert result.tenant_id == valid_data["tenantId"]
+                    assert result.client_id == valid_data["clientId"]
+                    assert result.username == valid_data["username"]
+                    assert result.home_account_id == valid_data["homeAccountId"]
+                    assert result.authority == valid_data["authority"]
+        finally:
+            os.unlink(tmp_file.name)
+
+    def test_load_malformed_json(self):
+        """Test loading fails with malformed JSON."""
+        malformed_json = '{"tenantId": "test", "clientId": '  # incomplete JSON
+
+        with tempfile.NamedTemporaryFile(mode="w", suffix=".json", delete=False) as tmp_file:
+            tmp_file.write(malformed_json)
+            tmp_file.flush()
+
+        try:
+            with patch("os.path.expanduser", return_value=tmp_file.name):
+                with patch("os.path.exists", return_value=True):
+                    with pytest.raises(ValueError):
+                        load_vscode_auth_record()
+        finally:
+            os.unlink(tmp_file.name)
+
+    def test_load_invalid_record(self):
+        """Test loading fails with invalid authentication record data."""
+        invalid_data = {
+            "tenantId": "12345678-1234-1234-1234-123456789012",
+            "clientId": "wrong-client-id",  # Invalid client ID
+            "username": "user@example.com",
+            "homeAccountId": "user.tenant",
+            "authority": KnownAuthorities.AZURE_PUBLIC_CLOUD,
+        }
+
+        with tempfile.NamedTemporaryFile(mode="w", suffix=".json", delete=False) as tmp_file:
+            json.dump(invalid_data, tmp_file)
+            tmp_file.flush()
+
+        try:
+            with patch("os.path.expanduser", return_value=tmp_file.name):
+                with patch("os.path.exists", return_value=True):
+                    with pytest.raises(ValueError, match="Authentication record validation failed"):
+                        load_vscode_auth_record()
+        finally:
+            os.unlink(tmp_file.name)
+
+    def test_load_missing_required_fields(self):
+        """Test loading fails when required fields are missing."""
+        incomplete_data = {
+            "tenantId": "12345678-1234-1234-1234-123456789012",
+            "clientId": AZURE_VSCODE_CLIENT_ID,
+            # Missing username, homeAccountId, authority
+        }
+
+        with tempfile.NamedTemporaryFile(mode="w", suffix=".json", delete=False) as tmp_file:
+            json.dump(incomplete_data, tmp_file)
+            tmp_file.flush()
+
+        try:
+            with patch("os.path.expanduser", return_value=tmp_file.name):
+                with patch("os.path.exists", return_value=True):
+                    with pytest.raises(ValueError) as exc_info:
+                        load_vscode_auth_record()
+
+                    error_message = str(exc_info.value)
+                    assert "username field is missing" in error_message
+                    assert "homeAccountId field is missing" in error_message
+                    assert "authority field is missing" in error_message
+        finally:
+            os.unlink(tmp_file.name)
diff --git a/sdk/identity/azure-identity/tests/test_vscode_credential_async.py b/sdk/identity/azure-identity/tests/test_vscode_credential_async.py
index 7e4bf27c671e..aee22c19e07e 100644
--- a/sdk/identity/azure-identity/tests/test_vscode_credential_async.py
+++ b/sdk/identity/azure-identity/tests/test_vscode_credential_async.py
@@ -2,357 +2,27 @@
 # Copyright (c) Microsoft Corporation.
 # Licensed under the MIT License.
 # ------------------------------------
-import time
-from unittest import mock
-from urllib.parse import urlparse
+from unittest.mock import patch
 
-from azure.core.credentials import AccessToken
-from azure.core.exceptions import ClientAuthenticationError
-from azure.identity import AzureAuthorityHosts, CredentialUnavailableError
-from azure.identity._constants import EnvironmentVariables
-from azure.identity._internal.user_agent import USER_AGENT
-from azure.identity.aio import VisualStudioCodeCredential
-from azure.core.pipeline.policies import SansIOHTTPPolicy
 import pytest
-
-from helpers import build_aad_response, mock_response, Request
-from helpers_async import async_validating_transport, wrap_in_future
-from test_vscode_credential import GET_REFRESH_TOKEN, GET_USER_SETTINGS
-
-
-def get_credential(user_settings=None, **kwargs):
-    # defaulting to empty user settings ensures tests work when real user settings are available
-    with mock.patch(GET_USER_SETTINGS, lambda: user_settings or {}):
-        return VisualStudioCodeCredential(**kwargs)
-
-
-@pytest.mark.skip(reason="VS code credential is disabled")
-@pytest.mark.asyncio
-async def test_tenant_id():
-    def get_transport(expected_tenant):
-        return async_validating_transport(
-            requests=[
-                Request(base_url="https://{}/{}".format(AzureAuthorityHosts.AZURE_PUBLIC_CLOUD, expected_tenant))
-            ],
-            responses=[mock_response(json_payload=build_aad_response(access_token="**"))],
-        )
-
-    # credential should default to "organizations" tenant
-    transport = get_transport("organizations")
-    credential = get_credential(transport=transport)
-    with mock.patch(GET_REFRESH_TOKEN, lambda _: "**"):
-        await credential.get_token("scope")
-    assert transport.send.call_count == 1
-
-    # ... unless VS Code has a tenant configured
-    user_settings = {"azure.tenant": "vs-code-setting"}
-    transport = get_transport(user_settings["azure.tenant"])
-    credential = get_credential(user_settings, transport=transport)
-    with mock.patch(GET_REFRESH_TOKEN, lambda _: "**"):
-        await credential.get_token("scope")
-    assert transport.send.call_count == 1
-
-    # ... and a tenant specified by the application prevails over VS Code configuration
-    transport = get_transport("from-application")
-    credential = get_credential(user_settings, tenant_id="from-application", transport=transport)
-    with mock.patch(GET_REFRESH_TOKEN, lambda _: "**"):
-        await credential.get_token("scope")
-    assert transport.send.call_count == 1
-
-
-@pytest.mark.skip(reason="VS code credential is disabled")
-def test_tenant_id_validation():
-    """The credential should raise ValueError when given an invalid tenant_id"""
-
-    valid_ids = {"c878a2ab-8ef4-413b-83a0-199afb84d7fb", "contoso.onmicrosoft.com", "organizations", "common"}
-    for tenant in valid_ids:
-        get_credential(tenant_id=tenant)
-
-    invalid_ids = {"my tenant", "my_tenant", "/", "\\", '"my-tenant"', "'my-tenant'"}
-    for tenant in invalid_ids:
-        with pytest.raises(ValueError):
-            get_credential(tenant_id=tenant)
-
-
-@pytest.mark.skip(reason="VS code credential is disabled")
-@pytest.mark.asyncio
-async def test_no_scopes():
-    """The credential should raise ValueError when get_token is called with no scopes"""
-
-    credential = get_credential()
-    with pytest.raises(ValueError):
-        await credential.get_token()
-
-
-@pytest.mark.skip(reason="VS code credential is disabled")
-@pytest.mark.asyncio
-async def test_policies_configurable():
-    policy = mock.Mock(spec_set=SansIOHTTPPolicy, on_request=mock.Mock())
-
-    async def send(*_, **kwargs):
-        # ensure the `claims` and `tenant_id` keywords from credential's `get_token` method don't make it to transport
-        assert "claims" not in kwargs
-        assert "tenant_id" not in kwargs
-        return mock_response(json_payload=build_aad_response(access_token="**"))
-
-    credential = get_credential(policies=[policy], transport=mock.Mock(send=send))
-    with mock.patch(GET_REFRESH_TOKEN, lambda _: "**"):
-        await credential.get_token("scope")
-
-    assert policy.on_request.called
-
-
-@pytest.mark.skip(reason="VS code credential is disabled")
-@pytest.mark.asyncio
-async def test_user_agent():
-    transport = async_validating_transport(
-        requests=[Request(required_headers={"User-Agent": USER_AGENT})],
-        responses=[mock_response(json_payload=build_aad_response(access_token="**"))],
-    )
-    credential = get_credential(transport=transport)
-    with mock.patch(GET_REFRESH_TOKEN, lambda _: "**"):
-        await credential.get_token("scope")
-
-
-@pytest.mark.skip(reason="VS code credential is disabled")
-@pytest.mark.asyncio
-@pytest.mark.parametrize("authority", ("localhost", "https://localhost"))
-async def test_request_url(authority):
-    """the credential should accept an authority, with or without scheme, as an argument or environment variable"""
-
-    tenant_id = "expected-tenant"
-    access_token = "***"
-    parsed_authority = urlparse(authority)
-    expected_netloc = parsed_authority.netloc or authority  # "localhost" parses to netloc "", path "localhost"
-    expected_refresh_token = "refresh-token"
-
-    async def mock_send(request, **kwargs):
-        actual = urlparse(request.url)
-        assert actual.scheme == "https"
-        assert actual.netloc == expected_netloc
-        assert actual.path.startswith("/" + tenant_id)
-        assert request.body["refresh_token"] == expected_refresh_token
-        return mock_response(json_payload={"token_type": "Bearer", "expires_in": 42, "access_token": access_token})
-
-    credential = get_credential(tenant_id=tenant_id, transport=mock.Mock(send=mock_send), authority=authority)
-    with mock.patch(GET_REFRESH_TOKEN, return_value=expected_refresh_token):
-        token = await credential.get_token("scope")
-    assert token.token == access_token
-
-    # authority can be configured via environment variable
-    with mock.patch.dict("os.environ", {EnvironmentVariables.AZURE_AUTHORITY_HOST: authority}, clear=True):
-        credential = get_credential(tenant_id=tenant_id, transport=mock.Mock(send=mock_send))
-        with mock.patch(GET_REFRESH_TOKEN, return_value=expected_refresh_token):
-            await credential.get_token("scope")
-    assert token.token == access_token
-
-
-@pytest.mark.skip(reason="VS code credential is disabled")
-@pytest.mark.asyncio
-async def test_credential_unavailable_error():
-    credential = get_credential()
-    with mock.patch(GET_REFRESH_TOKEN, return_value=None):
-        with pytest.raises(CredentialUnavailableError):
-            await credential.get_token("scope")
-
-
-@pytest.mark.skip(reason="VS code credential is disabled")
-@pytest.mark.asyncio
-async def test_redeem_token():
-    expected_token = AccessToken("token", 42)
-    expected_value = "value"
-
-    mock_client = mock.Mock(spec=object)
-    token_by_refresh_token = mock.Mock(return_value=expected_token)
-    mock_client.obtain_token_by_refresh_token = wrap_in_future(token_by_refresh_token)
-    mock_client.get_cached_access_token = mock.Mock(return_value=None)
-
-    with mock.patch(GET_REFRESH_TOKEN, return_value=expected_value):
-        credential = get_credential(_client=mock_client)
-        token = await credential.get_token("scope")
-        assert token is expected_token
-        token_by_refresh_token.assert_called_with(("scope",), expected_value, claims=None, tenant_id=None)
-
-
-@pytest.mark.asyncio
-async def test_cache_refresh_token():
-    expected_token = AccessToken("token", 42)
-
-    mock_client = mock.Mock(spec=object)
-    token_by_refresh_token = mock.Mock(return_value=expected_token)
-    mock_client.obtain_token_by_refresh_token = wrap_in_future(token_by_refresh_token)
-    mock_client.get_cached_access_token = mock.Mock(return_value=None)
-    mock_get_credentials = mock.Mock(return_value="VALUE")
-
-    credential = get_credential(_client=mock_client)
-    with mock.patch(GET_REFRESH_TOKEN, mock_get_credentials):
-        await credential.get_token("scope")
-        assert mock_get_credentials.call_count == 1
-        await credential.get_token("scope")
-        assert mock_get_credentials.call_count == 1
-
-
-@pytest.mark.skip(reason="VS code credential is disabled")
-@pytest.mark.asyncio
-async def test_no_obtain_token_if_cached():
-    expected_token = AccessToken("token", time.time() + 3600)
-
-    token_by_refresh_token = mock.Mock(return_value=expected_token)
-    mock_client = mock.Mock(
-        get_cached_access_token=mock.Mock(return_value=expected_token),
-        obtain_token_by_refresh_token=wrap_in_future(token_by_refresh_token),
-    )
-
-    credential = get_credential(_client=mock_client)
-    with mock.patch(
-        GET_REFRESH_TOKEN,
-        mock.Mock(side_effect=Exception("credential should not acquire a new token")),
-    ):
-        token = await credential.get_token("scope")
-
-    assert token_by_refresh_token.call_count == 0
-    assert token.token == expected_token.token
-    assert token.expires_on == expected_token.expires_on
-
-
-@pytest.mark.skip(reason="VS code credential is disabled")
-@pytest.mark.asyncio
-async def test_adfs():
-    """The credential should raise CredentialUnavailableError when configured for ADFS"""
-
-    credential = get_credential(tenant_id="adfs")
-    with pytest.raises(CredentialUnavailableError) as ex:
-        await credential.get_token("scope")
-    assert "adfs" in ex.value.message.lower()
-
-
-@pytest.mark.skip(reason="VS code credential is disabled")
-@pytest.mark.asyncio
-async def test_custom_cloud_no_authority():
-    """The credential is unavailable when VS Code is configured to use a cloud with no known authority"""
-
-    cloud_name = "AzureCustomCloud"
-    credential = get_credential({"azure.cloud": cloud_name})
-    with pytest.raises(CredentialUnavailableError, match="authority.*" + cloud_name):
-        await credential.get_token("scope")
-
-
-@pytest.mark.skip(reason="VS code credential is disabled")
-@pytest.mark.asyncio
-@pytest.mark.parametrize(
-    "cloud,authority",
-    (
-        ("AzureCloud", AzureAuthorityHosts.AZURE_PUBLIC_CLOUD),
-        ("AzureChinaCloud", AzureAuthorityHosts.AZURE_CHINA),
-        ("AzureUSGovernment", AzureAuthorityHosts.AZURE_GOVERNMENT),
-    ),
-)
-async def test_reads_cloud_settings(cloud, authority):
-    """the credential should read authority and tenant from VS Code settings when an application doesn't specify them"""
-
-    expected_tenant = "tenant-id"
-    user_settings = {"azure.cloud": cloud, "azure.tenant": expected_tenant}
-
-    transport = async_validating_transport(
-        requests=[Request(base_url="https://{}/{}".format(authority, expected_tenant))],
-        responses=[mock_response(json_payload=build_aad_response(access_token="**"))],
-    )
-
-    credential = get_credential(user_settings, transport=transport)
-    with mock.patch(GET_REFRESH_TOKEN, lambda _: "**"):
-        await credential.get_token("scope")
-
-    assert transport.send.call_count == 1
-
-
-@pytest.mark.skip(reason="VS code credential is disabled")
-@pytest.mark.asyncio
-async def test_no_user_settings():
-    """the credential should default to Public Cloud and "organizations" tenant when it can't read VS Code settings"""
-
-    transport = async_validating_transport(
-        requests=[Request(base_url="https://{}/{}".format(AzureAuthorityHosts.AZURE_PUBLIC_CLOUD, "organizations"))],
-        responses=[mock_response(json_payload=build_aad_response(access_token="**"))],
-    )
-
-    credential = get_credential(transport=transport)
-    with mock.patch(GET_REFRESH_TOKEN, lambda _: "**"):
-        await credential.get_token("scope")
-
-    assert transport.send.call_count == 1
-
-
-@pytest.mark.skip(reason="VS code credential is disabled")
-@pytest.mark.asyncio
-async def test_multitenant_authentication():
-    first_tenant = "first-tenant"
-    first_token = "***"
-    second_tenant = "second-tenant"
-    second_token = first_token * 2
-
-    async def send(request, **kwargs):
-        # ensure the `claims` and `tenant_id` keywords from credential's `get_token` method don't make it to transport
-        assert "claims" not in kwargs
-        assert "tenant_id" not in kwargs
-        parsed = urlparse(request.url)
-        tenant = parsed.path.split("/")[1]
-        assert tenant in (first_tenant, second_tenant), 'unexpected tenant "{}"'.format(tenant)
-        token = first_token if tenant == first_tenant else second_token
-        return mock_response(json_payload=build_aad_response(access_token=token))
-
-    credential = get_credential(
-        tenant_id=first_tenant, transport=mock.Mock(send=send), additionally_allowed_tenants=["*"]
-    )
-    with mock.patch(GET_REFRESH_TOKEN, lambda _: "**"):
-        token = await credential.get_token("scope")
-    assert token.token == first_token
-
-    token = await credential.get_token("scope", tenant_id=first_tenant)
-    assert token.token == first_token
-
-    with mock.patch(GET_REFRESH_TOKEN, lambda _: "**"):
-        token = await credential.get_token("scope", tenant_id=second_tenant)
-    assert token.token == second_token
-
-    # should still default to the first tenant
-    token = await credential.get_token("scope")
-    assert token.token == first_token
-
-
-@pytest.mark.skip(reason="VS code credential is disabled")
-@pytest.mark.asyncio
-async def test_multitenant_authentication_not_allowed():
-    expected_tenant = "expected-tenant"
-    expected_token = "***"
-
-    async def send(request, **kwargs):
-        # ensure the `claims` and `tenant_id` keywords from credential's `get_token` method don't make it to transport
-        assert "claims" not in kwargs
-        assert "tenant_id" not in kwargs
-        parsed = urlparse(request.url)
-        tenant = parsed.path.split("/")[1]
-        token = expected_token if tenant == expected_tenant else expected_token * 2
-        return mock_response(json_payload=build_aad_response(access_token=token))
-
-    credential = get_credential(
-        tenant_id=expected_tenant, transport=mock.Mock(send=send), additionally_allowed_tenants=["*"]
-    )
-
-    with mock.patch(GET_REFRESH_TOKEN, lambda _: "**"):
-        token = await credential.get_token("scope")
-    assert token.token == expected_token
-
-    token = await credential.get_token("scope", tenant_id=expected_tenant)
-    assert token.token == expected_token
-
-    token = await credential.get_token("scope", tenant_id="un" + expected_tenant)
-    assert token.token == expected_token * 2
-
-    with mock.patch.dict("os.environ", {EnvironmentVariables.AZURE_IDENTITY_DISABLE_MULTITENANTAUTH: "true"}):
-        token = await credential.get_token("scope", tenant_id="un" + expected_tenant)
-        assert token.token == expected_token
-
-
-def test_deprecation_warning():
-    with pytest.deprecated_call():
-        get_credential()
+from azure.identity._credentials.vscode import VisualStudioCodeCredential as SyncVisualStudioCodeCredential
+from azure.identity.aio._credentials.vscode import VisualStudioCodeCredential
+from azure.identity import CredentialUnavailableError
+
+
+class TestVisualStudioCodeCredentialAsync:
+    """Test cases for the asynchronous VisualStudioCodeCredential"""
+
+    @pytest.mark.asyncio
+    async def test_credential_uses_sync_credential(self):
+        """Test that the async credential uses the sync version."""
+        credential = VisualStudioCodeCredential()
+        assert isinstance(credential._sync_credential, SyncVisualStudioCodeCredential)
+
+    @pytest.mark.asyncio
+    async def test_invalid_auth_record(self):
+        """Test that an error is raised if the auth record is nonexistent."""
+        # Test with a nonexistent file
+        with patch("os.path.expanduser", return_value="nonexistent_file.json"):
+            with pytest.raises(CredentialUnavailableError):
+                await VisualStudioCodeCredential().get_token_info("https://management.azure.com/.default")