[英]Getting auth token from Microsoft Graph endpoint using cer or pfx on file
我正在嘗試使用我使用自簽名創建的 cer/pfx 證書從 Graph Endpoint 獲取身份驗證令牌。 我已將證書放在文件系統上。 這是我正在使用的代碼:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
using System.Security.Cryptography.X509Certificates;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
namespace DAL_HTTP
{
public class MSGraphAuth
{
public string _tenantId;
public string _clientId;
public string _certificateThumbprint;
public string _debugCertificatePath;
public string _debugCertificatePassword;
public MSGraphAuth()
{
string TenantName = "testtenant.onmicrosoft.com";
string TenantId = "<tenantid>";
string ClientID = "<appid>";
string AuthenticationContextURL = "https://login.microsoftonline.com/testtenant.onmicrosoft.com";
string AcquireTokenURL = "https://graph.microsoft.com";
string ClientKey = "*********";
string certificateFilePath = @"D:\folder\test.onmicrosoft.com.pfx";
string certificatePassword = "*******";
_tenantId = TenantId;
_clientId = ClientID;
_certificateThumbprint = GetCertificateThumprint(certificateFilePath, certificatePassword);
_debugCertificatePath = certificateFilePath;
_debugCertificatePassword = certificatePassword;
}
public string GetCertificateThumprint(string certificateFilePath, string certPassword)
{
X509Certificate2 cert = new X509Certificate2(certificateFilePath, certPassword);
return cert.Thumbprint;
}
public async Task<string> GetAccessTokenAsync(string url)
{
url = GetTenantUrl(url);
var authContext = new AuthenticationContext($"https://login.microsoftonline.com/{_tenantId}/oauth2/token"); // you can also use the v2.0 endpoint URL
return (await authContext.AcquireTokenAsync(url, GetCertificate(_clientId, _certificateThumbprint))).AccessToken;
}
public static string GetTenantUrl(string url)
{
const string suffix = "sharepoint.com";
var index = url.IndexOf(suffix, StringComparison.OrdinalIgnoreCase);
return index != -1 ? url.Substring(0, index + suffix.Length) : url;
}
public ClientAssertionCertificate GetCertificate(string clientId, string thumbprint)
{
var certificate = GetCertificateFromDirectory(_debugCertificatePath, _debugCertificatePassword);
return new ClientAssertionCertificate(clientId, certificate);
}
public static X509Certificate2 GetCertificateFromDirectory(string path, string password)
{
return new X509Certificate2(System.IO.Path.GetFullPath(path), password, X509KeyStorageFlags.DefaultKeySet);
}
private static X509Certificate2 GetCertificateFromStore(string thumbprint)
{
var store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
store.Open(OpenFlags.ReadOnly);
var certificates = store.Certificates.Find(X509FindType.FindByThumbprint, thumbprint, false);
store.Close();
return certificates[0];
}
}
}
但是,我在這一行得到一個錯誤:
return (await authContext.AcquireTokenAsync(url, GetCertificate(_clientId, _certificateThumbprint))).AccessToken;
錯誤消息如下:
mscorlib.dll 中發生了“Microsoft.IdentityModel.Clients.ActiveDirectory.AdalServiceException”類型的未處理異常
附加信息:AADSTS90002:未找到租戶“令牌”。 如果租戶沒有活動訂閱,則可能會發生這種情況。 檢查以確保您擁有正確的租戶 ID。 請咨詢您的訂閱管理員。
跟蹤 ID:c9d3eac6-77e0-4f56-8c96-ac924ff90700
相關 ID:e90027e1-cbcb-4291-9630-984c5c23757d
時間戳:2020-08-14 17:11:34Z
我一直在關注這兩篇文章,但仍然無法正常工作。:
如何使用帶有證書的 Microsoft Graph API (INTUNE)
我究竟做錯了什么? 請幫忙。
看來你沒有得到你想要的令牌,試試這個帶證書的官方樣本。
它使用客戶端憑據流來獲取訪問令牌,該令牌可用於調用 Microsoft Graph 並訪問組織數據。 該示例同時使用證書和客戶端密碼,您可以只使用證書。
private static async Task RunAsync()
{
AuthenticationConfig config = AuthenticationConfig.ReadFromJsonFile("appsettings.json");
// Even if this is a console application here, a daemon application is a confidential client application
IConfidentialClientApplication app;
X509Certificate2 certificate = ReadCertificate(config.CertificateName);
app = ConfidentialClientApplicationBuilder.Create(config.ClientId)
.WithCertificate(certificate)
.WithAuthority(new Uri(config.Authority))
.Build();
// With client credentials flows the scopes is ALWAYS of the shape "resource/.default", as the
// application permissions need to be set statically (in the portal or by PowerShell), and then granted by
// a tenant administrator.
string[] scopes = new string[] { $"{config.ApiUrl}.default" };
AuthenticationResult result = null;
try
{
result = await app.AcquireTokenForClient(scopes)
.ExecuteAsync();
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("Token acquired");
Console.ResetColor();
}
catch (MsalServiceException ex) when (ex.Message.Contains("AADSTS70011"))
{
// Invalid scope. The scope has to be of the form "https://resourceurl/.default"
// Mitigation: change the scope to be as expected
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Scope provided is not supported");
Console.ResetColor();
}
if (result != null)
{
var httpClient = new HttpClient();
var apiCaller = new ProtectedApiCallHelper(httpClient);
await apiCaller.CallWebApiAndProcessResultASync($"{config.ApiUrl}v1.0/users", result.AccessToken, Display);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.