|
C# Authentication Program Example
Create a new console application project and you might want to use AuthenticateCS as the solution and project names.
|
Rename the source file to AuthenticateClassExample to reflect our application. The class name also will be automatically renamed to the same name.
Add the following codes.
using System; using System.Net; using System.Text; using System.IO; using System.Collections;
namespace AuthenticateCS { class AuthenticateClassExample { /// <summary> /// Displays simple usage information for running the sample. /// </summary> static void usage() { Console.WriteLine("Usage: Executable_file_name [-r URI] [-u user-name] [-p password] [-d domain]"); Console.WriteLine("Available options:"); Console.WriteLine(" -r URI URI resource to retrieve"); Console.WriteLine(" -u user-name Username to use for authentication"); Console.WriteLine(" -p password Password to use for authentication"); Console.WriteLine(" -d domain Domain to use for authentication"); Console.WriteLine(" -m Displays authentication modules"); Console.WriteLine(); }
/// <summary> /// Retrieves the specified URI with the given credential information. The retrieved resource /// is simply printed to the Console. /// </summary> /// <param name="uriName">Resource to retrieve</param> /// <param name="creds">Credential information to associate with the request</param> static void RetrieveUri(string uriName, NetworkCredential creds) { HttpWebRequest httpRequest = null; HttpWebResponse httpResponse = null;
try { httpRequest = (HttpWebRequest)WebRequest.Create(uriName); Uri temp = new Uri(uriName); Console.WriteLine("\nCreating web request...: '{0}'", temp.ToString()); httpRequest.Credentials = creds; httpResponse = (HttpWebResponse)httpRequest.GetResponse(); StreamReader httpReader = new StreamReader(httpResponse.GetResponseStream(), Encoding.UTF8); string httpContent = httpReader.ReadToEnd(); Console.WriteLine(httpContent); httpReader.Close(); } catch (WebException wex) { Console.WriteLine("Exception occurred: {0}", wex.Message); Console.WriteLine(wex.StackTrace); httpResponse = (HttpWebResponse)wex.Response; } finally { if (httpResponse != null) httpResponse.Close(); } }
/// <summary> /// Enumerates and prints the available authentication modules. /// </summary> static void DisplayAuthenticationModules() { IEnumerator registeredModules = AuthenticationManager.RegisteredModules; Console.WriteLine("Authentication Modules:"); while (registeredModules.MoveNext()) { IAuthenticationModule currentAuthenticationModule = (IAuthenticationModule)registeredModules.Current; Console.WriteLine(" Module : {0}", registeredModules.Current); Console.WriteLine(" Supports Pre-Authentication : {0}", currentAuthenticationModule.CanPreAuthenticate); } }
/// <summary> /// This routine parses the command line, creates the user credential object if /// credentials are supplied and issues the request. /// </summary> /// <param name="args">Command line arguments</param> static void Main(string[ ] args) { NetworkCredential userCredentials = null; // string uriResource = "https://accountservices.passport.net/default.srf?id=10&vv=600&lc=1033"; string uriResource = "http://www.micronewsads.com/passport/default.asp? msppchlg=1&mspplogin=http://login.passport.com/login.srf%3Flcid%3D1033%26id%3D6850%26ru%3Dhttp%253A%252F% 252Fwww%252Emicronewsads%252Ecom%252Fpassport%252Fdefault%252Easp%26tw%3D0%26fs%3D1%26kv%3D1% 26ct%3D1054440998%26ems%3D1%26ver%3D1.990.1052.1&C=1"; string userName = null, passWord = null, domain = null; // bool usePassport = false;
usage();
// Parse the command line for(int i=0; i < args.Length ;i++) { try { if ( ( args[i][0] == '-' ) || ( args[i][0] == '/' ) ) { switch ( Char.ToLower( args[i][1] ) ) { case 'd': // Domain to use for authentication domain = args[ ++i ]; break; case 'm': // Display registered authentication modules DisplayAuthenticationModules(); return; case 'p': // Password to use for authentication passWord = args[ ++i ]; break; case 'r': // URI resource to download (get) uriResource = args[ ++i ]; break; case 'u': // Username to use for authentication userName = args[ ++i ]; break; case 'x': // Web proxy to use for all requests WebRequest.DefaultWebProxy = new WebProxy(args[++i]); //GlobalProxySelection.Select = new WebProxy( args[ ++i ] ); break; default: usage(); return; } } } catch { usage(); return; } }
// Make the request Console.WriteLine("Making a request..."); try { if ( ( userName != null ) || ( passWord != null ) || ( domain != null ) ) userCredentials = new NetworkCredential( userName, passWord, domain );
RetrieveUri( uriResource, userCredentials ); } catch ( Exception ex ) { Console.WriteLine("Exception occurred: {0}", ex.Message); Console.WriteLine( ex.StackTrace ); } } } }
|
Build and run the project. The following are the sample of the outputs. You should try running this program against the HTTPS (web) server with username and password.