I have a console application to download a file from a SharePoint site. The sharepoint site uses claims based authentication.
This code throws a 403 Forbidden exception. The specified Network credential has full access to the site, and is able to download the same file from a browser.
WebClient webClient = new WebClient();
webClient.Credentials = new NetworkCredential(username,Password,domain);
byte[] fileData = webClient.DownloadData(urlOfAFile);
FileStream file = File.Create(localPath);
file.Write(fileData, 0, fileData.Length);
Any idea how to fix this?
Maybe a bit late, but adding the right request header before making the request solves the problem:
webClient.Headers.Add("X-FORMS_BASED_AUTH_ACCEPTED", "f");
I also encounter this issue, and below is my research:
{
ClientContext m_clientContext = new ClientContext(strSiteUrl);
m_clientContext.ExecutingWebRequest += new EventHandler<WebRequestEventArgs>(ctx_MixedAuthRequest);
m_clientContext.AuthenticationMode = ClientAuthenticationMode.Default;
m_clientContext.Credentials = new NetworkCredential(uname, pwd);
Web m_currentWeb = m_clientContext.Web;
m_clientContext.Load(m_currentWeb);
m_clientContext.ExecuteQuery();
}
private void ctx_MixedAuthRequest(object sender, WebRequestEventArgs e)
{
try
{
//Add the header that tells SharePoint to use Windows authentication.
e.WebRequestExecutor.RequestHeaders.Add(
"X-FORMS_BASED_AUTH_ACCEPTED", "f");
}
catch (Exception ex)
{
MessageBox.Show("Error setting authentication header: " + ex.Message);
}
}
here is the article: https://msdn.microsoft.com/en-us/library/office/hh124553(v=office.14).aspx
Related
I'm playing with OneDrive SDK 1.1.15.0:
try
{
AppConfig appConfig = new AppConfig
{
MicrosoftAccountAppId = oneDriveClientID, //something like 00000000123456AB
MicrosoftAccountClientSecret = oneDriveClientSecret, //something like 3vx[...]1sJ
MicrosoftAccountReturnUrl = "https://localhost/return",
MicrosoftAccountScopes = new string[] { "wl.signin", "wl.offline_access", "onedrive.readonly" }
};
OneDriveClient oneDriveClient = new OneDriveClient(appConfig);
AccountSession accountSession = await oneDriveClient.AuthenticateAsync();
//more code
await oneDriveClient.SignOutAsync();
}
catch (Exception ex)
{
throw ex;
}
My problem is in line:
AccountSession accountSession = await oneDriveClient.AuthenticateAsync();
that throws the following exception:
Microsoft.OneDrive.Sdk.OneDriveException, AuthenticationFailure: Failed to retrieve a valid authentication token for the user.
Any ideas?
Thank you in advance!
UPDATE
After reading comment from ginach (thank you!), I update my code. Some arguments to underline:
I want to access OneDrive from an Azure worker Role, so no authentication windows or something like that.
I upload the Microsoft.OneDrive SDK to 1.1.20 version.
I already registered my application to the OneDrive dev portal.
My actual code is:
try
{
MicrosoftAccountServiceInfo serviceInfo = new MicrosoftAccountServiceInfo();
serviceInfo.AppId = oneDriveClientID; //something like: 00000000ABCDEFGH
serviceInfo.ClientSecret = oneDriveClientSecret; //something like: 3vx[...]1sJ
serviceInfo.ReturnUrl = oneDriveReturnUrl; //something like: https://localhost/return
serviceInfo.Scopes = oneDriveAccountScopes; //something like new string[] { "wl.signin", "wl.offline_access", "onedrive.readonly" }
MicrosoftAccountAuthenticationProvider authenticationProvider = new MicrosoftAccountAuthenticationProvider(serviceInfo);
OneDriveClient oneDriveClient = await OneDriveClient.GetAuthenticatedMicrosoftAccountClient(oneDriveClientID, oneDriveReturnUrl, oneDriveAccountScopes, authenticationProvider);
//more code
await oneDriveClient.SignOutAsync();
}
catch (OneDriveException odex)
{
throw odex;
}
catch (Exception ex)
{
throw ex;
}
I obtain again and again (in OneDriveClient.GetAuthenticatedMicrosoftAccountClient method) a OneDriveException stating (Error property): AuthenticationFailure - Failed to retrieve a valid authentication token for the user.
Any suggestion?
Thank you.
UPDATE 2
OK, I'm trying a new approach. Using RestSharp I try to login to OneDrive with that code:
string clientId = "00[...]00";
string scopes = "wl.signin, wl.offline_access, onedrive.readonly";
string responseType = "code";
string redirectUri = "https://login.live.com/oauth20_desktop.srf";
RestClient client = new RestClient("https://login.live.com");
RestRequest request = new RestRequest();
request.Method = Method.GET;
request.Resource = "oauth20_authorize.srf";
request.AddQueryParameter("client_id", clientId);
request.AddQueryParameter("scope", scopes);
request.AddQueryParameter("response_type", responseType);
request.AddQueryParameter("redirect_uri", redirectUri);
IRestResponse response = client.Execute(request);
string content = response.Content;
I check the request with Fiddler and what I'm sending is:
https://login.live.com/oauth20_authorize.srf?client_id=00[...]00&scope=wl.signin%20wl.offline_access%20onedrive.readonly&response_type=code&redirect_uri=https%3A%2F%2Flogin.live.com%2Foauth20_desktop.srf
But OneDrive server answers my with:
Microsoft account requires JavaScript to sign in. This web browser either does not support JavaScript, or scripts are being blocked. To find out whether your browser supports JavaScript, or to allow scripts, see the browser's online help.
So I try the request in a browser and OneDrive server redirects me to the authorization page:
Now the question is: is there any workaround to skip the manual authorization?
Thank you,
Attilio
The client requires an authentication provider to be able to retrieve authentication tokens. There are a few ways to do this depending on your current platform.
Create your own IAuthenticationProvider implementation. The authentication provider is responsible for setting the Authentication header on requests. Here's how you would create a client instance with a custom authentication provider:
var client = new OneDriveClient(appConfig, serviceInfoProvider: new
ServiceInfoProvider(new CustomAuthenticationProvider()));
Use one of the various default authentication implementations. Take a look at the SDK authentication documentation for the available options and examples.
If you have a refresh token and only want to do the silent authentication flow you can use OneDriveClient.GetSilentlyAuthenticatedMicrosoftAccountClient. Here's an example:
var client = await OneDriveClient.GetSilentlyAuthenticatedMicrosoftAccountClient(clientId, returnUrl, scopes, refreshToken);
I am developing a C# application which should connect to the user`s Dropbox using the DropNet C# Api.
I connect my application like this:
UserLogin login=client.GetToken();
client.UserLogin = login;
String url = client.BuildAuthorizeUrl();
ConnectForm authorizer = new ConnectForm(url);
authorizer.ShowDialog(this);
try
{
UserLogin accessToken = client.GetAccessToken();
this.toolStripStatusLabel1.Text = "connected";
}
catch (DropboxException exc)
{
client = new DropNetClient("API KEY", "API SECRET");
this.toolStripStatusLabel1.Text = "error";
}
My toolStripStatusLabel displays "connected" after this code part and after I try to upload a file (or to create a folder) like this
client.UploadFile("/", "test.txt", File.ReadAllBytes("C:/Users/Me/Desktop/test.txt"));
this.toolStripStatusLabel1.Text = "File uploaded";
it displays "File uploaded" but there are still no files in my Dropbox.. My Dropbox Api Error Log shows some 403 errors but without any further information.
Does anybody know whats wrong here?
I've found the solution.
When you register your application for "App-Folder" permission only you have to set client.useSandbox=true; directly after initalizing.
I am trying to upload a file into a SharePoint library by using WebClient and the WebDav .NET library from independentsoft. First I had the problem that the Upload-method returned an exception with HTTP 403. Than I realized that I have to go through a proxy. Now it's returning me HTTP 405. I also used the ClientOM but wasn't able to configure the proxy settings there so I still get a HTTP 403 there.
The code i am using for WebClient and WebDav .NET is the following:
WebClient:
webClient.UseDefaultCredentials = true;
string[] bypassList = { "localhost" };
webClient.Proxy = new WebProxy("proxy", true, bypassList, new NetworkCredential("user", "password"));
try
{
byte[] response = webClient.UploadFile("http://sharepoint/testBlankSite/testLibrary/TestUpload.txt", "PUT", #"...\Desktop\TestUpload.txt");
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
WebDav .NET
NetworkCredential credential = new NetworkCredential("user", "password");
string[] bypassList = { "localhost" };
WebProxy proxy = new WebProxy("proxy", true, bypassList, new NetworkCredential("user", "password"));
WebdavSession session = new WebdavSession(credential, proxy);
Resource resource = new Resource(session);
try
{
resource.Upload("http://sharepoint/testBlankSite/testLibrary/TestUpload.txt", #"...\Desktop\TestUpload.txt");
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
Has anyone an idea why this isn't working and how I can solve this?
This is a pretty common problem with SharePoint. Check out these links:
SharePoint, WebDAV, and a Case of the 405 Status Codes
SharePoint 2013 - Disable WebDAV use on SharePoint
As #GavinB and #Jeremy mentioned, the alternative is the client-side object model, i.e. Microsoft.SharePoint.Client. This library is just a wrapper and it performs HTTP requests that are similar to the ones you are trying.
Our company web site is hosted in ORCSWEB. Some kind of policy and rule has been set on ORCS end. When people try to access our company ftp with wrong credential 3 times and fail then our ftp will be locked. We often upload file through ftp by programatically but some times found ftp lock. So I talk to orcsweb tech support: they said we are try to access our ftp anonymously by code. So the code which I use to access ftp as follows. So please go through my code and tell me what is wrong in my code which causes anonymous access because I try to access with the right credentials.
public static string IsFtpAccessible(string FTPAddress)
{
string strError = "";
FtpWebRequest ftp = (FtpWebRequest)FtpWebRequest.Create(FTPAddress);
FtpWebResponse res;
StreamReader reader;
ftp.Credentials = new NetworkCredential("myuserid", "00000password");
ftp.KeepAlive = false;
ftp.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
ftp.UsePassive = true;
ftp.UseBinary = true;
ftp.KeepAlive = false;
try
{
using (res = (FtpWebResponse)ftp.GetResponse())
{
reader = new StreamReader(res.GetResponseStream());
}
}
catch(Exception ex)
{
strError = "ERROR:" + ex.Message.ToString();
}
return strError;
}
So tell me what is missing in my code that causes anonymous access.
Anonymous access must be allowed on the server, which I'm assuming is not allowed based on your description. Typically, Anonymous access credentials are supplied like this:
request.Credentials = new NetworkCredential ("anonymous","janeDoe#contoso.com");
The main point is that an email address is the password.
If you only sometimes find that the code based FTP is locked, then this is not where your problem lies.
Any idea of how to upload a file to Google site from c#?
I am trying to upload but getting a 403 error. However, I am using the same credentials to connect to the site and get the list of attachments and pages present on the site.
Any help would be greatly appreciated!!
They most likely have an anti-CSRF scheme that stores temporal identifiers in the page and/or cookies, this is specifically to hinder bots.
You are most likely submitting a request without the proper CSRF tokens and get rejected. I would recommend analyzing how they handle CSRF, after this point it will most likely boil down to making a WebRequest to the page and so you can get any cookies they get back, along with having the form so you can scrape out any hidden fields that are relevant. Then move those over to your post request that you're attempting to the send the file to.
I figured out the problem and resolved it. Below is the complete function:
public bool UploadAttachment()
{
try
{
//AsyncSendData data = new AsyncSendData();
string parentUrl = Cabinets["Cabinet1"].ToString();
string parentID = parentUrl.Split('/')[7];
AtomEntry entry = new AtomEntry();
entry.Title.Text = "abc.jpg";
AtomCategory cat = new AtomCategory();
cat.Term = ATTACHMENT_TERM;
cat.Label = "attachment";
cat.Scheme = KIND_SCHEME;
entry.Categories.Add(cat);
AtomLink link = new AtomLink();
link.Rel = PARENT_REL;
link.HRef = parentUrl;
entry.Links.Add(link);
AtomContent content = new AtomContent();
FileInfo info = new FileInfo("C:\\Bluehills.txt");
FileStream stream = info.Open(FileMode.Open,FileAccess.ReadWrite,FileShare.ReadWrite);
this.setUserCredentials(userName, password);
Uri postUri = new Uri(makeFeedUri("content"));
entry.Source = new AtomSource();
//this.EntrySend(postUri, entry, GDataRequestType.Insert);
// Send the request and receive the response:
AtomEntry insertedEntry = this.Insert(postUri, stream, (string)DocumentTypes["TXT"], "bluehills");
return true;
}
catch (Exception ex)
{
return false;
}
}