Query sharepoint list anonymously - sharepoint

Hi do i access a sharepoint list with anonymous authentication? I am trying to read a sharepoint list with javascript and it only works if I have logged in with an admin user but if I have not logged in I get the "Access denied. You do not have permission to perform this action or access this resource." error message.
My code is as below
var siteUrl = "http://site/subsite";
var clientContext = new SP.ClientContext(siteUrl);
var clientContext = new SP.ClientContext.get_current;
var oList = clientContext.get_web().get_lists().getByTitle('Subscriptions');
var camlQuery = new SP.CamlQuery();
camlQuery.set_viewXml('<view><Query><Where><Contains><FieldRef Name=\'EMail\'/><Value Type=\'Text\'>searchText</Value></Contains></Where></Query></view>');
this.collListItem = oList.getItems(camlQuery);
clientContext.load(collListItem);
clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
I believe the site is set to allow anonymous authentication. The subsite also. The list also allows anonymous user to view items. I am using sharepoint 2013

By default the site is not set to allow anonymous authentication. You have to allow anonymous authentication explicitly from IIS.
Please check if you are able to browse that site with the anonymous user.

By default getitems method of list is blocked on SharePoint. You will have to open it using power shell script.
https://sharepointinaction.wordpress.com/tag/the-method-getitems-of-the-type-list-is-blocked-by-the-administrator-on-the-server/

Related

'Access Denied' accessing SharePoint Online Site Collection with App Permission

I have created an App Principal in SharePoint Online using the Site Collections /AppRegNew.aspx page and then used page /appInv.aspx to grant that App Principal FullControl of the site collection using the following permission XML:
<AppPermissionRequests>
<AppPermissionRequest Scope="http://sharepoint/content/sitecollection" Right="FullControl"/>
</AppPermissionRequests>
However, when I try to access a list in that site collection using CSOM and c# (using TokenHelper.cs), I get error:
'Access denied. You do not have permission to perform this action or access this resource.'
I have another App Principal which I had granted Tenant Admin permission for testing - if I use the ClientID and ClientSecret associated with that App Principal, my code runs properly (I am just reading a few list items for testing)
Am I doing something wrong with the AppPermissionRequests XML? is there some other step I am missing? I could use the Tenant Admin App Principal, but I want to do this the 'right' way - and from my research, it looks like it should be working with the SiteCollection FullControl permission.
Example code I am using to attempt access:
Uri siteUri = new Uri("https://MyCompany.sharepoint.com/sites/johntest");
string realm = TokenHelper.GetRealmFromTargetUrl(siteUri);
string accessToken = TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, siteUri.Authority, realm).AccessToken;
using (ClientContext context = TokenHelper.GetClientContextWithAccessToken(siteUri.ToString(), accessToken))
{
Web thisWeb = context.Web;
context.Load(thisWeb);
context.ExecuteQuery();
List roomsList = context.Web.Lists.GetByTitle("Rooms");
context.Load(roomsList);
context.ExecuteQuery();
Console.WriteLine("List retrieved");
CamlQuery camlQuery = new CamlQuery();
camlQuery.ViewXml = "<View><Query><Where><Eq><FieldRef Name='Title'/><Value Type='Text'>SomeValue</Value></Eq></Where></Query></View>";
ListItemCollection listItems = roomsList.GetItems(camlQuery);
context.Load(listItems);
context.ExecuteQuery();
Console.WriteLine("Query succeeded");
}
Because you are accessing the resource with an application login, by using TokenHelper.GetAppOnlyAccessToken, you must add the AllowAppOnlyPolicy="true" attribute to the AppPermissionRequest.
Friendly reminder, the client id and client secret should be treated like a user name and password when the AllowAppOnlyPolicy attribute is true, especially if the application is highly privileged, such as tenant admin or full control over a site collection. In any case, the client secret should be guarded, but it has to be combined with an authenticated user, if AllowAppOnlyPolicy is false.

Why I don't need to authenticate the user before i can execute query in CSOM example

I am going thru the examples here which shows how to perform basic operations with the SharePoint 2013 .NET Framework client object model (CSOM).
https://msdn.microsoft.com/en-us/library/office/fp179912.aspx
My question is why I don't need to authenticate the user before i can execute query in CSOM
For example
// Starting with ClientContext, the constructor requires a URL to the
// server running SharePoint.
ClientContext context = new ClientContext("http://SiteUrl");
// The SharePoint web at the URL.
Web web = context.Web;
// We want to retrieve the web's properties.
context.Load(web);
// Execute the query to the server.
context.ExecuteQuery();
// Now, the web's properties are available and we could display
// web properties, such as title.
label1.Text = web.Title;
You dont need to do this cause it will use the current logged in user. Otherwise you have to impersonate the user first.
ClientContext context = new ClientContext("http://server/");
context.Credentials = new NetworkCredential("user", "password", "domain");
// Some Cording
context.ExecuteQuery();

DTD is prohibited in this XML document when using CSOM with SharePoint Online

This code snippet
string strUserName="abc";
string strPassword="123";
SecureString ssPwd = new SecureString();
strPassword.ToList().ForEach(ssPwd.AppendChar);
ClientContext context = new ClientContext(siteurl);
SharePointOnlineCredentials credentials = new SharePointOnlineCredentials(strUserName, ssPwd);
context.Credentials = credentials;
// The SharePoint web at the URL.
Web web = context.Web;
// We want to retrieve the web's properties.
context.Load(web);
// Execute the query to the server.
context.ExecuteQuery();
Creates the following error message trying to connect to SharePoint Online:
For security reasons DTD is prohibited in this XML document. To enable DTD processing set the DtdProcessing property on XmlReaderSettings to Parse and pass the settings into XmlReader.Create method.
The same thing happens using the SharePoint Client Browser downloaded from CodePlex (https://spcb.codeplex.com).
What's wrong? What can I do?

Sharepoint Online adding a list item using client object model

I have used Javascript and sharepoint client object model to add a list item to a list. I am working with a sharepoint 2013 online public site. I have a content editor with the following javascript code.
var clientContext = new SP.ClientContext.get_current();
var web = clientContext.get_web();
var list = web.get_lists().getByTitle('Subscriptions');
var email = document.getElementById('email').value;
// Create a new list item
var itemCreateInfo = new SP.ListItemCreationInformation();
var listItem = list.addItem(itemCreateInfo);
listItem.set_item('Title',email );
listItem.update();
This code works fine for the user who has permission. it will add a element to the subscription list. But it fails when we use this for a Anonymous user. After searching I found that that there is a tool : http://anonymous365.codeplex.com/.
But it did not work from the code though i gave anonymous access to the list.
Please suggest me a way to overcome this.
Thanks,
Access to SharePoint Online requires an authenticated session of some variety. The only site that is available for public (anonymous) access is the pre-provisioned "public site" that is available with certain subscriptions which is meant to host a standard corporate website. A sample project that shows how to support claims authentication with SPO can be found here: http://code.msdn.microsoft.com/office/Remote-Authentication-in-b7b6f43c/

impersonate as different user inside the webpart code

I use the sharepoint lists as a database.
I want to somehow impersonate as different user inside the webpart code
and than as this user I will have both write and edit permission to the list.
My goal is to be able to have full premission only through the webpart code.
I am using MOSS 2007.
SPSecurity.RunWithElevatedPrivilieges() will execute your code as the system account, i.e. the account under which the application pool runs, which might or might not be what you want to do. For example, if you have a workflow attached to the list which is supposed to trigger when new items are added to the list, it will not fire if you insert a new list item under the credentials of the system account (this was a security fix introduced in SharePoint 2007 SP 1). In that case you will have to perform the insert operation under a different account that has the correct permissions on the list.
You can get the UserToken for any user using the following code:
SPUserToken userToken = null;
SPSecurity.RunWithElevatedPrivileges(() =>
{
using (SPSite site = new SPSite(SPContext.Current.Site.ID))
{
using (SPWeb web = site.OpenWeb(SPContext.Current.Web.ID))
{
userToken = web.AllUsers["domain\\username"].UserToken;
}
}
});
Replace the "domain\username" with the correct windows account name. Then you can pass this user token to one of the overloads of the SPSite object constructor to execute the code under this user's credentials like so:
using (SPSite site = new SPSite(SPContext.Current.Site.ID, userToken))
{
using (SPWeb web = site.OpenWeb(SPContext.Current.Web.ID))
{
// This code will execute under the credentials of the userToken user
}
}
Hope this helps.
You are looking for SPSecurity.RunWithElevatedPrivileges Method.

Resources