无效的承载令牌

时间:2019-09-26 12:35:42

标签: c# azure authentication

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

  

[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:执行functi时发生异常   上: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;
}

2 个答案:

答案 0 :(得分:0)

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

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

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

要解决此问题:

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

enter image description here

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

答案 1 :(得分:0)

检查 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