我从身份验证开始。所以我创建了一个 WebApi 并尝试使用不记名令牌来保护它。我在启动类的配置方法中添加了如下代码:
string clientId = "76dd292c-8522-40d8-b0df-09e6c3300498";
public void Configuration(IAppBuilder app)
{
var tvps = new TokenValidationParameters
{
ValidAudience = clientId,
ValidateIssuer = false,
};
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions
{
AccessTokenFormat = new Microsoft.Owin.Security.Jwt.JwtFormat(tvps, new OpenIdConnectCachingSecurityTokenProvider("https://login.microsoftonline.com/common/v2.0/.well-known/openid-configuration")),
});
}
在客户端,我有以下代码:
var clientId = "76dd292c-8522-40d8-b0df-09e6c3300498";
PublicClientApplication client = new PublicClientApplication(clientId) {
UserTokenCache=new FileCache()
};
var result = client.AcquireTokenAsync(new string[] { clientId }).Result;
HttpClient httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", result.Token);
var res=httpClient.GetAsync("https://localhost:44321/Api/Values").Result;
我得到 401 未经授权。我从https://github.com/AzureADQuickStarts/WebAPI-Bearer-DotNet/archive/complete.zip下载了示例代码, 并将我的客户指向了该服务。它工作正常。我比较了代码和它的相同。我试图了解可能是什么问题。将不胜感激任何帮助。