Created
May 29, 2020 21:14
-
-
Save manoj-choudhari-git/46d6500e7ead9ed8c88c4aef17611df5 to your computer and use it in GitHub Desktop.
Azure AD Authentication for WPF App using MSAL
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
public partial class MainWindow : Window | |
{ | |
public MainWindow() | |
{ | |
InitializeComponent(); | |
} | |
private async void SignInButton_Click(object sender, RoutedEventArgs e) | |
{ | |
string[] scopes = new string[] { "user.read" }; | |
AuthenticationResult authResult = null; | |
var app = App.PublicClientApp; | |
try | |
{ | |
ResultText.Text = ""; | |
authResult = await (app as PublicClientApplication).AcquireTokenInteractive(scopes) | |
.ExecuteAsync(); | |
DisplayBasicTokenInfo(authResult); | |
UpdateSignInState(true); | |
} | |
catch (Exception ex) | |
{ | |
ResultText.Text = $"Error Acquiring Token:{Environment.NewLine}{ex}"; | |
} | |
} | |
private async void SignOutButton_Click(object sender, RoutedEventArgs e) | |
{ | |
IEnumerable<IAccount> accounts = await App.PublicClientApp.GetAccountsAsync(); | |
try | |
{ | |
while (accounts.Any()) | |
{ | |
await App.PublicClientApp.RemoveAsync(accounts.FirstOrDefault()); | |
accounts = await App.PublicClientApp.GetAccountsAsync(); | |
} | |
UpdateSignInState(false); | |
} | |
catch (MsalException ex) | |
{ | |
ResultText.Text = $"Error signing-out user: {ex.Message}"; | |
} | |
} | |
private void UpdateSignInState(bool signedIn) | |
{ | |
if (signedIn) | |
{ | |
SignOutButton.Visibility = Visibility.Visible; | |
SignInButton.Visibility = Visibility.Collapsed; | |
} | |
else | |
{ | |
ResultText.Text = ""; | |
TokenInfoText.Text = ""; | |
SignOutButton.Visibility = Visibility.Collapsed; | |
SignInButton.Visibility = Visibility.Visible; | |
} | |
} | |
private void DisplayBasicTokenInfo(AuthenticationResult authResult) | |
{ | |
TokenInfoText.Text = ""; | |
if (authResult != null) | |
{ | |
TokenInfoText.Text += $"Username: {authResult.Account.Username}" + Environment.NewLine; | |
TokenInfoText.Text += $"Token Expires: {authResult.ExpiresOn.ToLocalTime()}" + Environment.NewLine; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment