要使用不需要AAD注册的Microsoft Graph的MFA客户端,可以使用以下解决方法:
using System;
using System.Net.Http;
using System.Threading.Tasks;
public class Program
{
static async Task Main(string[] args)
{
// 定义OAuth 2.0授权码流程的参数
var clientId = "YourClientId";
var redirectUri = "https://your-redirect-uri";
var authEndpoint = "https://login.microsoftonline.com/common/oauth2/v2.0/authorize";
var tokenEndpoint = "https://login.microsoftonline.com/common/oauth2/v2.0/token";
var scope = "https://graph.microsoft.com/.default";
// 构建授权码请求URL
var authUrl = $"{authEndpoint}?client_id={clientId}&response_type=code&redirect_uri={redirectUri}&response_mode=query&scope={scope}";
Console.WriteLine("请在浏览器中打开以下URL,并登录您的Microsoft账户进行授权:");
Console.WriteLine(authUrl);
Console.WriteLine("授权完成后,请将浏览器重定向的URL中的授权码复制粘贴到下方:");
// 获取授权码
var authCode = Console.ReadLine();
using (var client = new HttpClient())
{
// 使用授权码交换访问令牌
var tokenRequest = new FormUrlEncodedContent(new[]
{
new KeyValuePair("client_id", clientId),
new KeyValuePair("code", authCode),
new KeyValuePair("redirect_uri", redirectUri),
new KeyValuePair("grant_type", "authorization_code"),
new KeyValuePair("scope", scope)
});
var tokenResponse = await client.PostAsync(tokenEndpoint, tokenRequest);
// 解析访问令牌
var tokenJson = await tokenResponse.Content.ReadAsStringAsync();
Console.WriteLine("访问令牌:");
Console.WriteLine(tokenJson);
}
}
}
using System;
using System.Net.Http;
using System.Threading.Tasks;
public class Program
{
static async Task Main(string[] args)
{
// 定义客户端凭据流程的参数
var clientId = "YourClientId";
var clientSecret = "YourClientSecret";
var tokenEndpoint = "https://login.microsoftonline.com/YourTenantId/oauth2/v2.0/token";
var scope = "https://graph.microsoft.com/.default";
using (var client = new HttpClient())
{
// 使用客户端凭据交换访问令牌
var tokenRequest = new FormUrlEncodedContent(new[]
{
new KeyValuePair("client_id", clientId),
new KeyValuePair("client_secret", clientSecret),
new KeyValuePair("grant_type", "client_credentials"),
new KeyValuePair("scope", scope)
});
var tokenResponse = await client.PostAsync(tokenEndpoint, tokenRequest);
// 解析访问令牌
var tokenJson = await tokenResponse.Content.ReadAsStringAsync();
Console.WriteLine("访问令牌:");
Console.WriteLine(tokenJson);
}
}
}
请注意,无论哪种方法,您都需要替换示例代码中的参数为您自己的实际值,如YourClientId、YourClientSecret等。