无法在控制台应用中使用ADAL.NET和Microsoft Graph API提取令牌

时间:2019-12-11 02:15:47

标签: c# microsoft-graph

我尝试从Office 365 excel访问我的excel,但是失败。

这是我的代码:

    namespace active_directory_wpf_msgraph_v2
    {
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
    public partial class MainWindow : Window
    {
//Set the API Endpoint to Graph 'me' endpoint
        string graphAPIEndpoint = "https://graph.microsoft.com/v1.0/me/drive/root/search(q='Book.xlsx')";

//Set the scope for API call to user.read
        string[] scopes = new string[] { "user.read","Files.ReadWrite", "Files.ReadWrite.Selected" };
        public MainWindow()
        {
            InitializeComponent();
        }

/// <summary>
/// Call AcquireToken - to acquire a token requiring user to sign-in
/// </summary>
        private async void CallGraphButton_Click(object sender, RoutedEventArgs e)
        {
            TokenCache tokenCache = new TokenCache();

// load tokens from file 
            string tokenPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Excel365Test");
            if (!System.IO.Directory.Exists(tokenPath)) { System.IO.Directory.CreateDirectory(tokenPath); }
            tokenPath = Path.Combine(tokenPath, "tokens.dat");
            if (System.IO.File.Exists(tokenPath))
            {
                tokenCache.Deserialize(System.IO.File.ReadAllBytes(tokenPath));
            }
            // this is the OAUTH 2.0 TOKEN ENDPOINT from https://portal.azure.com/ -> Azure Active Directory -> App Registratuons -> End Points
            var authenticationContext = new AuthenticationContext(graphAPIEndpoint, tokenCache);

// only prompt when needed, you'll get a UI the first time you run


var platformParametes = new PlatformParameters(PromptBehavior.Auto);

        var authenticationResult = authenticationContext.AcquireTokenAsync("https://graph.microsoft.com/",
            "MyclientID",     // Application ID from https://portal.azure.com/
            new Uri("https://login.live.com/oauth20_desktop.srf"),         // Made up redirect URL, also from https://portal.azure.com/
            platformParametes).Result;
        string token = authenticationResult.AccessToken;

            // save token so we don't need to re-authorize
        System.IO.File.WriteAllBytes(tokenPath, tokenCache.Serialize());

            // use the token with Microsoft.Graph calls


GraphServiceClient client = new GraphServiceClient(new DelegateAuthenticationProvider(
        (requestMessage) =>
        {
            requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", token);

            return Task.FromResult(0);
        }));
    }

/// <summary>
/// Perform an HTTP GET request to a URL using an HTTP Authorization header
/// </summary>


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();
                }
            }
        }
    }

在那里在authenticationResult弹出错误。 错误显示:

  1. AdalException:authority_not_in_valid_list:“ authority”不在有效地址列表中
  2. AdalServiceException:AADSTS50049:未知或无效实例。 跟踪ID:1ff97781-991f-4f8e-9005-810277384f01 相关编号:65c0f15b-2f74-45cd-833e-141bbfa0d2a5 时间戳记:2019-12-11 02:14:27Z
  3. AdalServiceException:响应状态代码未指示成功:400(BadRequest)。

请帮助我解决这个问题。

0 个答案:

没有答案