Skip to content

Instantly share code, notes, and snippets.

@roycornelissen
Last active July 16, 2019 08:41
Show Gist options
  • Save roycornelissen/7eafb17b27485933c1d15d942d7e26b6 to your computer and use it in GitHub Desktop.
Save roycornelissen/7eafb17b27485933c1d15d942d7e26b6 to your computer and use it in GitHub Desktop.
Azure AD B2C Console App
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp2.2</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Identity.Client" Version="4.1.0" />
</ItemGroup>
</Project>
using Microsoft.Identity.Client;
using System;
using System.Threading.Tasks;
namespace ADB2C_TestClient
{
class Program
{
private const string B2C_INSTANCE = "https://login.microsoftonline.com/tfp/{0}/{1}/";
private const string CLIENT_ID = "[redacted]";
private const string REDIRECT_URI = "http://localhost:44365"; // need to pin this to a specific url:port, and it has to be http://localhost, otherwise MSAL won't accept it :(
private const string TENANT = "[redacted].onmicrosoft.com";
private const string POLICY = "B2C_1_SIGNUP_POC";
private static readonly string[] scopes = new[] { "https://[redacted]/user_impersonation" };
static void Main(string[] args)
{
var app = PublicClientApplicationBuilder.Create(CLIENT_ID)
.WithRedirectUri(REDIRECT_URI)
.WithB2CAuthority(string.Format(B2C_INSTANCE, TENANT, POLICY))
.WithLogging(Log, LogLevel.Warning, true)
.Build();
var result = AcquireTokenInteractive(app).GetAwaiter().GetResult();
if (result != null)
{
Console.WriteLine($"User name: {result.Account.Username}");
Console.WriteLine($"Access token: {result.AccessToken}");
}
}
private static void Log(LogLevel level, string message, bool containsPii)
{
Console.WriteLine($"{level}: {message}");
}
private static async Task<AuthenticationResult> AcquireTokenInteractive(IPublicClientApplication app)
{
try
{
var authResult = await app.AcquireTokenInteractive(scopes)
.WithPrompt(Prompt.SelectAccount)
.WithUseEmbeddedWebView(false)
.WithSystemWebViewOptions(new SystemWebViewOptions
{
HtmlMessageSuccess = "Login succeeded. You can close this browser.",
HtmlMessageError = "Hmm, something went wrong... Please close this browser."
})
.ExecuteAsync();
return authResult;
}
catch (MsalException msalex)
{
string msg = msalex.Message;
if (msalex.InnerException != null)
{
msg += $"Error Code: {msalex.ErrorCode} Inner Exception: {msalex.InnerException.Message}";
}
Console.WriteLine($"Error logging in: {msg}");
}
catch (Exception ex)
{
string msg = ex.Message;
if (ex.InnerException != null)
{
msg += $"Inner Exception: {ex.InnerException.Message}";
}
Console.WriteLine($"Error logging in: {msg}");
}
return null;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment