我有一个内置的Dynamics (2016),它使用ADFS (3.0)配置。当用户想要登录时,他们被重定向到ADFS登录页面,用户输入他们的Windows凭据。
从.net核心应用程序中,我需要使用HttpClient向CRM提出请求。当我试图像往常一样发送Windows Auth CRM的凭据时,它不起作用。我得到了401的未经授权。就像下面。
HttpClient client = new HttpClient(new HttpClientHandler() { Credentials = new NetworkCredential("myuser", "mypassword", "mydomain") });
var result = client.GetAsync("https://mycrmaddress/api/data/v8.0/accounts");我还尝试使用adal检索令牌,并将其作为承载令牌附加到请求中,但无法使用Adal获取令牌。当我尝试时,我会收到以下信息:
The authorization server does not support the requested 'grant_type'. The authorization server only supports 'authorization_code'ADFS3.0不支持此流。
我不能升级到ADFS 4.0,所以我想知道我对CRM进行身份验证调用的选项是什么(因为这个应用程序是一个服务,所以没有提示登录窗口)。
是否可以在ADFS上进行任何配置,以便我的第一个示例能够工作?或者,即使它是ADFS3.0,也可以用Adal完成吗?或者任何其他的解决方案。
发布于 2018-11-01 13:54:23
我找到了我问题的答案。有点讨厌,但我自己测试过,而且很管用。作为一种临时解决方案,这将发挥作用。
详细信息可在这里获得:https://community.dynamics.com/crm/f/117/t/255985
ADFS3.0支持授权代码流,这是我们将在本例中使用的。
- {authProvider} - ADFS Uri - something like [https://adfs.mycompany.com/adfs/oauth2/](https://adfs.mycompany.com/adfs/oauth2/)
- {ClientId} - The Guid used to by your infrastructure team to add your application to ADFS
- {RedirectUri} - The IFD Uri for dynamics - should match the redirect Url used to by your infrastructure team to add your application to ADFS
- username - The User set up on ADFS and in Dynamics
- password - The password for the above user
然后使用HttpClient对这些信息进行以下调用。
var uri = $"{authProvider}authorize?response_type=code&client_id={clientId}&resource={redirectUri}&redirect_uri={redirectUri}";
var content = new FormUrlEncodedContent(new[] {
new KeyValuePair<string,string>("username",username),
new KeyValuePair<string,string>("password",password),
});
var responseResult = _httpManager.PostAsync(uri, content).Result;响应内容将是一个html页面(请记住,此流程通常会提示用户登录页面)。在此页面中,将有一个包含授权代码的表单。使用像HtmlAgilityPack这样的库检索令牌。这是解决方案的一部分。
为此,我们需要打以下电话
var uri = $"{authProvider}token";
var content = new FormUrlEncodedContent(new[] {
new KeyValuePair<string,string>("grant_type","authorization_code"),
new KeyValuePair<string,string>("client_id",clientId),
new KeyValuePair<string,string>("redirect_uri",redirectUri),
new KeyValuePair<string,string>("code",code)
});
var response = await _httpManager.PostAsync(uri, content);响应内容将是包含访问令牌的json字符串。
您需要将令牌作为承载令牌附加到报头中的HttpClient。
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer",token);
httpClient.DefaultRequestHeaders.Add("OData-MaxVersion", "4.0");
httpClient.DefaultRequestHeaders.Add("OData-Version", "4.0");从现在开始,您可以调用CRM,您将获得授权。不过,正常情况下,访问令牌是短暂的。您要么需要增加他们的生命周期,要么每次它过期时都请求一个新的令牌。
https://stackoverflow.com/questions/53072272
复制相似问题