尝试访问OneDrive文件时收到401无效的身份验证令牌

时间:2019-05-08 05:55:24

标签: c# onedrive

我相信我将使用我基本上从Microsoft Graph网站复制并粘贴的这段代码从Microsoft Graph服务获取有效的访问令牌。

string[] scopes = { "user.read", "files.read"};// new string["user.read"];
AuthenticationResult result = null;
var clientId = [REDACTED];
var app = PublicClientApplicationBuilder.Create(clientId).Build();
var accounts = await app.GetAccountsAsync();

try
{
    result = await app.AcquireTokenSilent(scopes, accounts.FirstOrDefault()).ExecuteAsync();
}
catch (MsalUiRequiredException ex)
{
    // A MsalUiRequiredException happened on AcquireTokenSilent.
    // This indicates you need to call AcquireTokenInteractive to acquire a token
    System.Diagnostics.Debug.WriteLine($"MsalUiRequiredException: {ex.Message}");

    try
    {
        result = await app.AcquireTokenInteractive(scopes)
                          .ExecuteAsync();
    }
    catch (MsalException msalex)
    {
        Debug.WriteLine( $"Error Acquiring Token:{System.Environment.NewLine}{msalex}");
    }
}
catch (Exception ex)
{
    Debug.WriteLine($"Error Acquiring Token Silently:{System.Environment.NewLine}{ex}");
    return;
}

if (result != null)
{
    accessToken = result.AccessToken;
    // Use the token
}

AuthenticationResult.AccessToken看起来像一个令牌。 AuthenticationResult中的范围包括以下内容:

  • files.read
  • files.read.all
  • openid
  • 个人资料
  • user.read

我这样发出请求

UriBuilder builder = new UriBuilder("https://api.onedrive.com");
builder.Path = "/v1.0/me/drive/root/children";
Uri url = builder.Uri;

HttpClient httpClient = new HttpClient();

httpClient.DefaultRequestHeaders.Add("Authorization", "Bearer " + accessToken);
var response = await httpClient.GetAsync(url);

结果是这样的:

{StatusCode: 401, ReasonPhrase: '', Version: 2.0, Content: System.Net.Http.StreamContent, Headers:
{
  x-qosstats: {"ApiId":0,"ResultType":2,"SourcePropertyId":0,"TargetPropertyId":42}
  x-throwsite: 4f37.717b
  strict-transport-security: max-age=31536000; includeSubDomains
  x-msnserver: CH1AAPCE5584BBF
  p3p: CP="BUS CUR CONo FIN IVDo ONL OUR PHY SAMo TELo"
  date: Wed, 08 May 2019 05:15:17 GMT
  www-authenticate: Bearer realm="OneDriveAPI", error="invalid_token", error_description="Invalid auth token"
  x-msedge-ref: Ref A: 8DF9298AE79A4F8A8417D0A41221308F Ref B: WSTEDGE1006 Ref C: 2019-05-08T05:15:17Z
  x-asmversion: UNKNOWN; 19.245.502.2003
  content-length: 70
}}

我玩过不同的范围和不同的请求。我也在这里和其他地方进行了广泛搜索,发现了类似的问题,但没有任何效果。我有种直觉,这是一个范围/权限问题,但我一直盯着permissions reference,但我不明白。

我应该注意,我已经能够使用旧的OneDrive SDK包装器完成此工作,因此我知道我的应用程序配置正确。我正在尝试切换到原始REST API。

0 个答案:

没有答案