Sdílet prostřednictvím


Implementing the credential prompter

I received a question on my earlier post on implementing the credential prompter. When connecting to the web service you have to specify a CatalogServiceAgent object. When authenticating against a Web service, the default behavior is to first try to make Web service method calls without any authentication credentials.  If an Authentication related exception results (e.g. HTTP 401 response from the Web server), then the next step is to try using the user's default credentials, if available. If those credentials are not available or also fail, and the CatalogServiceAgent has been provided with an IPromptForCredentials  implementation, then the IPromptForCredentials.PromptForCredentials method is invoked to retrieve alternate credentials for the user.  This typically involves displaying a dialog box to a user in order to prompt them to input new credentials. These credentials are then cached in a System.Net.CredentialCache object and re-used when issuing further method calls against the service.

A sample implementation of the credential prompter whcih prompts the user for the login name and password can be done as follows:

 

internal class UserCredentialPrompter : IPromptForCredentials

{

      public NetworkCredential PromptForCredentials(string url,

      string authType)

      {

            // Set the network credentials

            NetworkCredential myCredentials = null;

            // Launch dialog to capture the user name and password

            Login form = new Login();

      // Show the Login dialog

            DialogResult result = form.ShowDialog();

            if (result == DialogResult.OK)

            {

                // Create the NetworkCredential based on user input

                myCredentials = new NetworkCredential(form.UserName,

                  form.Password, form.Domain);

            }

            // Return the obtained credentials

            return myCredentials;

      }

}

 

You can then instantiate the CatalogServiceAgent as

CatalogServiceAgent catalogServiceAgent = new CatalogServiceAgent(@"https://Servername/CatalogWebservice/CatalogWebservice.asmx", ServiceAgent.DefaultAuthMethods, new UserCredentialPrompter());

CatalogContext context = CatalogContext.Create(catalogServiceAgent);