Below is the code related to how to connect to Azure AD B2C using B2CGraphClient.
1. Get Access Token using following approach :
this.clientId = clientId;
this.clientSecret = clientSecret;
this.tenant = tenant;
// The AuthenticationContext is ADAL's primary class, in which you indicate the direcotry to use.
this.authContext = new AuthenticationContext("https://login.microsoftonline.com/" + tenant);
// The ClientCredential is where you pass in your client_id and client_secret, which are
// provided to Azure AD in order to receive an access_token using the app's identity.
this.credential = new ClientCredential(clientId, clientSecret);
2. Send Graph Request using below code :
// First, use ADAL to acquire a token using the app's identity (the credential)
// The first parameter is the resource we want an access_token for; in this case, the Graph API.
Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationResult result = await authContext.AcquireTokenAsync("https://graph.windows.net", credential);
//AuthenticationResult result = authContext.AcquireToken("https://graph.windows.net", credential);
// For B2C user managment, be sure to use the 1.6 Graph API version.
HttpClient http = new HttpClient();
string url = "https://graph.windows.net/" + tenant + api + "?" + Globals.aadGraphVersion;
if (!string.IsNullOrEmpty(query))
{
url += "&" + query;
}
Console.ForegroundColor = ConsoleColor.Cyan;
// Append the access token for the Graph API to the Authorization header of the request, using the Bearer scheme.
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, url);
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);
HttpResponseMessage response = await http.SendAsync(request);
if (!response.IsSuccessStatusCode)
{
string error = await response.Content.ReadAsStringAsync();
object formatted = JsonConvert.DeserializeObject(error);
throw new WebException("Error Calling the Graph API: \n" + JsonConvert.SerializeObject(formatted, Formatting.Indented));
}
Console.ForegroundColor = ConsoleColor.Green;
await response.Content.ReadAsStringAsync();
No comments:
Post a Comment