以下是一个使用AD B2C的非交互/无头身份验证并使用资源所有者密码凭证流程的代码示例:
using System;
using System.Net.Http;
using System.Threading.Tasks;
using Newtonsoft.Json;
public class Program
{
public static async Task Main(string[] args)
{
// 配置AD B2C租户和应用程序的详细信息
string tenantId = "your-tenant-id";
string clientId = "your-client-id";
string clientSecret = "your-client-secret";
string policy = "your-policy-name";
string scope = "your-scope";
// 构建请求的参数
var requestParams = new Dictionary
{
{ "grant_type", "password" },
{ "client_id", clientId },
{ "client_secret", clientSecret },
{ "scope", scope },
{ "username", "your-username" },
{ "password", "your-password" },
};
// 构建请求的URL
string requestUrl = $"https://{tenantId}.b2clogin.com/{tenantId}.onmicrosoft.com/{policy}/oauth2/v2.0/token";
// 发送请求获取访问令牌
using (var httpClient = new HttpClient())
{
var response = await httpClient.PostAsync(requestUrl, new FormUrlEncodedContent(requestParams));
var responseContent = await response.Content.ReadAsStringAsync();
// 解析响应内容
var tokenResponse = JsonConvert.DeserializeObject(responseContent);
if (tokenResponse != null && !string.IsNullOrEmpty(tokenResponse.AccessToken))
{
// 使用访问令牌调用API
string apiUrl = "your-api-url";
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", tokenResponse.AccessToken);
var apiResponse = await httpClient.GetAsync(apiUrl);
var apiResponseContent = await apiResponse.Content.ReadAsStringAsync();
Console.WriteLine(apiResponseContent);
}
}
}
public class TokenResponse
{
[JsonProperty("access_token")]
public string AccessToken { get; set; }
[JsonProperty("expires_in")]
public int ExpiresIn { get; set; }
[JsonProperty("token_type")]
public string TokenType { get; set; }
}
}
请注意,此示例代码仅用于说明目的。在实际环境中,应该进行错误处理、参数验证和安全性考虑。