I am calling a WCF service using the follwing code:
string certPath = #"C:\certs\mycert.pem";
var uri = new Uri("http://Myserver/TestService.svc/MyMethod/parm1/parm2");
X509Certificate cert = X509Certificate.CreateFromCertFile(certPath);
var request = WebRequest.Create(uri) as HttpWebRequest;
request.Credentials = new NetworkCredential("user", "password");
request.PreAuthenticate = true;
request.ClientCertificates.Add(cert);
var response = request.GetResponse();
But getting
HTTP/1.1 400 Bad Request
error and
No Proxy-Authenticate Header is present
Can someone please point me in the right direction?
I suggest you try
string urlAddress = "http://www.google.com";
string userName = "user01";
string password = "puser01";
string proxyServer = "127.0.0.1";
int proxyPort = 8081;
HttpWebRequest request = (HttpWebRequest) WebRequest.Create(urlAddress);
if (userName != string.Empty)
{
request.Proxy = new WebProxy(proxyServer, proxyPort)
{
UseDefaultCredentials = false,
Credentials = new NetworkCredential(userName, password)
};
string basicAuthBase64 = Convert.ToBase64String(Encoding.GetEncoding("ISO-8859-1").GetBytes(string.Format("{0}:{1}", userName, password)));
request.Headers.Add("Proxy-Authorization", string.Format("Basic {0}", basicAuthBase64));
}
Reference:Sending Basic authentication over http
Related
I have a dot net implementation of the HttpWebRequest to send the HTTP post request to an API.
I am sending the HTTP request as:
HttpWebRequest hwr = null;
Uri uri = new Uri(booking ? Settings.BookingUrl: Settings.AvailabilityUrl);
hwr = HttpWebRequest.Create(uri) as HttpWebRequest;
hwr.Method = "POST";
hwr.Credentials = new NetworkCredential(Settings.Username, Settings.Password);
hwr.ContentType = "text/xml";
hwr.KeepAlive = false;
hwr.Timeout = 150000;
hwr.AllowAutoRedirect = true;
hwr.Accept = "text/xml";
hwr.PreAuthenticate = true;
hwr.ProtocolVersion = new Version(1, 1);
hwr.UserAgent = "";
hwr.AllowWriteStreamBuffering = true;
Stream streamOut = hwr.GetRequestStream();
I want to replicate this exact request in a postman. But, I am stuck in sending the NetworkCredential in a request header. Since Credentials are an object of System.Net.NetworkCredential type.
I am trying to use the API against our ALM 12.21 server, but always ends up with "401 Unauthorized". It seems that I get the auth cookie back correctly, but when I try to do something after that I am unauthorized.
I use this the get this to get auth cookie (seems to work):
HttpWebRequest myauthrequest = (HttpWebRequest)WebRequest.Create("https://server/qcbin/authentication-point/alm-authenticate");
string AuthenticationXML = #"<alm-authentication>
<user>username</user>
<password>password</password>
</alm-authentication>";
byte[] Requestbytes = Encoding.UTF8.GetBytes(AuthenticationXML);
myauthrequest.Method = "POST";
myauthrequest.ContentType = "application/xml";
myauthrequest.ContentLength = Requestbytes.Length;
myauthrequest.Accept = "application/xml";
Stream RequestStr = myauthrequest.GetRequestStream();
RequestStr.Write(Requestbytes, 0, Requestbytes.Length);
RequestStr.Close();
HttpWebResponse myauthres = (HttpWebResponse)myauthrequest.GetResponse();
var AuthenticationCookie = myauthres.Headers.Get("Set-Cookie");
AuthenticationCookie = AuthenticationCookie.Replace(";Path=/;HTTPOnly", "");
I am not sure if the .Replace is needed. Just read it somewhere. I get 401 both with or without it though, when trying to do subsequent requests.
Trying e.g. this after getting auth cookie:
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("https://server/qcbin/rest/domains/FS/projects/P3602_SLS_Project/defects/1");
req.Method = "GET";
req.ContentType = "application/xml";
req.Accept = "application/octet-stream";
req.Headers.Set(HttpRequestHeader.Cookie, AuthenticationCookie);
HttpWebResponse res = (HttpWebResponse)req.GetResponse();
Stream RStream2 = res.GetResponseStream();
XDocument doc = XDocument.Load(RStream2);
Which fails with 401.
Anyone have complete working code for the ALM 12.21 REST API?
You need two main cookies to get the ALM REST API works perfectly.
LWSSO_COOKIE_KEY
QCSession
almURL = "https://..com/qcbin/"
authEndPoint = almURL + "authentication-point/authenticate"
qcSessionEndPoint = almURL + "rest/site-session"
After you get successful response for authEndPoint you will get the LWSSO_COOKIE_KEY
Use that cookie in your next request to qcSessionEndPoint, it should give you QCSession cookie.
Use both LWSSO_COOKIE_KEY and QCSession cookies in your subsequent requests to get data from ALM.
I see that you are using octet-stream to get the defect response. When I checked the documentation, it can return one of the following types.
"application/xml"
"application/atom+xml"
"application/json"
Just in case, if you need to see some working implementation in python, here it is https://github.com/macroking/ALM-Integration/blob/master/ALM_Integration_Util.py
It may give you some idea.
Thank you #Barney. You sent me in the correct direction :-) For anyone interested, I managed it like this, e.g. for getting defect ID 473:
Logging on to create a CookieContainer and then use that to do the actual ALM data fetch:
private void button1_Click(object sender, EventArgs e)
{
string almURL = #"https://url/qcbin/";
string domain = "domain";
string project = "project";
CookieContainer cookieContainer = LoginAlm2(almURL, "username", "password", domain, project);
HttpWebRequest myWebRequest1 = (HttpWebRequest)WebRequest.Create(almURL + "/rest/domains/" + domain + "/projects/" + project + "/defects/473");
myWebRequest1.CookieContainer = cookieContainer;
myWebRequest1.Accept = "application/json";
WebResponse webResponse1 = myWebRequest1.GetResponse();
StreamReader reader = new StreamReader(webResponse1.GetResponseStream());
string res = reader.ReadToEnd();
}
public CookieContainer LoginAlm2(string server, string user, string password, string domain, string project)
{
//Creating the WebRequest with the URL and encoded authentication
string StrServerLogin = server + "/api/authentication/sign-in";
HttpWebRequest myWebRequest = (HttpWebRequest)WebRequest.Create(StrServerLogin);
myWebRequest.Headers[HttpRequestHeader.Authorization] = "Basic " + Base64Encode(user + ":" + password);
WebResponse webResponse = myWebRequest.GetResponse();
CookieContainer c = new CookieContainer();
Uri uri = new Uri(server);
string StrCookie = webResponse.Headers.ToString();
string StrCookie1 = StrCookie.Substring(StrCookie.IndexOf("LWSSO_COOKIE_KEY=") + 17);
StrCookie1 = StrCookie1.Substring(0, StrCookie1.IndexOf(";"));
c.Add(new Cookie("LWSSO_COOKIE_KEY", StrCookie1) { Domain = uri.Host });
//Then the QCSession cookie
string StrCookie2 = StrCookie.Substring(StrCookie.IndexOf("QCSession=") + 10);
StrCookie2 = StrCookie2.Substring(0, StrCookie2.IndexOf(";"));
c.Add(new Cookie("QCSession", StrCookie2) { Domain = uri.Host });
//Then the ALM_USER cookie
string StrCookie3 = StrCookie.Substring(StrCookie.IndexOf("ALM_USER=") + 9);
StrCookie3 = StrCookie3.Substring(0, StrCookie3.IndexOf(";"));
c.Add(new Cookie("ALM_USER", StrCookie3) { Domain = uri.Host });
//And finally the XSRF-TOKEN cookie
string StrCookie4 = StrCookie.Substring(StrCookie.IndexOf("XSRF-TOKEN=") + 12);
StrCookie4 = StrCookie4.Substring(0, StrCookie4.IndexOf(";"));
c.Add(new Cookie("XSRF-TOKEN", StrCookie4) { Domain = uri.Host });
return c;
}
Works like a charm :-)
public void Execute()
{
if(this.OnPreExecute!=null)
{
this.OnPreExecute();
}
HttpWebRequest httpWebRequest = WebRequest.CreateHttp(this.Url);
//httpWebRequest.Credentials = new NetworkCredential("userName", "password");
SetBasicAuthHeader(httpWebRequest, userName, password);
httpWebRequest.Method = "GET";
httpWebRequest.Accept = "application/json";
httpWebRequest.BeginGetResponse(OnGetResponseCompleted, httpWebRequest);
}
public void SetBasicAuthHeader(WebRequest httpWebRequest, String userName, String password)
{
string authInfo = userName + ":" + password;
authInfo = Convert.ToBase64String(Encoding.Unicode.GetBytes(authInfo));
httpWebRequest.Headers["Authorization"] = "Basic" + authInfo;
}
consider that i'm having username as admin and password as 3. How would i have to pass those values.
WebClient webClient = new WebClient();
webClient.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
var uri = new Uri(url, UriKind.Absolute);
StringBuilder postData = new StringBuilder();
postData.AppendFormat("{0}={1}", "userName", HttpUtility.UrlEncode(userName));
postData.AppendFormat("&{0}={1}", "password", HttpUtility.UrlEncode(password));
webClient.Headers[HttpRequestHeader.ContentLength] = postData.Length.ToString();
webClient.UploadStringAsync(uri, "POST", postData.ToString());
Thanks who responsed for this question for spending your precious time.
you just have to pass the username credentials method along with that API.Just like as follows,
i used Username as manoj and Password as 3
httpWebRequest.Credentials = new NetworkCredential("manoj", "3");
I have read several posts about login in to sites that needs email and password, but i couldn't find a solution about logging in to a specific site called geni.com. Is there a way?
CookieContainer cookie;
string user = "somemail#somehost.com";
string pass = "123456";
string formUrl = "http://www.geni.com/login/";
string formParams = String.Format("profile_username={0}&password={1}", "MYUSERNAME", "MYPASS");
string cookieHeader;
HttpWebRequest myWebRequest;
WebResponse myWebResponse;
String URL = textBox1.Text;
myWebRequest = (HttpWebRequest)WebRequest.Create("formUrl");
myWebRequest.ContentType = "application/x-www-form-urlencoded";
myWebRequest.Method = "POST";
string login = string.Format("go=&Fuser={0}&Fpass={1}", user, pass);
byte[] postbuf = Encoding.ASCII.GetBytes(login);
myWebResponse = myWebRequest.GetResponse(); //Returns a response from an Internet resource
cookieHeader = myWebResponse.Headers["Set-cookie"];
cookie = myWebRequest.CookieContainer = new CookieContainer();
myWebRequest.CookieContainer = cookie;
Stream streamResponse = myWebResponse.GetResponseStream();
StreamReader sreader = new StreamReader(streamResponse);
Rstring = sreader.ReadToEnd();
I am a bit confused, can anybody help me??
Here's a link to their API documentation. To login you'll want to call their API like this:
https://www.geni.com/platform/oauth/request_token?client_id=YOUR_APP_ID&client_secret=YOUR_APP_SECRET&grant_type=client_credentials
I'm trying to read files from a SharePoint document library using HttpWebRequest. In order to do that I have to pass some credentials. I'm using the below request:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "GET";
request.ContentType = "application/msexcel";
request.UserAgent = "Mozilla/4.0+(compatible;+MSIE+5.01;+Windows+NT+5.0";
request.Credentials = new NetworkCredential(UserName, PassWord);
Is this the correct way to pass credentials?
You could also use:
request.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
If you need to run request as the current user from desktop application use CredentialCache.DefaultCredentials (see on MSDN).
Your code looks fine if you need to run a request from server side code or under a different user.
Please note that you should be careful when storing passwords - consider using the SecureString version of the constructor.
If you need to set the credentials on the fly, have a look at this source:
http://spc3.codeplex.com/SourceControl/changeset/view/57957#1015709
private ICredentials BuildCredentials(string siteurl, string username, string password, string authtype) {
NetworkCredential cred;
if (username.Contains(#"\")) {
string domain = username.Substring(0, username.IndexOf(#"\"));
username = username.Substring(username.IndexOf(#"\") + 1);
cred = new System.Net.NetworkCredential(username, password, domain);
} else {
cred = new System.Net.NetworkCredential(username, password);
}
CredentialCache cache = new CredentialCache();
if (authtype.Contains(":")) {
authtype = authtype.Substring(authtype.IndexOf(":") + 1); //remove the TMG: prefix
}
cache.Add(new Uri(siteurl), authtype, cred);
return cache;
}