This scenario is for a UWP app for which Windows domain authentication needs to be used.
When creating Windows Forms applications, I can use the code below to have the user input their domain credentials to verify the user and then provide permission to perform tasks within the application.
The code below works perfectly in Windows Forms applications as in if the user is connected to the network, it authenticates with the server and otherwise validates with the cached credentials.
How can I validate active directory credentials both on the server and locally cached in a UWP app?
private void button1_Click(object sender, EventArgs e)
{
bool valid = false;
try
{
using (PrincipalContext context = new PrincipalContext(ContextType.Domain))
{
valid = context.ValidateCredentials(textBox1.Text, textBox2.Text);
if (valid)
{
// Login with server credentials successful
MessageBox.Show("Successfully Logged In");
}
else
{
// Login with server credentials failed
MessageBox.Show("Invalid UserName/Password");
}
}
}
catch (PrincipalServerDownException exPSD)
{
//server is down; check local cache
MessageBox.Show("server is down; check local cache");
valid = false;
using (PrincipalContext checkpass = new PrincipalContext(ContextType.Machine)) //checks local machine first
{
valid = checkpass.ValidateCredentials(textBox1.Text, textBox2.Text);
if (valid)
{
// Login with cached credentials successful
MessageBox.Show("Successfully Logged In");
}
else
{
// Login with cached credentials failed
MessageBox.Show("Invalid UserName/Password");
}
}
}
catch (Exception ex)
{
//some other exception; show general message
MessageBox.Show("some other exception; show general message");
}
}
The Web Account Management sample shows how to validate credentials against AD.