|
C++ Authentication Program Example
Create a new CLR console application project and you might want to use AuthenticateCP as the project and the solution names.
|
Add the following codes for a few functions and the main().
// AuthenticateCP.cpp : main project file.
#include "stdafx.h"
using namespace System; using namespace System::Net; using namespace System::Text; using namespace System::IO; using namespace System::Collections;
/// <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 = nullptr; HttpWebResponse^ httpResponse = nullptr;
try { httpRequest = (HttpWebRequest^)WebRequest::Create(uriName); Uri^ temp = gcnew Uri(uriName); Console::WriteLine("\nCreating web request...: '{0}'", temp->ToString());
httpRequest->Credentials = creds; httpResponse = (HttpWebResponse^)httpRequest->GetResponse(); StreamReader^ httpReader = gcnew 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 != nullptr) 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> int main(array<System::String ^> ^args) { NetworkCredential^ userCredentials = nullptr; // 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 = nullptr; String^ passWord = nullptr; String^ domain = nullptr; // bool usePassport = false;
// Parse the command line if(args->Length != 0) { 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 0; 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 = gcnew WebProxy(args[++i]); // GlobalProxySelection::Select = gcnew WebProxy( args[ ++i ] ); break; default: usage(); return 0; } } } catch(Exception^ err) { Console::WriteLine("Error: " + err->Message); usage(); return 0; } } } else { usage(); return 0; }
// Make the request Console::WriteLine("Making a request..."); try { if ( ( userName != nullptr ) || ( passWord != nullptr ) || ( domain != nullptr ) ) userCredentials = gcnew NetworkCredential( userName, passWord, domain ); RetrieveUri( uriResource, userCredentials ); } catch ( Exception^ ex ) { Console::WriteLine("Exception occurred: {0}", ex->Message); Console::WriteLine( ex->StackTrace ); } return 0; } |
Build and run the project. The following are snapshots of the sample outputs. You should try running this program against the HTTPS (web) server.