I am trying to connect SharePoint 2013 Online website using a Context Token from a console executable. However, it is giving me error The remote server returned an error: (403) Forbidden.
Here is the code snippet:
string spurl = ConfigurationManager.AppSettings["Sharepoint_URL"].ToString();
using (ClientContext context = new ClientContext(spurl))
{
context.Credentials = new NetworkCredential("username", "password", "domain");
context.ExecuteQuery();
Web web = context.Web;
context.Load(web);
context.ExecuteQuery();
Console.WriteLine(context.Web.Title);
}
Console.ReadKey();
How can I make a connection with SharePoint Online? Does it only support claims-based authentication?
I think the method with which you are trying to authenticate is outdated. The SharePoint 2013 Client Object Model now has a class called SharePointOnlineCredentials which abstracts away all the tedious cookie container stuff. E.g.:
using (ClientContext clientContext = new ClientContext("https://yoursite.sharepoint.com/"))
{
SecureString passWord = new SecureString();
clientContext.Credentials = new SharePointOnlineCredentials("loginname#yoursite.onmicrosoft.com", passWord);
Web web = clientContext.Web;
clientContext.Load(web);
clientContext.ExecuteQuery();
Console.WriteLine(web.Title);
Console.ReadLine();
}
Please refer to this link for more information: https://sharepoint.stackexchange.com/questions/83985/access-the-sharepoint-online-webservice-from-a-console-application
Related
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
using (ClientContext context = new ClientContext("https://abc.sharepoint.com/sites/app"))
{
SecureString passWord = new SecureString();
foreach (char c in "password".ToCharArray()) passWord.AppendChar(c);
context.Credentials = new SharePointOnlineCredentials("Admin#sample.onmicrosoft.com", passWord);
context.Load(context.Web, x => x.Url);
context.ExecuteQuery();
}
This is my old code block and this is working Azure "security default" disabled environment.
When I run this in an environment with Azure security default enabled, an error appears. I need to use a code block connected to the PNP framework to execute this code. Any recommendations?
You can use GetACSAppOnlyContext to access SharePoint online. Please refer to following code
string siteUrl = "https://xxx.sharepoint.com/sites/demo";
string clientId = "*******-****-4818-a928-f14658a9fe90";
string clientSecret = "*****************";
using (var clientContext = new AuthenticationManager().GetACSAppOnlyContext(siteUrl, clientId, clientSecret))
{
clientContext.Load(clientContext.Web, p => p.Title);
clientContext.ExecuteQuery();
Console.WriteLine(clientContext.Web.Title);
};
My project is set up to use azure ad as login(from the dotnet core template). I have successfully managed to log in.
However, i want to use the same logged in user to retrive data from sharepoint rest api.
I have the following method:
public async Task<FileResults> Test()
{
var siteUrl = "https://xxxxx.sharepoint.com";
var username = "xx#xx.no";
var password = "xxxxxx";
var securePassword = new SecureString();
password.ToCharArray().ToList().ForEach(c => securePassword.AppendChar(c));
var credentials = new SharePointOnlineCredentials(username, securePassword);
var handler = new HttpClientHandler();
handler.Credentials = credentials;
var uri = new Uri(siteUrl);
handler.CookieContainer.SetCookies(uri, credentials.GetAuthenticationCookie(uri));
var json = string.Empty;
using (var client = new HttpClient(handler))
{
client.DefaultRequestHeaders.Clear();
client.DefaultRequestHeaders.Add("Accept", "application/json;odata=verbose");
var response = await client.GetAsync(siteUrl + "/_api/Web/GetFolderByServerRelativeUrl('/Delte%20dokumenter/Test')/Files");
json = await response.Content.ReadAsStringAsync();
var result = Newtonsoft.Json.JsonConvert.DeserializeObject<Rootobject>(json);
var files = result.FileResults;
return files;
}
}
This is working fine and im getting documents from sharepoint.
But, this is when using hardcoded credentials. How do i use the credentials of the logged in user via azure AD? Do i retrive the accesstoken?
To use the Azure AD Authentication you need to have one of the Authentication flows.
Note: Username/Password flow is not recommended.
After that you will be getting the tokens according to the scopes that are specified and you need to hit the Microsoft Graph Api, internally you need to hit the SharePoint API endpoints according to your requirement.
You can start exploring with this sample
I'm creating an MVC app that requires me to nab the group users from a Sharepoint site. I'm getting a 401 error when I publish and run it via IIS (localhost). When I run it through the debugger though, everything works as intended.
I'm assuming it's a permissions error based on the context. Is there a way to run the app normally using my current NTLM credentials programmatically (instead of what seems like the IIS account/user)?
Code
(I'm on mobile right now, so I'm sorry if anything looks wonky...)
// Constructor
clientContext = new ClientContext("http://sharepointsite");
clientContext.Credentials = CredentialCache.DefaultNetworkCredentials;
//clientContext.Credentials = new NetworkCredentials("username", "password", "domain"); <- this works just fine if I hard code my current credentials
// Calling method
UserCollection users = GetUsersCollection();
clientContext.Load(users);
try {
clientContext.ExecuteQuery(); // 401 error here
return true;
}
catch {
return false;
}
You can specify the credentials you connect to SharePoint with CSOM it would look something like this:
clientContext.Credentials = new NetworkCredential("Username", "Password", "Domain");
You can do MVC impersonation like this:
string currentUser = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
System.Security.Principal.WindowsImpersonationContext impersonationContext;
impersonationContext =
((System.Security.Principal.WindowsIdentity)User.Identity).Impersonate();
currentUser += "Impersonate:" + System.Security.Principal.WindowsIdentity.GetCurrent().Name;
impersonationContext.Undo();
ViewBag.U = currentUser;
return View();
I found that example in this thread:
http://forums.asp.net/t/1961337.aspx?Asp+Net+MVC+5+how+to+impersonate+user+on+IIS
I have a need to retrieve a list of subwebs for a specified user using the client object model. The challenge is that this is being called from a C# web service that is running under the identity of a SharePoint user with access to all the subwebs. Is there a way to filter this list to only return those that belong to a specified user? I only have the username and do not have the password for this account so direct impersonation using NetworkCredential is not going to work.
Pseudo code below:
var clientContext = new ClientContext(siteUrl);
var site = clientContext.Web;
var user = site.CurrentUser;
clientContext.Load(site);
clientContext.Load(user);
clientContext.ExecuteQuery();
var webCollection = site.GetSubwebsForCurrentUser(null);
clientContext.Load(webCollection);
clientContext.ExecuteQuery();
foreach (var web in webCollection)
{
// should I check permissions here?
}
I can get a remote console app talking to a NTLM Sharepoint site with ClientContext and I can it talking to a remote Kerberos Sharepoint box with HttpWebRequest.GetResponse();
But I cannot get it talking to the Kerberos Sharepoint box with CientContext. Any additional pointers would be gratefully recieved.
string siteURL = "http://my.remote.sharepoint";
ClientContext ctx = new ClientContext(siteURL);
CredentialCache cc = new CredentialCache();
cc.Add(new Uri(siteURL), "Kerberos", CredentialCache.DefaultNetworkCredentials);
ctx.AuthenticationMode = ClientAuthenticationMode.Default;
ctx.Credentials =cc;
/////////////////////////////////////////////////////////////////////////////////
// This code confirms that I can access "my.remote.sharepoint" with KRB
// HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(siteURL);
// myHttpWebRequest.Credentials = cc;
// myHttpWebRequest.UseDefaultCredentials = true;
// HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
/////////////////////////////////////////////////////////////////////////////////
Web remoteWeb = ctx.Web;
ctx.Load(remoteWeb);
ctx.ExecuteQuery();
//401 unauthorised returned from here
Wireshark suggests that it returns the initial 401 & then gives up! Any ideas
Please check if a SPN is registered for that host and a reverse DNS entry exists.