#xamarin #xamarin.forms #xamarin.ios #microsoft-graph-api #azure-sdk-.net
Вопрос:
Я пытаюсь пройти аутентификацию через api graph для AD в Azure.Имя пользователя идентификатораpasswordcredential, но всякий раз, когда я инициализирую ctor учетных данных, он выдает следующее исключение:
The method or operation is not implemented. at System.Diagnostics.Tracing.EventSource.GetSources ()
Трассировка стека:
System.TypeInitializationException: The type initializer for 'Azure.Core.Pipeline.LoggingPolicy' threw an exception. ---> System.TypeInitializationException: The type initializer for 'Azure.Core.Diagnostics.AzureCoreEventSource' threw an exception. ---> System.NotImplementedException: The method or operation is not implemented.
at System.Diagnostics.Tracing.EventSource.GetSources () [0x00000] in /Library/Frameworks/Xamarin.iOS.framework/Versions/Current/src/Xamarin.iOS/mcs/class/corlib/System.Diagnostics.Tracing/EventSource.cs:318
at Azure.Core.Diagnostics.AzureEventSource.DeduplicateName (System.String eventSourceName) [0x00010] in <0aa90fe0646d47bc95bff520717dbf16>:0
at Azure.Core.Diagnostics.AzureEventSource..ctor (System.String eventSourceName) [0x00000] in <0aa90fe0646d47bc95bff520717dbf16>:0
at Azure.Core.Diagnostics.AzureCoreEventSource..ctor () [0x00000] in <0aa90fe0646d47bc95bff520717dbf16>:0
at Azure.Core.Diagnostics.AzureCoreEventSource..cctor () [0x00000] in <0aa90fe0646d47bc95bff520717dbf16>:0
--- End of inner exception stack trace ---
at Azure.Core.Pipeline.LoggingPolicy..cctor () [0x00000] in <0aa90fe0646d47bc95bff520717dbf16>:0
--- End of inner exception stack trace ---
at Azure.Core.Pipeline.HttpPipelineBuilder.Build (Azure.Core.ClientOptions options, Azure.Core.Pipeline.HttpPipelinePolicy[] perCallPolicies, Azure.Core.Pipeline.HttpPipelinePolicy[] perRetryPolicies, Azure.Core.ResponseClassifier responseClassifier) [0x00164] in <0aa90fe0646d47bc95bff520717dbf16>:0
at Azure.Identity.CredentialPipeline..ctor (Azure.Identity.TokenCredentialOptions options) [0x00023] in <47110d8b120248e4b903ba2cc44741ea>:0
at Azure.Identity.CredentialPipeline.GetInstance (Azure.Identity.TokenCredentialOptions options) [0x00003] in <47110d8b120248e4b903ba2cc44741ea>:0
at Azure.Identity.UsernamePasswordCredential..ctor (System.String username, System.String password, System.String tenantId, System.String clientId, Azure.Identity.TokenCredentialOptions options, Azure.Identity.CredentialPipeline pipeline, Azure.Identity.MsalPublicClient client) [0x00069] in <47110d8b120248e4b903ba2cc44741ea>:0
at Azure.Identity.UsernamePasswordCredential..ctor (System.String username, System.String password, System.String tenantId, System.String clientId, Azure.Identity.TokenCredentialOptions options) [0x00000] in <47110d8b120248e4b903ba2cc44741ea>:0
at MyProject.GraphService.Init (System.String username, System.String password, System.String tenantId, System.String clientId, System.String eventKeyword) [0x00014] in .../MyProject/GraphService.cs:31
at MyProject.Features.Auth.AuthViewModel.InnerGetUser () [0x00077] in .../MyProject/Features/Auth/AuthViewModel.cs:57
Мой код-ведьма graphService — это стандартная библиотека версии 2.1, и она используется AuthViewModel в проекте Xamarin.forms.
public class AuthViewModel: BaseViewModel
{
...
private async Task InnerGetUser()
{
try
{
this.IsBusy = true;
if (string.IsNullOrEmpty(this.Email) ||
string.IsNullOrEmpty(this.Password))
throw new ValidationException("Email e password devono essere compilati");
this._graphService.Init(this.Email, this.Password,
this._settingsService.GetStringSetting(Services.Settings.TenantId),
this._settingsService.GetStringSetting(Services.Settings.ClientId),
this._settingsService.GetStringSetting(Services.Settings.EventKeyword));
var user = await this._graphService.GetUser();
this._userService.CurrentUser = new UserDto()
{
Name = user.DisplayName
};
this._userService.InvokeOnLoginDone();
}
catch (Exception e)
{
await base.ShowError(e);
}
finally
{
this.IsBusy = false;
}
}
...
}
public class GraphService: IGraphService
{
...
public void Init(string username, string password, string tenantId, string clientId, string eventKeyword)
{
this._eventKeyword = eventKeyword;
Console.WriteLine("Creo credentials provider");
var userNamePasswordCredential = new UsernamePasswordCredential(
username, password, tenantId, clientId, new TokenCredentialOptions
{
AuthorityHost = AzureAuthorityHosts.AzurePublicCloud
});
Console.WriteLine("Creo graph service client");
this._graphClient = new GraphServiceClient(userNamePasswordCredential);
}
...
}
Любопытно, что он отлично работает в консольном приложении в net5.
Самородки:
- Xamarin.формы 5.0.0.2125,
- Лазурь.Личность 1.4.1,
- Майкрософт.График 4.6.0
Env:
- mac.os 11.6
- visual studio для mac 8.10.10 (сборка 8)
sdks:
- .NET 5.0.401,
- Моно 6.12.0.140,
- Xamarin.iOS 15.0.0.6.
Есть какие-нибудь идеи?
Спасибо.
Комментарии:
1. Каков ваш…/MyProject/Функции/Auth/AuthViewModel.cs:57 код?
2. он вызывает фрагмент кода, который я вставил выше, witch пытается создать экземпляр UsernamePasswordCredential и терпит неудачу. В проекте Xamarin.forms вызывающим является authviewmodel.
3. Я обновил пример кода
4. проверять issueexplorer.com/issue/Azure/azure-sdk-for-net/24055
5. Как я вижу из вопросов 24055, это похоже на ошибку Azure.Core. Новая версия будет выпущена в ближайшее время в октябре.
Ответ №1:
У меня была аналогичная проблема с Azure.Хранение.Большие двоичные объекты, получающие исключение
System.TypeInitializationException: The type initializer for 'Azure.Core.Pipeline.LoggingPolicy' threw an exception. ---> System.TypeInitializationException: The type initializer for 'Azure.Core.Diagnostics.AzureCoreEventSource' threw an exception. ---> System.NotImplementedException: The method or operation is not implemented.
Я решил эту проблему, установив Azure.Core. Я надеюсь, что это может быть вам полезно.
Комментарии:
1. Привет, Йохан, добавляю Лазурный. Ядро фактически предотвращает выдачу учетных данных UsernamePasswordCredential, но теперь следующий шаг (путем вызова var user = ждите этого._graphClient.Me.Request() .GetAsync();) вызывает то же исключение для другого компонента: инициализатора типа для ‘Azure. Идентичность. Источник событий Azure Identity» выдал исключение. —> Система. Исключение NotImplementedException: Метод или операция не реализованы. в Системе. Диагностика. Трассировка. Источник событий. GetSources ()
2. @Gaburiere вы установили оба пакета на все платформы? Общий доступ, iOS и Android?
3. да, я пытался, но безрезультатно. Только путем обновления Microsoft. График до версии 4.7.0 и Azure. Идентификация до версии 1.5.0 сделала свое дело! Теперь возникла проблема с доступом к связке ключей и собственной связью, добавив пользовательское право к тому, которое содержит доступ к самой связке ключей, но я думаю, что это другая история :). Он работает на Android.
Ответ №2:
Я публикую это как Не ответ, так как у меня та же проблема, и я безуспешно пытался это сделать. Я попытался установить все параметры диагностики в значение false. Это действительно возымело эффект, потому что оно перестало выдавать исключение, когда я создал BLOB-клиент, но вместо этого теперь оно выдает систему.Исключение NotImplementedException при повторении результатов перечисления больших двоичных объектов.
ClientSecretCredentialOptions options = new ClientSecretCredentialOptions();
options.Diagnostics.IsDistributedTracingEnabled = false;
options.Diagnostics.IsLoggingContentEnabled = false;
options.Diagnostics.IsLoggingEnabled = false;
options.Diagnostics.IsTelemetryEnabled = false;
Комментарии:
1. Привет, я тоже пытался отключить диагностику, как один из последних постов issueexplorer.com/issue/Azure/azure-sdk-for-net/24055 говорит, но безуспешно.
Ответ №3:
Обновление Microsoft.График до версии 4.7.0 и Azure.Обновление до версии 1.5.0 устранило проблему.