使用MS Dynamics CRM 2016的REST Web API在线进行身份验证

Chr*_*ris 5 python rest azure-active-directory adal dynamics-crm-2016

我正在尝试访问新的REST API,以构建服务器到服务器接口,以将CRM与其他应用程序(如网店等)集成.

我尝试了从Azure AD获取访问令牌的两种方法:

客户凭证

import adal

token_response = adal.acquire_token_with_client_credentials(
    'https://login.microsoftonline.com/abcdefgh-1234-5678-a1b1-morerandomstuff', 
    client_id,
    secret
)
Run Code Online (Sandbox Code Playgroud)

和用户/密码

import adal

token_response = adal.acquire_token_with_username_password(
    'https://login.microsoftonline.com/abcdefgh-1234-5678-a1b1-morerandomstuff',
    'interface@crm.my_domain.com',
    'my_password'
)
Run Code Online (Sandbox Code Playgroud)

在这两种情况下,token_response都会获得一个token-object,包含accessToken,refreshToken,expiresIn等.所以我认为到目前为止还没有错误.

然后我尝试向Web API发出一个简单的请求:

headers = {'Authorization': '%s %s' % (token_response.get('tokenType'),
                                       token_response.get('accessToken'))}

r = requests.get('https://domain.api.crm4.dynamics.com/api/data/v8.0/Product',
                 headers=headers)
Run Code Online (Sandbox Code Playgroud)

这总是返回HTTP 401 - 未授权:访问被拒绝.

('WWW-Authenticate', 'Bearer error=invalid_token,
error_description=Error during token validation!,
authorization_uri=https://login.windows.net/eabcdefgh-1234-5678-a1b1-morerandomstuff/oauth2/authorize,
resource_id=https://domain.api.crm4.dynamics.com/')
Run Code Online (Sandbox Code Playgroud)

尝试发出请求的用户具有Office-365-Administrator权限,并且在CRM中具有所有管理员角色和管理员角色.根据我的口味,这甚至有点多,但我在某处读到,用户必须拥有office-365管理员权限.在Azure AD中,配置了一个应用程序,该应用程序具有对CRM的"委派权限"("作为组织用户访问CRM Online").

我在这里错过了什么?或者我的REST-get-request错了?新API的Microsoft文档几乎不存在 - 每当您单击某个链接时,您将获得旧API(组织API等)的文档

Hen*_*k H 4

acquire_token_with_username_password有一个可选参数用于指定您要访问的资源:

资源(str,可选):您正在访问的资源。默认为“ https://management.core.windows.net/ ”。

因此,您应该能够通过将资源添加为参数来指定您想要访问 CRM acquire_token_with_username_password

token_response = adal.acquire_token_with_username_password(
    'https://login.microsoftonline.com/abcdefgh-1234-5678-a1b1-morerandomstuff',
    'interface@crm.my_domain.com',
    'my_password',
    resource='https://domain.crm4.dynamics.com'
)
Run Code Online (Sandbox Code Playgroud)

这将为您提供用于访问 CRM 的正确令牌。

获得正确的令牌后,您还需要稍微修改您的 Web API 调用(从Productproducts):

r = requests.get('https://domain.api.crm4.dynamics.com/api/data/v8.0/products',
                 headers=headers)
Run Code Online (Sandbox Code Playgroud)