我们正在尝试根据此处的指南为我们的应用程序创建本地环境:https://learn.microsoft.com/en-us/dotnet/azure/sdk/authentication/local-development-service-principal?tabs =azure-portal%2Cvisual-studio%2C命令行
为了对服务进行身份验证,我们正在尝试使用 DefaultAzureCredentials() 。
但是独立的 DefaultAzureCredential 给了我们以下异常
(Azure.Identity.CredentialUnavailableException: DefaultAzureCredential failed to retrieve a token from the included credentials. See the troubleshooting guide for more information. https://aka.ms/azsdk/net/identity/defaultazurecredential/troubleshoot\r\n- EnvironmentCredential authentication unavailable. Environment variables are not fully configured. See the troubleshooting guide for more information. https://aka.ms/azsdk/net/identity/environmentcredential/troubleshoot\r\n- WorkloadIdentityCredential authentication unavailable. The workload options are not fully configured. See the troubleshooting guide for more information. https://aka.ms/azsdk/net/identity/workloadidentitycredential/troubleshoot\r\n- ManagedIdentityCredential authentication unavailable. The requested identity has not been assigned to this resource.\r\nStatus: 400 (Bad Request)\r\n\r\nContent:\r\n{\"error\":\"invalid_request\",\"error_description\":\"Identity not found\"}\r\n\r\nHeaders:\r\nx-ms-request-id: 1f8909d1-e628-4d91-896b-50166142786a\r\nContent-Length: 68\r\nContent-Type: application/json; charset=utf-8\r\nDate: Tue, 19 Nov 2024 19:05:50 GMT\r\nServer: IMDS/150.870.65.1475\r\n\r\n- Visual Studio Token provider can't be accessed at C:\\WINDOWS\\system32\\config\\systemprofile\\AppData\\Local\\.IdentityService\\AzureServiceAuth\\tokenprovider.json\r\n- Azure CLI authentication failed due to an unknown error. See the troubleshooting guide for more information. https://aka.ms/azsdk/net/identity/azclicredential/troubleshoot Traceback (most recent call last):\r\n File \"runpy.py\", line 196, in _run_module_as_main\r\n File \"runpy.py\", line 86, in _run_code\r\n File \"D:\\a\\_work\\1\\s\\build_scripts\\windows\\artifacts\\cli\\Lib\\site-packages\\azure/cli/__main__.py\", line 39, in <module>\r\n File \"D:\\a\\_work\\1\\s\\build_scripts\\windows\\artifacts\\cli\\Lib\\site-packages\\azure/cli/core/__init__.py\", line 917, in get_default_cli\r\n File \"D:\\a\\_work\\1\\s\\build_scripts\\windows\\artifacts\\cli\\Lib\\site-packages\\azure/cli/core/azlogging.py\", line 30, in <module>\r\n File \"D:\\a\\_work\\1\\s\\build_scripts\\windows\\artifacts\\cli\\Lib\\site-packages\\azure/cli/core/commands/__init__.py\", line 25, in <module>\r\n File \"D:\\a\\_work\\1\\s\\build_scripts\\windows\\artifacts\\cli\\Lib\\site-packages\\azure/cli/core/extension/__init__.py\", line 18, in <module>\r\n File \"D:\\a\\_work\\1\\s\\build_scripts\\windows\\artifacts\\cli\\Lib\\site-packages\\knack/config.py\", line 40, in __init__\r\n File \"D:\\a\\_work\\1\\s\\build_scripts\\windows\\artifacts\\cli\\Lib\\site-packages\\knack/util.py\", line 115, in ensure_dir\r\n File \"D:\\a\\_work\\1\\s\\build_scripts\\windows\\artifacts\\cli\\Lib\\site-packages\\knack/util.py\", line 112, in ensure_dir\r\n File \"os.py\", line 225, in makedirs\r\nPermissionError: [WinError 5] Access is denied: 'C:\\\\WINDOWS\\\\system32\\\\config\\\\systemprofile\\\\.azure'\r\n- Az.Accounts module >= 2.2.0 is not installed.\r\n- Azure Developer CLI could not be found. ---> System.AggregateException: Multiple exceptions were encountered while attempting to authenticate. ---> Azure.Identity.CredentialUnavailableException: EnvironmentCredential authentication unavailable. Environment variables are not fully configured. See the troubleshooting guide for more information. https://aka.ms/azsdk/net/identity/environmentcredential/troubleshoot\r\n at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n at Azure.Identity.CredentialDiagnosticScope.FailWrapAndThrow(Exception ex, String additionalMessage, Boolean isCredentialUnavailable)\r\n at Azure.Identity.EnvironmentCredential.<GetTokenImplAsync>d__12.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at Azure.Identity.EnvironmentCredential.<GetTokenAsync>d__11.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n at Azure.Identity.DefaultAzureCredential.<GetTokenFromSourcesAsync>d__14.MoveNext()\r\n --- End of inner exception stack trace ---\r\n --- End of inner exception stack trace ---\r\n at Azure.Identity.DefaultAzureCredential.<GetTokenFromSourcesAsync>d__14.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at Azure.Identity.DefaultAzureCredential.<GetTokenImplAsync>d__12.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n at Azure.Identity.CredentialDiagnosticScope.FailWrapAndThrow(Exception ex, String additionalMessage, Boolean isCredentialUnavailable)\r\n at Azure.Identity.DefaultAzureCredential.<GetTokenImplAsync>d__12.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at Azure.Identity.DefaultAzureCredential.<GetTokenAsync>d__11.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Runtime.CompilerServices.ValueTaskAwaiter`1.GetResult()\r\n at Microsoft.Azure.Advisor.Common.Providers.AzureMSALAuthenticationProvider.<GetAccessTokenUtility>d__20.MoveNext() in C:\\One\\EngSys\\EngSys-AzExpertBE\\src\\AzeCommon\\Providers\\AzureMSALAuthenticationProvider.cs:line 312").
尝试将 DefaulAzureCredential 与凭据选项一起使用,这让我有点困难((此处 MFA 身份验证失败)(
Azure.Identity.AuthenticationFailedException: UsernamePasswordCredential authentication failed: AADSTS50076: Due to a configuration change made by your administrator, or because you moved to a new location, you must use multi-factor authentication to access '2746ea77-4702-4b45-80ca-3c97e680e8b7'. Trace ID: a183be80-9b37-4d4b-b861-e7b104930d00 Correlation ID: 498902ed-d264-42b7-8e97-60001298377c Timestamp: 2024-11-18 23:03:41Z The returned error contains a claims challenge. For additional info on how to handle claims related to multifactor authentication, Conditional Access, and incremental consent, see https://aka.ms/msal-conditional-access-claims. If you are using the On-Behalf-Of flow, see https://aka.ms/msal-conditional-access-claims-obo for details.\nSee the troubleshooting guide for more information. https://aka.ms/azsdk/net/identity/usernamepasswordcredential/troubleshoot ---> Microsoft.Identity.Client.MsalClaimsChallengeException: AADSTS50076: Due to a configuration change made by your administrator, or because you moved to a new location, you must use multi-factor authentication to access '2746ea77-4702-4b45-80ca-3c97e680e8b7'. Trace ID: a183be80-9b37-4d4b-b861-e7b104930d00 Correlation ID: 498902ed-d264-42b7-8e97-60001298377c Timestamp: 2024-11-18 23:03:41Z The returned error contains a claims challenge. For additional info on how to handle claims related to multifactor authentication, Conditional Access, and incremental consent, see https://aka.ms/msal-conditional-access-claims. If you are using the On-Behalf-Of flow, see https://aka.ms/msal-conditional-access-claims-obo for details.\r\n at Microsoft.Identity.Client.OAuth2.OAuth2Client.ThrowServerException(HttpResponse response, RequestContext requestContext)\r\n at Microsoft.Identity.Client.OAuth2.OAuth2Client.CreateResponse[T](HttpResponse response, RequestContext requestContext)\r\n at Microsoft.Identity.Client.OAuth2.OAuth2Client.<ExecuteRequestAsync>d__12`1.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at Microsoft.Identity.Client.OAuth2.TokenClient.<SendHttpAndClearTelemetryAsync>d__11.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n at Microsoft.Identity.Client.OAuth2.TokenClient.<SendHttpAndClearTelemetryAsync>d__11.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at Microsoft.Identity.Client.OAuth2.TokenClient.<SendTokenRequestAsync>d__5.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.ExceptionServices.ExceptionDispatch Info.Throw()\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at Microsoft.Identity.Client.Internal.Requests.RequestBase.<SendTokenRequestAsync>d__26.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at Microsoft.Identity.Client.Internal.Requests.UsernamePasswordRequest.<GetTokenResponseAsync>d__6.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at Microsoft.Identity.Client.Internal.Requests.UsernamePasswordRequest.<ExecuteAsync>d__5.MoveNext()\r\n--- End of stack trace from previous location where exception was
)
尝试使用正常的 VisualStudioCredential () 最初获取 tokenprovider.json 文件的文件未找到异常,但似乎 SF 应用程序正在 windows32 而不是 %userlocal% 中查找来获取文件。因此,复制文件并重新运行,导致我访问该文件的权限被拒绝(无法找到引导 SF 应用程序查找我的 %userlocal% 路径的方法)(
Azure.Identity.AuthenticationFailedException: VisualStudioCredential authentication failed: Access to the path 'C:\\WINDOWS\\system32\\config\\systemprofile\\AppData\\Local\\.IdentityService\\AzureServiceAuth\\tokenprovider.json' is denied. ---> System.UnauthorizedAccessException: Access to the path 'C:\\WINDOWS\\system32\\config\\systemprofile\\AppData\\Local\\.IdentityService\\AzureServiceAuth\\tokenprovider.json' is denied.\r\n at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)\r\n at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)\r\n at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)\r\n at System.IO.StreamReader..ctor(String path, Encoding encoding, Boolean detectEncodingFromByteOrderMarks, Int32 bufferSize, Boolean checkHost)\r\n at System.IO.File.InternalReadAllText(String path, Encoding encoding, Boolean checkHost)\r\n )
( PS:对于步骤 1 和 2 :我尝试设置 AZURE_USERNAME、AZURE_PASSWORD、AZURE_TENANT_ID 的 Env_variables)
还有以 Azure Auth 集开头的 VS。
关于如何正确使用 DefaultAzureAuthentication() 有什么建议,否则我们可能会出错?
我已按照以下步骤在本地 Azure Service Fabric 应用程序中使用 DefaultAzureCredential。
Key Vault=>Access Policies(if you have selected vault access instead of RBAC)=>Create
并向服务主体(EntraID 应用程序)授予 Key 和 Secret 权限。将
Azure_Client_ID, Azure_Client_Secret, Azure_Tenant_ID
设置为本地环境变量。
或者您可以使用以下代码进行设置。
代码片段:
protected override async Task RunAsync(CancellationToken cancellationToken)
{
string tenantId = "<Azure_Tenant_ID>";
string clientId = "<AZURE_CLIENT_ID>";
string clientSecret = "<AZURE_CLIENT_SECRET>";
Environment.SetEnvironmentVariable("AZURE_TENANT_ID", tenantId);
Environment.SetEnvironmentVariable("AZURE_CLIENT_ID", clientId);
Environment.SetEnvironmentVariable("AZURE_CLIENT_SECRET", clientSecret);
var defaultAzureCredentialOptions = new DefaultAzureCredentialOptions
{
ExcludeEnvironmentCredential = false,
ExcludeManagedIdentityCredential = true,
ExcludeSharedTokenCacheCredential = true,
ExcludeVisualStudioCredential = false,
ExcludeVisualStudioCodeCredential = false,
ExcludeAzureCliCredential = true,
ExcludeInteractiveBrowserCredential = true
};
var credential = new DefaultAzureCredential(defaultAzureCredentialOptions);
var kvUri = "https://<KeyVault_name>.vault.azure.net/";
var client = new SecretClient(new Uri(kvUri),credential);
var secretName = "<Secret_Name>";
var secret = await client.GetSecretAsync(secretName);
string keyVaultValue = secret.Value.Value;
long iterations = 0;
while (true)
{
cancellationToken.ThrowIfCancellationRequested();
ServiceEventSource.Current.ServiceMessage(this.Context, "Working-{0}", ++iterations);
await Task.Delay(TimeSpan.FromSeconds(1), cancellationToken);
}
}
我可以调试代码并通过本地使用
DefaultAzureCredential
获取秘密。
调试输出:
Step into: Stepping over property 'Azure.ValueResponse.get_Value'. To step into properties or operators, go to Tools->Options->Debugging and uncheck 'Step over properties and operators (Managed only)'.
Step into: Stepping over property 'Azure.Security.KeyVault.Secrets.KeyVaultSecret.get_Value'. To step into properties or operators, go to Tools->Options->Debugging and uncheck 'Step over properties and operators (Managed only)'.