401 Unauthorized:WebApi UseOAuthBearerAuthentication

时间:2017-04-10 13:06:40

标签: asp.net-web-api2 azure-active-directory msal

我开始使用身份验证。所以我创建了一个WebApi并试图使用bearer token来保护它。我在启动类的配置方法中添加了以下代码:

    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下载了示例代码 并指出我的客户这项服务。它工作正常。我比较了代码和它的相同。我想知道可能是什么问题。非常感谢任何帮助。

0 个答案:

没有答案