我有一个“服务器应用程序访问web API”的场景。
该网站使用OIDC并进行身份验证,没有问题。
然而,我有一个在没有用户上下文的情况下访问一些web API的用例,为此,我使用了client_credentials。
服务器应用程序具有客户端ID和密钥。
因此,假设web API URL为:
https://my-pc/WebService/api/my-api/
web API具有RP标识符:
https://my-pc/WebService/api/my-api/
访问控制策略为:
允许所有人
我有一个声明规则:
c:[]索赔问题( => = c);
客户端权限设置为:
“所有客户端”,范围为openid和user_impersonation。
代码是:
AuthenticationContext ac = new AuthenticationContext("https://my-adfs/adfs/", false);
// ClientCredential contains client_id and secret key
AuthenticationResult result = await ac.AcquireTokenAsync("https://my-pc/WebService/api/my-api/", clientCredential);
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "https://my-pc/WebService/api/my-api/");
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);
HttpContent content = new FormUrlEncodedContent(new[] { new KeyValuePair<string, string>("foo", "blah"), new KeyValuePair<string, string>("foo1", "blah1") });
request.Content = content;
HttpResponseMessage response = await client.SendAsync(request);ADFS返回访问令牌没有问题,但当我调用web api时,我总是得到一个401 - Unauthenticated。
有什么想法吗?
发布于 2017-03-16 03:05:29
最终解决了这个问题,并且wrote it up。
这两段代码:
using Microsoft.IdentityModel.Clients.ActiveDirectory;
ClientCredential clientCredential = new ClientCredential(clientId, secretKey);
AuthenticationContext ac = new AuthenticationContext("https://my-adfs/adfs/", false);
AuthenticationResult result = await ac.AcquireTokenAsync("https://my-pc/WebService",
clientCredential);
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post,
"https://my-pc/WebService/api/my-api/");
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);
HttpContent content = new FormUrlEncodedContent(new[] { new KeyValuePair<string,
string>("foo", "blah"), new KeyValuePair<string, string>("foo1", "blah1") });
request.Content = content;
HttpResponseMessage response = await client.SendAsync(request);
if (response.IsSuccessStatusCode)
// etc在Startup.Auth.cs中
app.UseActiveDirectoryFederationServicesBearerAuthentication(
new ActiveDirectoryFederationServicesBearerAuthenticationOptions
{
TokenValidationParameters = new TokenValidationParameters()
{
SaveSigninToken = true,
ValidAudience = "https://my-pc/WebService"
},
MetadataEndpoint = "https://my-adfs/FederationMetadata/2007-06/FederationMetadata.xml"
});花了我好长时间!
发布于 2017-03-15 23:29:19
由于您没有在访问令牌中获取用户主体,因此您没有将用户会话附加到主体。当Web API在cookie(或Authorization header,如果您正在发送访问令牌)中查找主体时,它找不到主体,您仍然是匿名用户。
https://stackoverflow.com/questions/42795633
复制相似问题