Search code examples
c#.netsslauthorizationsnmp

How do I check for invalid credentials while making a ssl connection in C#


I have this method which tries to catch an exception that might be thrown when supplied with invalid credentials when connecting through SSL. The credentials are supplied through SNMP. But I am not always able to interpret the exception as invalid credentials, as you can see I am only trying to read the message of exception thrown which differs from a device to device.

Is what am I doing correct? Are there any foolproof ways to check if the credentials needed to make the connection is valid? I am totally lost here as the exception message thrown changes from device to device.

Thanks for any pointers.

try
{
    string ipSSL = string.Format(URL_CWIS_HELPSTRING, "s", SecurityBindingProxy.Destination.Address.Value.Host, "/");
    System.Net.WebRequest https = System.Net.HttpWebRequest.Create(ipSSL);
    System.Net.ServicePointManager.ServerCertificateValidationCallback = WsdlClient.ServiceRequirements.WsdlServiceRequirements.SSLCheckCallback;
    https.Credentials = new System.Net.NetworkCredential(SNMP.ConnectionInfo.Instance.Username, SNMP.ConnectionInfo.Instance.Password); ;
    System.Net.HttpWebResponse responseSSL = (System.Net.HttpWebResponse)https.GetResponse();
    responseSSL.Close();
}
catch (Exception ex)
{
    if (ex.Message.Contains("Unauthorized")
        || ex.Message.Contains("401"))
    {
        return -2;
    }
}

Solution

  • You want to be catching a more specific type of exception rather than parsing exception messages. If you look at the docs for GetResponse you'll see documented the types of exceptions thrown. If you catch a WebException then this will allow you to find out the HTTP status without parsing strings manually e.g.:

    catch (System.Net.WebException ex)
    {
        var errorResponse = (System.Net.HttpWebResponse)ex.Response;
        if (errorResponse.StatusCode == System.Net.HttpStatusCode.Unauthorized)
        {
            //...
        }
    }