Retrieve data for sub sites and child sites - spsite

I need to access following structure on SP server with following structure.
I have tried SPWebApp, SPWeb, SPSite and GetSubwebsForCurrentUser but I am missing something and I am not able to get data past branch Trees.
Please note that I do not have access to ClientContext (using network credentials with Admin account gives access denied error).
Any help will be appreciated.
\sites\Trees
\sites\Trees\Planted\Apples
\sites\Trees\Planted\1203\Pears
\sites\Trees\Planted\1203\Apples
\sites\Trees\Relocated\1104\Fer
\sites\Trees\Relocated\1104\Fer\local
\sites\Trees\Relocated\1104\Fer\invader
Thanks

private List<string> GetChildSites(string URL)
{
List<string> sitesList = new List<string>();
using (SPSite site = new SPSite(URL))
{
foreach (SPWeb web in site.AllWebs)
{
sitesList.Add(web.Url);
web.Dispose();
}
}
return sitesList;
}

Related

AEM 6.3 Cannot create groups with service user

Hoping someone on here can help me out of a conundrum.
We are trying to remove all Admin sessions from our application, but are stuck with a few due to JCR Access Denied exceptions. Specifically, when we try to create AEM groups or users with a service user we get an Access Denied exception. Here is a piece of code written to isolate the problem:
private void testUserCreation2() {
String groupName = "TestingGroup1";
Session session = null;
ResourceResolver resourceResolver = null;
String createdGroupName = null;
try {
Map<String, Object> param = new HashMap<String, Object>();
param.put(ResourceResolverFactory.SUBSERVICE, "userManagementService");
resourceResolver = resourceResolverFactory.getServiceResourceResolver(param);
session = resourceResolver.adaptTo(Session.class);
// Create UserManager Object
final UserManager userManager = AccessControlUtil.getUserManager(session);
// Create a Group
LOGGER.info("Attempting to create group: "+groupName+" with user "+session.getUserID());
if (userManager.getAuthorizable(groupName) == null) {
Group createdGroup = userManager.createGroup(new Principal() {
#Override
public String getName() {
return groupName;
}
}, "/home/groups/testing");
createdGroupName = createdGroup.getPath();
session.save();
LOGGER.info("Group successfully created: "+createdGroupName);
} else {
LOGGER.info("Group already exists");
}
} catch (Exception e) {
LOGGER.error("Error while attempting to create group.",e);
} finally {
if (session != null && session.isLive()) {
session.logout();
}
if (resourceResolver != null)
resourceResolver.close();
}
}
Notice that I'm using a subservice name titled userManagementService, which maps to a user titled fwi-admin-user. Since fwi-admin-user is a service user, I cannot add it to the administrators group (This seems to be a design limitation on AEM). However, I have confirmed that the user has full permissions to the entire repository via the useradmin UI.
Unfortunately, I still get the following error when I invoke this code:
2020-06-22 17:46:56.017 INFO
[za.co.someplace.forms.core.servlets.IntegrationTestServlet]
Attempting to create group: TestingGroup1 with user fwi-admin-user
2020-06-22 17:46:56.025 ERROR
[za.co.someplace.forms.core.servlets.IntegrationTestServlet] Error
while attempting to create group. javax.jcr.AccessDeniedException:
OakAccess0000: Access denied at
org.apache.jackrabbit.oak.api.CommitFailedException.asRepositoryException(CommitFailedException.java:231)
at
org.apache.jackrabbit.oak.api.CommitFailedException.asRepositoryException(CommitFailedException.java:212)
at
org.apache.jackrabbit.oak.jcr.delegate.SessionDelegate.newRepositoryException(SessionDelegate.java:670)
at
org.apache.jackrabbit.oak.jcr.delegate.SessionDelegate.save(SessionDelegate.java:496)
Is this an AEM bug, or am I doing something wrong here?
Thanks in advance
So it seems the bug is actually in the old useradmin interface. It was not allowing me to add my system user into the admninistrators group, but this is possible in the new touch UI admin interface.

How do I create an AlertsClient from an Azure Active Directory secret? [duplicate]

My company is looking into reporting on Azure. We only want our customers to give us read only credentials for us to use. I did some research and it looks like Azure Active Directory does just that. So I'm looking to authenticate using a read only Azure Directory Application.
To get me started I was following this blog on using the Management API via Azure Active Directory.
https://msdn.microsoft.com/en-us/library/azure/dn722415.aspx
Aside from the approach show being very unfriendly, it doesn't work =(
I get this error after logging in as a global administrator:
"AADSTS90014: The request body must contain the following parameter: 'client_secret or client_assertion'."
Did some research and found this style of authentication was for native app and NOT web apps (despite what the blog post saying other wise..). So I made a tweak. My GetAuthorizationHeader now looks like this:
private static string GetAuthorizationHeader()
{
AuthenticationResult result = null;
var context = new AuthenticationContext("https://login.windows.net/" + ConfigurationManager.AppSettings["tenantId"]);
string clientId = ConfigurationManager.AppSettings["clientId"];
string clientSecret = ConfigurationManager.AppSettings["clientSecret"];
ClientCredential clientCred = new ClientCredential(clientId, clientSecret);
var thread = new Thread(() =>
{
result = context.AcquireToken(
"https://management.core.windows.net/",
clientCred);
});
thread.SetApartmentState(ApartmentState.STA);
thread.Name = "AquireTokenThread";
thread.Start();
thread.Join();
if (result == null)
{
throw new InvalidOperationException("Failed to obtain the JWT token");
}
string token = result.AccessToken;
return token;
}
I am able to get the Access Token (yay). But now when I try to use this with the Azure Management library client I get this error:
"ForbiddenError: The server failed to authenticate the request. Verify that the certificate is valid and is associated with this subscription."
I double checked my permissions in my application. It looked good. I tried giving full access to everything to see if that would have made a difference.
I double checked my tenantId, clientId, and subscriptionId, all looked good.
I made sure the subscription I'm using is pointed to the AD my application is in.
I tried making a new secret key.
My guess is this is the issue:
However in this UI I am unable to select any values for that property. I'm unsure if this is the result of a bug or an unfinished feature.
Am I missing something here?
Thanks
Here's my full code for reference:
class Program
{
static void Main(string[] args)
{
var token = GetAuthorizationHeader();
var credential = new TokenCloudCredentials(ConfigurationManager.AppSettings["subscriptionId"], token);
using (var computeClient = new ComputeManagementClient(credential))
{
var images = computeClient.VirtualMachineOSImages.List();
}
}
private static string GetAuthorizationHeader()
{
AuthenticationResult result = null;
var context = new AuthenticationContext("https://login.windows.net/" + ConfigurationManager.AppSettings["tenantId"]);
string clientId = ConfigurationManager.AppSettings["clientId"];
string clientSecret = ConfigurationManager.AppSettings["clientSecret"];
ClientCredential clientCred = new ClientCredential(clientId, clientSecret);
var thread = new Thread(() =>
{
result = context.AcquireToken(
"https://management.core.windows.net/",
clientCred);
});
thread.SetApartmentState(ApartmentState.STA);
thread.Name = "AquireTokenThread";
thread.Start();
thread.Join();
if (result == null)
{
throw new InvalidOperationException("Failed to obtain the JWT token");
}
string token = result.AccessToken;
return token;
}
}
EDIT:
Progress has been made. As I discussed with Gaurav, I needed to ditch the Azure Management Library because as of right now it does not seem to support Azure Resource Manager (ARM) API! So instead I did raw web requests. And it works as intended. If I remove role access off my AD Application I get access denied. When I have it I get back data.
One thing I'm not sure about is making it so my application is auto-adding to new resources.
Also, Is there a way to list Resource Groups that are accessible for my AD Application?
New code:
class Program
{
static void Main(string[] args)
{
var token = GetAuthorizationHeader();
string subscriptionId = ConfigurationManager.AppSettings["subscriptionId"];
string resourceGroupName = ConfigurationManager.AppSettings["resourceGroupName"];
var uriListMachines = string.Format("https://management.azure.com/subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.Compute/virtualmachines?api-version=2015-05-01-preview", subscriptionId, resourceGroupName);
var t = WebRequest.Create(uriListMachines);
t.ContentType = "application/json";
t.Headers.Add("Authorization", "Bearer " + token);
var response = (HttpWebResponse)t.GetResponse();
string result = "";
using (var reader = new StreamReader(response.GetResponseStream()))
{
result = reader.ReadToEnd();
}
//Original Attempt:
//var credential = new TokenCloudCredentials(ConfigurationManager.AppSettings["subscriptionId"], token);
//using (var client = CloudContext.Clients.CreateComputeManagementClient(credential))
//{
// var images = client.VirtualMachineVMImages.List();
//}
}
private static string GetAuthorizationHeader()
{
AuthenticationResult result = null;
var context = new AuthenticationContext("https://login.windows.net/" + ConfigurationManager.AppSettings["tenantId"]);
string clientId = ConfigurationManager.AppSettings["clientId"];
string clientSecret = ConfigurationManager.AppSettings["clientSecret"];
ClientCredential clientCred = new ClientCredential(clientId, clientSecret);
var thread = new Thread(() =>
{
result = context.AcquireToken(
"https://management.core.windows.net/",
clientCred);
});
thread.SetApartmentState(ApartmentState.STA);
thread.Name = "AquireTokenThread";
thread.Start();
thread.Join();
if (result == null)
{
throw new InvalidOperationException("Failed to obtain the JWT token");
}
string token = result.AccessToken;
return token;
}
}
EDIT EDIT:
I figured out my hung up. Resources created in the OLD portal will get it's own distinct resource group.
From what I can tell you can not add a resource made in the old portal existing resource group (boooo). Resources created in the new portal will be able to assign the resource to an existing group (aka one that gives a role access to my AD Application).
This is such a mess! But at least I know what is going on now.
I believe you're on the right track as to why you're running into this problem.
Here's what's happening:
Essentially permission to execute Service Management API is a delegated permission and not an application permission. In other words, the API is executed in context of the user for which the token is acquired. Now you are getting this token for your application (specified by client id/secret). However your application doesn't have access to your Azure Subscription because the user record created for this application in your Azure AD is of type Service Principal. Since this Service Principal doesn't have access to your Azure Subscription, you're getting this Forbidden Error (I must say that the error is misleading because you're not using certificate at all).
There are a few things you could do:
Switch to Azure Resource Manager (ARM) API - ARM API is the next generation of Service Management API (SM API) and Azure is moving towards this direction only. It exclusively works off of Azure AD token. If possible, make use of that to manage your Azure resources (though you need to keep in mind that as of today not all Azure resources can be managed through ARM API). They way you do it is take your Service Principal and assign it to a particular role using new Azure Portal. Please see this link for more details on this: https://azure.microsoft.com/en-in/documentation/articles/resource-group-create-service-principal-portal/.
Use X509 Certificate - You can always use X509 Certificate based authorization to authorize your SM API requests. Please see this link for more details on that: https://msdn.microsoft.com/en-us/library/azure/ee460782.aspx#bk_cert. The downside of this approach is that the application (or whosoever has access to this certificate) will get full access to your Azure Subscription and can do everything there (including deleting resources).
Acquire token for a user instead of an application - This is another approach you can take. Essentially ask your users to login into Azure AD through your console application and acquire token for that user. Again, please keep in mind that this user must be a Co-Admin in your Azure Subscription and will have full access to your Azure Subscription as with SM API there's no concept of Role-based access control.

SharePoint O365 Get All Users With Certain Role

Is there a way to get all users who have "Full Control" permission at a site collection and subsite level and change their role to something else? PowerShell would be ideal but CSOM would be fine too if that's the only way to do it. I know I can get groups by role but I need a way to get explicitly added users.
I tried this older StackOverflow question: Get all the users based on a specific permission using CSOM in SharePoint 2013 but I keep getting a 403 forbidden error on the first ctx.ExecuteQuery(); for all sites even though I am a collection administrator. I also wonder if anyone had a PowerShell way to do it.
According the error message, I suspect that the credential is missing in your code.
Please try the code below and let me know whether it works on your side.
static void Main(string[] args)
{
var webUrl = "[your_site_url]";
var userEmailAddress = "[your_email_address]";
using (var context = new ClientContext(webUrl))
{
Console.WriteLine("input your password and click enter");
context.Credentials = new SharePointOnlineCredentials(userEmailAddress, GetPasswordFromConsoleInput());
context.Load(context.Web, w => w.Title);
context.ExecuteQuery();
Console.WriteLine("Your site title is: " + context.Web.Title);
//Retrieve site users
var users = context.LoadQuery(context.Web.SiteUsers);
context.ExecuteQuery();
foreach(var user in users)
{
Console.WriteLine(user.Email);
}
}
}
private static SecureString GetPasswordFromConsoleInput()
{
ConsoleKeyInfo info;
SecureString securePassword = new SecureString();
do
{
info = Console.ReadKey(true);
if (info.Key != ConsoleKey.Enter)
{
securePassword.AppendChar(info.KeyChar);
}
}
while (info.Key != ConsoleKey.Enter);
return securePassword;
}
}
You need the SharePoint Online Management shell to stand up a connection to O365 via Powershell.
Introduction to the SharePoint Online management shell

facebook c# SDK get albums and images

what i am trying to achieve should be simple by theory but hell by implementation, if you think otherwise please help.
so what i am trying to achieve here is that I have my facebook page which I created a developer acount for it, and what i want is to take albums from the page to my website.
I am using the latest stable facebook sdk for .net 6.8.0, and i am assuming that the graph api is on v2.2.
this is the code i am using below to get the access token and access my albums
try
{
var fb = new FacebookClient();
dynamic result = fb.Get("oauth/access_token", new
{
client_id = "---my application number---",
client_secret = "---my application secret---",
grant_type = "client_credentials"
});
var fb2 = new FacebookClient(result.access_token);
dynamic albums = fb2.Get("my application number/albums");
foreach (dynamic albumInfo in albums)
{
try
{
dynamic albumsPhotos = fb2.GetTaskAsync(albumInfo.id + "/photos");
}
catch (Exception Exception)
{
throw Exception;
}
}
}
catch (Exception e)
{
throw e;
}
The data returned in the dynamic albums variables is empty, the thing that confused me more is when i use facebook graph api explorer the call work fine and it return the albums. so what exactly i am missing.
I also read in some threads that you can access your albums without the secret password if they are public but that didn't work for me either i tried it in javascript but no joy.
Thank you in advance.
Since this is your page, it should be pretty easy to retrieve your own photos using Windows PowerShell and http://facebookpsmodule.codeplex.com Get-FBAlbums.

Facebook c# sdk get users email

I have a site which is using facebook for auth. I want to gather some basic info when a user signs up including their email address.
The code i have for the login is standard:
public ActionResult Login(string returnUrl)
{
var oAuthClient = new FacebookOAuthClient();
oAuthClient.AppId = AppSettings.GetConfigurationString("appId");
oAuthClient.RedirectUri = new Uri(AppSettings.GetConfigurationString("redirectUrl"));
var loginUri = oAuthClient.GetLoginUrl(new Dictionary<string, object> { { "state", returnUrl } });
return Redirect(loginUri.AbsoluteUri);
}
How do i add the request to access permissions in that? Or do i do it another way?
You need to use the email permission (the full list is here: http://developers.facebook.com/docs/authentication/permissions/ )
The way to add permissions to the authorization is by appending a comma separated list to &scope= , e.g.:
https://www.facebook.com/dialog/oauth?client_id=YOUR_APP_ID&redirect_uri=YOUR_URL&scope=email,read_stream
Update: As you marked, the parameters are passed to the GetLoginUrl() method, although in the codeplex forum they also used ExchangeCodeForAccessToken(), which you might want to take a look at also.
A couple of examples using the C# SDK:
http://blog.prabir.me/post/Facebook-CSharp-SDK-Writing-your-first-Facebook-Application.aspx
Facebook .NET SDK: How to authenticate with ASP.NET MVC 2
http://facebooksdk.codeplex.com/discussions/244568
A snoop at the sdk code and i came up wiht:
public ActionResult Login(string returnUrl)
{
var oAuthClient = new FacebookOAuthClient();
oAuthClient.AppId = AppSettings.GetConfigurationString("appId");
oAuthClient.RedirectUri = new Uri(AppSettings.GetConfigurationString("redirectUrl"));
var parameters = new Dictionary<string, object>();
parameters["state"] = returnUrl;
parameters["scope"] = "email";
var loginUri = oAuthClient.GetLoginUrl(parameters);
return Redirect(loginUri.AbsoluteUri);
}
not tested it yet and the missus is shouting at me for working late so will have to test tomoz :)