通过 username/password 抛出 AdalServiceException 访问 Dynamics CRM:AADSTS65001

Accessing Dynamics CRM via username/password throwing AdalServiceException: AADSTS65001

我按照这里的快速入门:https://docs.microsoft.com/en-us/powerapps/developer/common-data-service/webapi/enhanced-quick-start

效果很好,所以我需要注册我的应用程序,所以我按照以下步骤操作: https://docs.microsoft.com/en-us/powerapps/developer/common-data-service/walkthrough-register-app-azure-active-directory

但是现在我的单元测试给我错误:

Microsoft.IdentityModel.Clients.ActiveDirectory.AdalServiceException: AADSTS65001: The user or administrator has not consented to use the application with ID '[GUID]' named '[AppName]'. Send an interactive authorization request for this user and resource.

我觉得我理解错误,需要管理员同意。我的程序在 bakcgorund 中做了一些魔术,用户没有登录,它使用的是一组用户名和密码,用户不应该同意任何人。有什么方法可以永久设置此同意,或者每次都通过第一个教程中的 Helper class 强制设置?我所有的 Google-fu 都空了...谢谢。

你可以这样使用:

CrmserviceClient 来自 Microsoft.Xrm.Tooling.Connector nuget

 private CrmServiceClient GenerateService()     
    {            
        ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;            
        ServicePointManager.Expect100Continue = true;              
        ServicePointManager.CheckCertificateRevocationList = true;            
        ServicePointManager.DefaultConnectionLimit = 10; 
        var service = new CrmServiceClient(new Uri(organizationUrl), clientId, secret, false, string.Empty);
        if (service.IsReady == false)
        {
            throw new Exception("CrmOrgService isn't ready. " + service.LastCrmError);
        }
        return service;
    }

或者如果你想使用连接字符串,你可以使用这个:

连接字符串:https://docs.microsoft.com/en-us/dynamics365/customerengagement/on-premises/developer/xrm-tooling/use-connection-strings-xrm-tooling-connect

        var connectionString = 
            ConfigurationManager.ConnectionStrings["XY"].ConnectionString;

        var conn = new CrmServiceClient(connectionString);
        IOrganizationService orgService = conn.OrganizationServiceProxy;