是否存在使用AAD访问充当OData服务器的Azure App Service的外部OData客户端的示例?提供的身份是客户端应用程序本身在AAD中注册为本地应用程序的身份,而不是用户的身份,因此该应用程序不需要用户身份验证界面。
答案 0 :(得分:0)
实际上,为Odata服务设置AD与常规Web API相同。因此,您可以参考以下示例:https://github.com/azure-samples/active-directory-dotnet-daemon
次要区别是在客户端。由于客户端代码是由“ Odata客户端代码生成器”生成的,因此未使用HTTP客户端类。您需要利用DataServiceContext.SendingRequest Event添加授权标头。
请参阅下面的代码:
private static string aadInstance = ConfigurationManager.AppSettings["ida:AADInstance"];
private static string tenant = ConfigurationManager.AppSettings["ida:Tenant"];
private static string clientId = ConfigurationManager.AppSettings["ida:ClientId"];
private static string appKey = ConfigurationManager.AppSettings["ida:AppKey"];
private static string OdataServiceId = ConfigurationManager.AppSettings["OdataTestId"];
static string authority = String.Format(CultureInfo.InvariantCulture, aadInstance, tenant);
private static AuthenticationContext authContext = null;
private static ClientCredential clientCredential = null;
// Get an entire entity set.
static void ListAllProducts(Default.Container container)
{
foreach (var p in container.Products)
{
Console.WriteLine("{0} {1} {2}", p.Name, p.Price, p.Category);
}
}
static void AddProduct(Default.Container container, OdataTest.Models.Product product)
{
container.SendingRequest2 += Container_SendingRequest2;
container.AddToProducts(product);
var serviceResponse = container.SaveChanges();
foreach (var operationResponse in serviceResponse)
{
Console.WriteLine("Response: {0}", operationResponse.StatusCode);
}
}
private static void Container_SendingRequest2(object sender, Microsoft.OData.Client.SendingRequest2EventArgs e)
{
AuthenticationResult result= authContext.AcquireTokenAsync(OdataServiceId, clientCredential).Result;
e.RequestMessage.SetHeader("Authorization", "Bearer " + result.AccessToken);
}
static void Main(string[] args)
{
authContext = new AuthenticationContext(authority);
clientCredential = new ClientCredential(clientId, appKey);
// TODO: Replace with your local URI.
string serviceUri = "http://localhost:59837/";
var container = new Default.Container(new Uri(serviceUri));
var product = new OdataTest.Models.Product()
{
Name = "Yo-yo",
Category = "Toys",
Price = 4.95M
};
AddProduct(container, product);
ListAllProducts(container);
Console.ReadKey();
}
}