C# 使用带有WPF应用程序的graph连接到Azure AD api

C# 使用带有WPF应用程序的graph连接到Azure AD api,c#,azure,C#,Azure,我正在尝试使用graph连接到wpf应用程序中的azure广告。身份验证似乎正常,我得到了一个返回的访问令牌。我也可以使用这个令牌来获取关于我自己的基本信息。但是,当我试图从目录中请求某些内容时,会出现以下错误: 代码“:”JWT10315签名验证失败。试过的钥匙: 然后是一大堆其他的东西。一切似乎都很好。该应用程序已在Azure中注册。我设置了正确的访问权限。我不懂。有人能帮我吗?我的代码如下 //using Microsoft.IdentityModel.Clients.ActiveDire

我正在尝试使用graph连接到wpf应用程序中的azure广告。身份验证似乎正常,我得到了一个返回的访问令牌。我也可以使用这个令牌来获取关于我自己的基本信息。但是,当我试图从目录中请求某些内容时,会出现以下错误:

代码“:”JWT10315签名验证失败。试过的钥匙:

然后是一大堆其他的东西。一切似乎都很好。该应用程序已在Azure中注册。我设置了正确的访问权限。我不懂。有人能帮我吗?我的代码如下

//using Microsoft.IdentityModel.Clients.ActiveDirectory;
using Microsoft.Identity.Client;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace O365_Graph_Connector
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
    //graph endpoint
    //$upn="userPrincipalName eq '" + $user.Id +"'"
    string url = "https://graph.windows.net/mydomain.com/activities/signinEvents?api-version=beta&`$filter=userPrincipalName eq 'upn@withheld.com'";
    //string url = "https://graph.microsoft.com/v1.0/me/";
    //Scopes
    string[] _scopes = new string[] { "Directory.Read.All" };

    public MainWindow()
    {
        InitializeComponent();
        txtOutput.Text = "bla";


    }

    private async void btnConnect_Click(object sender, RoutedEventArgs e)
    {

        AuthenticationResult authResult = null;

        try
        {
            if (authResult == null)
            {
                authResult = await App.PublicClientApp.AcquireTokenSilentAsync(_scopes, App.PublicClientApp.Users.FirstOrDefault());
                Console.WriteLine("authenticated");
            }
        }
        catch (MsalUiRequiredException ex)
        {
            // A MsalUiRequiredException happened on AcquireTokenSilentAsync. This indicates you need to call AcquireTokenAsync to acquire a token
            System.Diagnostics.Debug.WriteLine($"MsalUiRequiredException: {ex.Message}");

            try
            {
                Console.WriteLine("trying method2");
                authResult = await App.PublicClientApp.AcquireTokenAsync(_scopes);

            }
            catch (MsalException msalex)
            {
                txtOutput.Text = $"Error Acquiring Token:{System.Environment.NewLine}{msalex}";

            }
        }
        catch (Exception ex)
        {
            txtOutput.Text = $"Error Acquiring Token Silently:{System.Environment.NewLine}{ex}";
            return;
        }

        if (authResult != null)
        {
            //txtOutput.Text = await GetHttpContentWithToken(url, authResult.AccessToken);
            String strResult = await GetHttpContentWithToken(url, authResult.AccessToken);
            txtOutput.Text = strResult;

        }
    }

    /// <summary>
    /// Perform an HTTP GET request to a URL using an HTTP Authorization header
    /// </summary>
    /// <param name="url">The URL</param>
    /// <param name="token">The token</param>
    /// <returns>String containing the results of the GET operation</returns>
    public async Task<string> GetHttpContentWithToken(string url, string token)
    {
        var httpClient = new System.Net.Http.HttpClient();
        System.Net.Http.HttpResponseMessage response;
        try
        {
            var request = new System.Net.Http.HttpRequestMessage(System.Net.Http.HttpMethod.Get, url);
            //Add the token in Authorization header
            request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);
            response = await httpClient.SendAsync(request);
            var content = await response.Content.ReadAsStringAsync();
            return content;
        }
        catch (Exception ex)
        {
            return ex.ToString();
        }
    }

    private void btnSignOut_Click(object sender, RoutedEventArgs e)
    {
        if (App.PublicClientApp.Users.Any())
        {
            try
            {
                App.PublicClientApp.Remove(App.PublicClientApp.Users.FirstOrDefault());
                this.txtOutput.Text = "User has signed-out";
                //this.CallGraphButton.Visibility = Visibility.Visible;
                //this.SignOutButton.Visibility = Visibility.Collapsed;
            }
            catch (MsalException ex)
            {
                txtOutput.Text = $"Error signing-out user: {ex.Message}";
                }
            }
        }
    }
}
//使用Microsoft.IdentityModel.Clients.ActiveDirectory;
使用Microsoft.Identity.Client;
使用制度;
使用System.Collections.Generic;
使用System.Linq;
使用系统文本;
使用System.Threading.Tasks;
使用System.Windows;
使用System.Windows.Controls;
使用System.Windows.Data;
使用System.Windows.Documents;
使用System.Windows.Input;
使用System.Windows.Media;
使用System.Windows.Media.Imaging;
使用System.Windows.Navigation;
使用System.Windows.Shapes;
命名空间O365\u图形\u连接器
{
/// 
///MainWindow.xaml的交互逻辑
/// 
公共部分类主窗口:窗口
{
//图端点
//$upn=“userPrincipalName eq'+$user.Id+'”
字符串url=”https://graph.windows.net/mydomain.com/activities/signinEvents?api-version=beta&`$filter=userPrincipalName eq'upn@withheld.com'";
//字符串url=”https://graph.microsoft.com/v1.0/me/";
//范围
string[]_scopes=新字符串[]{“Directory.Read.All”};
公共主窗口()
{
初始化组件();
txtOutput.Text=“bla”;
}
专用异步无效BTN连接\u单击(对象发送方,路由目标)
{
AuthenticationResult authResult=null;
尝试
{
如果(authResult==null)
{
authResult=wait App.PublicClientApp.AcquireTokenSilentAsync(_scopes,App.PublicClientApp.Users.FirstOrDefault());
Console.WriteLine(“已验证”);
}
}
捕获(MsalUiRequiredException ex)
{
//AcquireTokenSilentAsync上发生MsalUiRequiredException。这表示需要调用AcquireTokenAsync来获取令牌
System.Diagnostics.Debug.WriteLine($“MsalUiRequiredException:{ex.Message}”);
尝试
{
Console.WriteLine(“尝试方法2”);
authResult=await App.PublicClientApp.AcquireTokenAsync(_作用域);
}
捕获(MsalException-msalex)
{
txtOutput.Text=$“获取令牌时出错:{System.Environment.NewLine}{msalex}”;
}
}
捕获(例外情况除外)
{
txtOutput.Text=$“以静默方式获取令牌时出错:{System.Environment.NewLine}{ex}”;
返回;
}
if(authResult!=null)
{
//txtOutput.Text=等待GetHttpContentWithToken(url,authResult.AccessToken);
String stresult=等待GetHttpContentWithToken(url,authResult.AccessToken);
Text=stresult;
}
}
/// 
///使用HTTP授权头对URL执行HTTP GET请求
/// 
///网址
///代币
///包含GET操作结果的字符串
公共异步任务GetHttpContentWithToken(字符串url,字符串令牌)
{
var httpClient=new System.Net.Http.httpClient();
System.Net.Http.HttpResponseMessage响应;
尝试
{
var request=new System.Net.Http.HttpRequestMessage(System.Net.Http.HttpMethod.Get,url);
//在授权标头中添加令牌
request.Headers.Authorization=new System.Net.Http.Headers.AuthenticationHeaderValue(“承载者”,令牌);
响应=等待httpClient.SendAsync(请求);
var content=await response.content.ReadAsStringAsync();
返回内容;
}
捕获(例外情况除外)
{
返回例如ToString();
}
}
私有void btnSignOut_单击(对象发送者,路由目标e)
{
if(App.PublicClientApp.Users.Any())
{
尝试
{
App.PublicClientApp.Remove(App.PublicClientApp.Users.FirstOrDefault());
this.txtOutput.Text=“用户已注销”;
//this.CallGraphButton.Visibility=可见性.Visibility;
//this.signexputton.Visibility=可见性.已折叠;
}
渔获物(MSAlexex)
{
Text=$“注销用户时出错:{ex.Message}”;
}
}
}
}
}
字符串url=“`$filter=userPrincipalName eq”upn@withheld.com'";

根据您的描述,您正在访问。我按照这个来检查这个问题。我用目录.Read.All检查了仅应用程序范围(应用程序作为服务运行,没有登录用户)和委托范围(委托登录用户的权限),我还可以检索用户信息

但是,当我使用访问令牌通过邮递员访问登录活动API端点时,我收到一个响应并提示我将我的租户升级到Azure AD Premium tier,然后我拿起我的目录并通过在Azure门户上单击“公司品牌>获取免费Premium试用版”激活试用版。升级后,我可以按如下方式检索登录活动:

此外,我还遇到了如下类似问题:


通常,您可以利用对访问令牌进行解码,并确保相关属性已正确包含。

我在您的上一个屏幕截图中看到了excat错误消息。当我使用powershell时,它可以工作。因此,powershell变体的工作方式似乎与wpf变体不同。它还与graph api I有关