MSAL.Net code to call a B2C application
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Threading.Tasks; | |
using Microsoft.Identity.Client; | |
using System.Net.Http; | |
using System.Net; | |
namespace msalb2c | |
{ | |
class Program | |
{ | |
// your b2c tenant name | |
private static readonly string Tenant = "<tenant>.onmicrosoft.com"; | |
// your b2c tenant name | |
private static readonly string AzureAdB2CHostname = "<tenant>.b2clogin.com"; | |
// private static readonly string AzureAdB2CHostname = "login.microsoftonline.com"; | |
// Application ID of the MSAL.Net app | |
private static readonly string ClientId = "<Application ID>"; | |
// Your Policy Name. Should be something similar to B2C_1_SomeName | |
public static string PolicySignUpSignIn = "<Your Policy Name>"; | |
// use the full API scope in the "Published scopes" of the API app | |
public static string[] ApiScopes = { "<Your Web API scope>" }; | |
// Your Web API | |
public static string ApiEndpoint = "<Your API endpoint>"; | |
private static string AuthorityBase = $"https://{AzureAdB2CHostname}/tfp/{Tenant}/"; | |
public static string AuthoritySignInSignUp = $"{AuthorityBase}{PolicySignUpSignIn}"; | |
public static IPublicClientApplication PublicClientApp { get; private set; } | |
static void Main(string[] args) | |
{ | |
Console.WriteLine("Hello World!"); | |
AuthenticationResult result = GetToken().Result; | |
if (result != null) | |
{ | |
var content = SendRequest(ApiEndpoint, result.AccessToken).Result; | |
Console.WriteLine($"response from Azure Function App: {content}\r\n"); | |
} | |
Console.ReadKey(); | |
} | |
public static async Task<AuthenticationResult> GetToken() | |
{ | |
PublicClientApp = PublicClientApplicationBuilder.Create(ClientId) | |
.WithB2CAuthority(AuthoritySignInSignUp) | |
.Build(); | |
AuthenticationResult authResult = null; | |
IEnumerable<IAccount> accounts = await PublicClientApp.GetAccountsAsync(); | |
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; | |
try | |
{ | |
authResult = await PublicClientApp.AcquireTokenSilent(ApiScopes, GetAccountByPolicy(accounts, PolicySignUpSignIn)).ExecuteAsync(); | |
} | |
catch (MsalUiRequiredException ex) | |
{ | |
Console.WriteLine($"MsalUiRequiredException: {ex.Message}\r\n"); | |
try | |
{ | |
authResult = await PublicClientApp.AcquireTokenInteractive(ApiScopes) | |
.WithAccount(GetAccountByPolicy(accounts, PolicySignUpSignIn)) | |
.ExecuteAsync(); | |
} | |
catch (MsalException msalex) | |
{ | |
Console.WriteLine($"Error Acquiring Token:{System.Environment.NewLine}{msalex}\r\n"); | |
} | |
} | |
catch (Exception ex) | |
{ | |
Console.WriteLine($"Error Acquiring Token Silently:{System.Environment.NewLine}{ex}\r\n"); | |
} | |
if (authResult != null) | |
{ | |
Console.WriteLine($"access token: {authResult.AccessToken}\r\n"); | |
Console.WriteLine($"id token: {authResult.IdToken}\r\n"); | |
} | |
return authResult; | |
} | |
public static IAccount GetAccountByPolicy(IEnumerable<IAccount> accounts, string policy) | |
{ | |
foreach (var account in accounts) | |
{ | |
string userIdentifier = account.HomeAccountId.ObjectId.Split('.')[0]; | |
if (userIdentifier.EndsWith(policy.ToLower())) | |
return account; | |
} | |
return null; | |
} | |
public static async Task<string> SendRequest(string url, string token) | |
{ | |
var httpClient = new HttpClient(); | |
HttpResponseMessage response; | |
try | |
{ | |
var request = new HttpRequestMessage(HttpMethod.Get, url); | |
request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token); | |
response = await httpClient.SendAsync(request); | |
var content = await response.Content.ReadAsStringAsync(); | |
return content; | |
} | |
catch (Exception ex) | |
{ | |
return ex.ToString(); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment