[英]How to authenticate correctly in SharePoint Online from Azure Function with API Graph?
[英]Azure Graph API in .Net on desktop will not authenticate
每当我尝试使用Microsoft图形API与Azure AD进行通信时,都不会打开浏览器窗口。
如果我下载了使用UWP的示例,则它可以正常工作,但是当我尝试在现有应用程序(不是UWP)中实现相同代码时,它将无法工作。 我也尝试过使用.net 4.6.1制作一个简单的控制台应用程序,并且不会弹出任何浏览器窗口。 如果我在DelegateAuthenticationProvider中放置一个断点,它将永远不会被击中。 如果我直接调用GetTokenForUserAsync,则执行将无限期地与IdentityClientApp.AcquireTokenAsync保持一致。
这仅是为了在UWP项目上工作还是我做错了什么?
using System;
using System.Linq;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using Microsoft.Azure.ActiveDirectory.GraphClient;
using Microsoft.Graph;
using Microsoft.Identity.Client;
namespace ConsoleApp1
{
public class AuthenticationHelper
{
// The Client ID is used by the application to uniquely identify itself to the v2.0 authentication endpoint.
static string clientId = System.Configuration.ConfigurationManager.AppSettings["ida:ClientID"].ToString();
public static string[] Scopes = { "User.Read", "Mail.Send", "Files.ReadWrite" };
public static PublicClientApplication IdentityClientApp = new PublicClientApplication(clientId);
public static string TokenForUser = null;
public static DateTimeOffset Expiration;
private static GraphServiceClient graphClient = null;
// Get an access token for the given context and resourceId. An attempt is first made to
// acquire the token silently. If that fails, then we try to acquire the token by prompting the user.
public static GraphServiceClient GetAuthenticatedClient()
{
if (graphClient == null)
{
// Create Microsoft Graph client.
try
{
graphClient = new GraphServiceClient(
"https://graph.microsoft.com/v1.0",
new DelegateAuthenticationProvider(
async (requestMessage) =>
{
var token = await GetTokenForUserAsync();
requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", token);
// This header has been added to identify our sample in the Microsoft Graph service. If extracting this code for your project please remove.
requestMessage.Headers.Add("SampleID", "uwp-csharp-connect-sample");
}));
return graphClient;
}
catch (Exception ex)
{
}
}
return graphClient;
}
/// <summary>
/// Get Token for User.
/// </summary>
/// <returns>Token for user.</returns>
public static async Task<string> GetTokenForUserAsync()
{
Microsoft.Identity.Client.AuthenticationResult authResult;
try
{
authResult = await IdentityClientApp.AcquireTokenSilentAsync(Scopes, IdentityClientApp.Users.First());
TokenForUser = authResult.AccessToken;
}
catch (Exception)
{
if (TokenForUser == null || Expiration <= DateTimeOffset.UtcNow.AddMinutes(5))
{
authResult = await IdentityClientApp.AcquireTokenAsync(Scopes);
TokenForUser = authResult.AccessToken;
Expiration = authResult.ExpiresOn;
}
}
return TokenForUser;
}
/// <summary>
/// Signs the user out of the service.
/// </summary>
public static void SignOut()
{
foreach (var user in IdentityClientApp.Users)
{
IdentityClientApp.Remove(user);
}
graphClient = null;
TokenForUser = null;
}
}
}
为了理解使用Graph API的身份验证,我使用此示例(不是UWP而是WPF)
https://github.com/Azure-Samples/active-directory-dotnet-desktop-msgraph-v2/blob/master/README.md
这非常简单,它可以帮助我了解获取身份验证令牌的两种不同方式的行为: AcquireTokenSylentAsync() (无需与用户交互)和AcquireTokenAsync() (为用户登录打开浏览器)
根据您的描述,我在.NET 4.6.1上创建了我的控制台应用程序目标,并使用MSAL进行身份验证,并利用Microsoft Graph .NET客户端库与Microsoft Graph API进行通信。
我重用了GetTokenForUserAsync
方法,并按如下所示执行了我的代码段:
static void Main(string[] args)
{
MainAsync(args).GetAwaiter().GetResult();
}
static async Task MainAsync(string[] args)
{
var graphClient = new GraphServiceClient(
"https://graph.microsoft.com/v1.0",
new DelegateAuthenticationProvider(
async (requestMessage) =>
{
var token = await GetTokenForUserAsync();
requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", token);
}));
var user = await graphClient.Me.Request().GetAsync();
Console.WriteLine(JsonConvert.SerializeObject(user));
}
要么
static void Main(string[] args)
{
var graphClient = new GraphServiceClient(
"https://graph.microsoft.com/v1.0",
new DelegateAuthenticationProvider(
async (requestMessage) =>
{
var token = await GetTokenForUserAsync();
requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", token);
}));
var user = graphClient.Me.Request().GetAsync().Result;
Console.WriteLine(JsonConvert.SerializeObject(user));
Console.WriteLine("press any key to exit...");
Console.ReadLine();
}
测试:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.