2
我使用适用于Web API的Visual Studio 2015 Update 3创建了一个基本项目(没有任何自定义,裸露骨骼),并按照here指令将其部署到Azure(免费帐户)。 然后我用下面的代码创建了一个控制台客户端。从Azure Web API获取未经授权
public static async Task<bool> ReadValues()
{
try
{
// Authenticate the user and get a token from Azure AD
//AuthenticationResult authResult = await AuthContext.AcquireTokenSilentAsync(Resource, ClientId);
AuthenticationResult authResult = AuthContext.AcquireToken(Resource, ClientId, RedirectUri);
// Create an HTTP client and add the token to the Authorization header
HttpClient httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(
//"Bearer"
authResult.AccessTokenType
, authResult.AccessToken);
// Call the Web API to get the values
var requestUri = new Uri(WebApiUri, "api/values");
Console.WriteLine("Reading values from '{0}'.", requestUri);
HttpResponseMessage httpResponse = await httpClient.GetAsync(requestUri);
Console.WriteLine("HTTP Status Code: '{0}'", httpResponse.StatusCode.ToString());
//Console.WriteLine("HTTP Header: '{0}'", httpClient.DefaultRequestHeaders.Authorization.ToString());
if (httpResponse.IsSuccessStatusCode)
{
//
// Code to do something with the data returned goes here.
//
var s = await httpResponse.Content.ReadAsStringAsync();
Console.WriteLine(s);
}
else
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(httpResponse.ReasonPhrase);
}
return (httpResponse.IsSuccessStatusCode);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return false;
}
它正常工作,当我在本地调试从Visual Studio运行Web API,但是当我把它部署到Azure的,它返回未经授权。 一些常见的事情,我可能会问:
- 我收到有效承载令牌
- 我在Azure的AD的机器人HTHE WEB API和客户端
- 所创建的应用程序注册客户端和Web API使用了正确的重定向,资源URI
- 我使用的登录账号相同,用于创建Azure的帐户之一,它具有域/ AD/API中的全部特权
在API方面,这是整个startup.auth.cs
的using System.Configuration;
using System.IdentityModel.Tokens;
using Microsoft.Owin;
using Microsoft.Owin.Security.ActiveDirectory;
using Owin;
using WebApi;
[assembly: OwinStartup("default", typeof(Startup))]
namespace WebApi
{
public partial class Startup
{
// For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
public void ConfigureAuth(IAppBuilder app)
{
app.UseWindowsAzureActiveDirectoryBearerAuthentication(
new WindowsAzureActiveDirectoryBearerAuthenticationOptions
{
Tenant = ConfigurationManager.AppSettings["ida:Tenant"],
TokenValidationParameters = new TokenValidationParameters {
ValidAudience = ConfigurationManager.AppSettings["ida:Audience"]
},
});
}
}
}
我还需要检查?
其他参考资料
您可以在您注册身份验证中间件的位置添加代码(我假设您使用的是OWIN)。 – juunas
那么,auth配置看起来与我所做的API非常相似。如果'aud'声明值与'ida:Audience'和'ida:Tenant'的配置文件匹配,那么它可能是OWIN中间件根本没有运行吗? – juunas
嗨Juaunas,用其他代码更新了这个问题。我跟踪了我共享的两个链接,所有代码都来自VS代码模板和这两个链接。 – Diceyus