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;
}
Related
I'm triggering an external web page outside of sharepoint which needs to read lists using the sharepoint web api.
HttpWebRequest endpointRequest = (HttpWebRequest)HttpWebRequest.Create(sharepointUrl.ToString() + "/_api/web/lists");
endpointRequest.Method = "GET";
endpointRequest.Accept = "application/json;odata=verbose";
//endpointRequest.Headers.Add("Authorization", "Bearer " + accessToken);
HttpWebResponse endpointResponse = (HttpWebResponse)endpointRequest.GetResponse();
I can access the API using chrome if I'm logged in but I suspect I need the access token line.. but can't seem to find a way to populate it.
Currently it returns:
No connection could be made because the target machine actively refused it...
You need to set credential of HttpWebRequest.
Here you go:
HttpWebRequest endpointRequest = (HttpWebRequest)HttpWebRequest.Create(sharepointUrl.ToString() + "/_api/web/lists");
string password = "XXXXX";
string userName = "XXXX";
SecureString secureString = new SecureString();
foreach (char c in password.ToCharArray())
{
secureString.AppendChar(c);
}
endpointRequest.Credentials = new SharePointOnlineCredentials(userName, secureString);
//.........
If you are using SharePoint online, it can work with my answer above because i have tested.
If you are using SharePoint 2013/2010/2016, the code will be as below.
HttpWebRequest endpointRequest = (HttpWebRequest)HttpWebRequest.Create(sharepointUrl.ToString() + "/_api/web/lists");
string password = "XXXXX";
string userName = "XXXX";
string domain = "XXX"
endpointRequest.Credentials = new NetworkCredential(userName, password, domain);
//.........
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
My code is like this
Doc doc = new Doc();
string url = HttpContext.Current.Request.Url.AbsoluteUri;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
// required for HttpWebResponse.Cookies
request.CookieContainer = new CookieContainer();
request.Credentials = new NetworkCredential("username", "password");
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
if (response.Cookies.Count>0) { // includes ASP.NET_SessionId
bool needsCookie2 = false;
StringBuilder builder = new StringBuilder("Cookie: ");
for(int i = 0; i<response.Cookies.Count; ++i) {
Cookie cookie = response.Cookies[i];
if(!needsCookie2 && cookie.Version!=1)
needsCookie2 = true;
if(i>0)
builder.Append("; ");
builder.Append(cookie.ToString());
}
builder.Append(!needsCookie2? "\r\n": "\r\nCookie2: $Version=1\r\n");
doc.HtmlOptions.HttpAdditionalHeaders = builder.ToString();
}
doc.HtmlOptions.NoCookie = true;
doc.HtmlOptions.HostWebBrowser = false;
// cookieless Forms Authentication adds authentication ticket to the URL
int id = doc.AddImageUrl(response.ResponseUri.AbsoluteUri);
doc.Save(HttpContext.Current.Server.MapPath("~/media/pdf/1212.pdf"));
doc.Clear();
I am using simple form authentication in my website and I need to authenticate this webRequest in order to print a pdf through abcPDF, as my login details are stored in cookie i am trying to get it from there and add to my request. I assume the error is in line request.Credentials = new NetworkCredential("username", "password");
You say the website is using forms authentication, but your request is using basic authentication credentials:
request.Credentials = new NetworkCredential("username", "password");
You'll need to either switch the website to basic authentication, or perform a POST request against your login page to get the session cookie/token to use in subsequent requests.
Here is the sample code for PHP Webservice client that works:
$options = array();
$options['trace'] = 1;
$options['login'] = 'username';
$options['password'] = 'password';
$client = new SoapClient("http://wsurl.com/pt/wsdl", $options);
I would like to access this webservice using c# but having a hard time doing the authentication. Do I need to explicitly set the soap headers or there is a built in way to send credentials in .NET
There are two ways to do this because servers handle authentication differently. First you could use something like this:
var req = WebRequest.Create(<your url>);
NetworkCredential creds = new NetworkCredential(<username>, <password>);
req.Credentials = creds;
var rep = req.GetResponse();
However if you need an actual Authroization header you will want to use this code
public void SetBasicAuthHeader(WebRequest req, String userName, String userPassword)
{
string authInfo = userName + ":" + userPassword;
authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));
req.Headers["Authorization"] = "Basic " + authInfo;
}
And then your request code becomes
var req = WebRequest.Create(<your url>);
SetBasicAuthHeader(req, username, password);
rep = req.GetResponse();
Let me know if you have any questions.
If you add a service reference in your C# project, you can just call your service like this:
var proxy = new YourServiceClient();
proxy.ClientCredentials.UserName.UserName = "username";
proxy.ClientCredentials.UserName.Password = "password";
More information can be found here: http://msdn.microsoft.com/en-us/library/ms733775.aspx.
I am trying to create a application that will consume RSS data using .NET Framework. The RSS site requires User name and Password to start with.
and Am running this application from within my work place which requires NTLM authentication to connect to internet.
Following is the code that i am trying to use
NetworkCredential nc = new NetworkCredential("SITEUSERNAME", "SITEPASSWORD");
CredentialCache cache = new CredentialCache();
cache.Add(new Uri(RSSFeed), "Basic", nc);
cache.Add(new Uri(RSSFeed), "Ntlm", new NetworkCredential("USERNAME","PASSWORD","DOAMIN"));
HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(RSSFeed);
myHttpWebRequest.Proxy.Credentials = cache;
HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();
i get 407 error and if i simply use CredentialCache.DefaultNetworkCredentials i get 401 error.
solved the issue by using following code
string credentials = Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes("UserName" + ":" + "Password"));
StringBuilder outputData = new StringBuilder();
HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(RSSFeed);
myHttpWebRequest.Proxy.Credentials = CredentialCache.DefaultNetworkCredentials;
myHttpWebRequest.Headers.Add("Authorization", "Basic " + credentials);
HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();
Stream streamResponse = myHttpWebResponse.GetResponseStream();
If this code works, then your original code above was wrong. You should set
request.Proxy.Credentials = CredentialCache.DefaultNetworkCredentials;
and
NetworkCredential nc = new NetworkCredential("SITEUSERNAME", "SITEPASSWORD");
CredentialCache cache = new CredentialCache();
cache.Add(new Uri(RSSFeed), "Basic", nc);
cache.Add(new Uri(RSSFeed), "Ntlm", new NetworkCredential("USERNAME","PASSWORD","DOAMIN"));
HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(RSSFeed);
myHttpWebRequest.Credentials = cache;
In other words, you had exchanged credentials for the proxy and the destination server.