繁体   English   中英

不记名令牌无效

[英]Invalid bearer token

我有两种方法。 一个人根据我注册的应用程序的 Azure ClientID 和 Azure 密钥获取并返回访问令牌。 然后第二个调用 Azure Function,但是 function 返回错误:

[9/26/2019 12:18:49 PM] 创建一个新团队。

[9/26/2019 12:19:00 PM] 执行“AddTeam”(失败,Id=aaecc7fa-e3bd-40e7-8be9-a 8a173cc166b)

[9/26/2019 12:19:00 PM] System.Private.CoreLib:执行功能时出现异常:AddTeam。 System.Net.Http:值'Bearer'的格式无效。

感谢任何帮助,因为它让我发疯!

public static async Task<string> GetAccessToken()
{
    string clientId = "clientIDFromAzure";
    string clientKey = "secretKeyFromAzure";

    string authContextURL = "https://login.microsoftonline.com/tennantID";
    var authenticationContext = new AuthenticationContext(authContextURL);
    var credential = new ClientCredential(clientId, clientKey);
    var result = await authenticationContext
            .AcquireTokenAsync("https://management.azure.com/", credential);
    if (result == null)
    {
        throw new InvalidOperationException("Failed to obtain the token");
    }
    string token = result.AccessToken;
    return token;
}

public static async Task<string> CallGraph(HttpMethod method, string uri, string body)
{

    HttpClient httpClient = new HttpClient();
    string graphEndpoint = "https://graph.microsoft.com/";

    var request = new HttpRequestMessage(method, graphEndpoint + uri);
    request.Headers.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

    string accessToken = await TokenHelper.GetAccessToken();

    request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer ", accessToken);

    if (method != HttpMethod.Get)
        request.Content = new StringContent(body, Encoding.UTF8, "applciation/json");
    HttpResponseMessage response = await httpClient.SendAsync(request);
    string responseBody = await response.Content.ReadAsStringAsync();
    if (!response.IsSuccessStatusCode)
        throw new Exception(responseBody);
    return responseBody;
}

GetAccessToken方法中,您试图获取 Azure 管理 API 的访问令牌。

var result = await authenticationContext
            .AcquireTokenAsync("https://management.azure.com/", credential);

但是,您实际上使用该令牌来调用 Microsoft Graph API。 这就是您收到身份验证错误的原因。

要解决这个问题:

  1. 您需要在 Azure AD 中注册的应用中添加必要的 Graph API 权限,然后同意这些权限。

在此处输入图像描述

  1. 修改您的代码以获取 Microsoft Graph API 的令牌。
var result = await authenticationContext
            .AcquireTokenAsync("https://graph.microsoft.com/", credential);

检查 Bearer 之后的空格是否是真正的空格字符 (0x20),而不是 Unicode 等价物,例如不间断空格 (0xa0)。 我在 Visual Studio Code、OneNote 和 PowerShell 之间复制/粘贴时遇到了这个问题。

请注意,某些脚本语言(例如 PowerShell)在默认字符串比较中将这些字符视为相同:

'Bearer ' | Format-Hex # View as hex 

"`u{20}" -eq "`u{a0}"  # True: space == non-breaking space

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM