Skip to content

Instantly share code, notes, and snippets.

@manoj-choudhari-git
Created May 30, 2020 20:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save manoj-choudhari-git/76f12dfd06782ea894d13b11d2cc1cf0 to your computer and use it in GitHub Desktop.
Save manoj-choudhari-git/76f12dfd06782ea894d13b11d2cc1cf0 to your computer and use it in GitHub Desktop.
MSAL and Azure AD B2C - Code Behind for Embedded Login UI in .NET Core WPF
public partial class CustomLoginWindow : Window
{
private readonly Uri _authorizeUri;
private readonly Uri _redirectUri;
private readonly TaskCompletionSource<Uri> _taskCompletionSource;
private readonly CancellationToken _cancellationToken;
private CancellationTokenRegistration _cancellationTokenRegistration;
public CustomLoginWindow(
Uri authorizationUri,
Uri redirectUri,
TaskCompletionSource<Uri> taskCompletionSource,
CancellationToken cancellationToken)
{
InitializeComponent();
_authorizeUri = authorizationUri;
_redirectUri = redirectUri;
_taskCompletionSource = taskCompletionSource;
_cancellationToken = cancellationToken;
}
private void webBrowserControl_Navigating(object sender, NavigatingCancelEventArgs e)
{
// if URI does not starts with redirect URI, then return
if (!e.Uri.ToString().StartsWith(_redirectUri.ToString()))
{
// not redirect uri case
return;
}
// Parse query strings and check for code parameter
var query = HttpUtility.ParseQueryString(e.Uri.Query);
if (query.AllKeys.Any(x => x == "code"))
{
// It has a code parameter.
_taskCompletionSource.SetResult(e.Uri);
Close();
return;
}
// Otherwise there is an error
_taskCompletionSource.SetException(
new MsalExtensionException(
$"An error occurred, error: {query.Get("error")}, error_description: {query.Get("error_description")}"));
Close();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
// Register cancellation token
_cancellationTokenRegistration = _cancellationToken.Register(() => _taskCompletionSource.SetCanceled());
// Navigate to entry point of authorization flow
webBrowserControl.Navigate(_authorizeUri);
}
private void Window_Closed(object sender, EventArgs e)
{
// Displose the cancellation token
_taskCompletionSource.TrySetCanceled();
_cancellationTokenRegistration.Dispose();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment