GetAzureADAppOnlyAuthenticatedContext() публичный Метод

Returns a SharePoint ClientContext using Azure Active Directory App Only Authentication. This requires that you have a certificated created, and updated the key credentials key in the application manifest in the azure AD accordingly.
public GetAzureADAppOnlyAuthenticatedContext ( string siteUrl, string clientId, string tenant, StoreName storeName, StoreLocation storeLocation, string thumbPrint, AzureEnvironment environment = AzureEnvironment.Production ) : ClientContext
siteUrl string Site for which the ClientContext object will be instantiated
clientId string The Azure AD Application Client ID
tenant string The Azure AD Tenant, e.g. mycompany.onmicrosoft.com
storeName StoreName The name of the store for the certificate
storeLocation StoreLocation The location of the store for the certificate
thumbPrint string The thumbprint of the certificate to locate in the store
environment AzureEnvironment Indicates which Azure AD environment is being used
Результат ClientContext
        internal static SPOnlineConnection InitiateAzureADAppOnlyConnection(Uri url, string clientId, string tenant, string certificatePEM, string privateKeyPEM, SecureString certificatePassword, int minimalHealthScore, int retryCount, int retryWait, int requestTimeout, string tenantAdminUrl, PSHost host, bool disableTelemetry, bool skipAdminCheck = false, AzureEnvironment azureEnvironment = AzureEnvironment.Production)
        {
            string           password    = new System.Net.NetworkCredential(string.Empty, certificatePassword).Password;
            X509Certificate2 certificate = CertificateHelper.GetCertificateFromPEMstring(certificatePEM, privateKeyPEM, password);

            var authManager    = new OfficeDevPnP.Core.AuthenticationManager();
            var clientContext  = authManager.GetAzureADAppOnlyAuthenticatedContext(url.ToString(), clientId, tenant, certificate, azureEnvironment);
            var context        = PnPClientContext.ConvertFrom(clientContext, retryCount, retryWait * 1000);
            var connectionType = ConnectionType.OnPrem;

            if (url.Host.ToUpperInvariant().EndsWith("SHAREPOINT.COM"))
            {
                connectionType = ConnectionType.O365;
            }
            if (skipAdminCheck == false)
            {
                if (IsTenantAdminSite(context))
                {
                    connectionType = ConnectionType.TenantAdmin;
                }
            }

            CleanupCryptoMachineKey(certificate);

            return(new SPOnlineConnection(context, connectionType, minimalHealthScore, retryCount, retryWait, null, url.ToString(), tenantAdminUrl, PnPPSVersionTag, host, disableTelemetry, InitializationType.AADAppOnly));
        }
Пример #2
0
        public static void ProvisionArtifactsByTemplate()
        {
            // Create a PnP AuthenticationManager object
            AuthenticationManager am = new AuthenticationManager();

            // Authenticate against SPO with an App-Only access token
            using (ClientContext context = am.GetAzureADAppOnlyAuthenticatedContext(
                O365ProjectsAppContext.CurrentSiteUrl, O365ProjectsAppSettings.ClientId,
                O365ProjectsAppSettings.TenantId, O365ProjectsAppSettings.AppOnlyCertificate))
            {
                Web web = context.Web;

                // Load the template from the file system
                XMLTemplateProvider provider =
                new XMLFileSystemTemplateProvider(
                    String.Format(HttpContext.Current.Server.MapPath(".")),
                    "ProvisioningTemplates");

                ProvisioningTemplate template = provider.GetTemplate("O365ProjectsAppSite.xml");

                // Configure the AppSiteUrl parameter
                template.Parameters["AppSiteUrl"] = O365ProjectsAppContext.CurrentAppSiteUrl;

                // Apply the template to the target site
                template.Connector = provider.Connector;
                web.ApplyProvisioningTemplate(template);
            }
        }
Пример #3
0
        private static SPOnlineConnection InitiateAzureAdAppOnlyConnectionWithCert(Uri url, string clientId, string tenant,
                                                                                   int minimalHealthScore, int retryCount, int retryWait, int requestTimeout, string tenantAdminUrl, PSHost host, bool disableTelemetry,
                                                                                   bool skipAdminCheck, AzureEnvironment azureEnvironment, X509Certificate2 certificate)
        {
            var authManager   = new OfficeDevPnP.Core.AuthenticationManager();
            var clientContext =
                authManager.GetAzureADAppOnlyAuthenticatedContext(url.ToString(), clientId, tenant, certificate,
                                                                  azureEnvironment);
            var context = PnPClientContext.ConvertFrom(clientContext, retryCount, retryWait * 1000);

            context.RequestTimeout = requestTimeout;
            var connectionType = ConnectionType.OnPrem;

            if (url.Host.ToUpperInvariant().EndsWith("SHAREPOINT.COM"))
            {
                connectionType = ConnectionType.O365;
            }

            if (skipAdminCheck == false)
            {
                if (IsTenantAdminSite(context))
                {
                    connectionType = ConnectionType.TenantAdmin;
                }
            }

            CleanupCryptoMachineKey(certificate);

            var spoConnection = new SPOnlineConnection(context, connectionType, minimalHealthScore, retryCount, retryWait, null,
                                                       url.ToString(), tenantAdminUrl, PnPPSVersionTag, host, disableTelemetry, InitializationType.AADAppOnly);

            spoConnection.ConnectionMethod = ConnectionMethod.AzureADAppOnly;
            return(spoConnection);
        }
Пример #4
0
        public static void ProvisionArtifactsByCode()
        {
            // Create a PnP AuthenticationManager object
            AuthenticationManager am = new AuthenticationManager();

            // Authenticate against SPO with an App-Only access token
            using (ClientContext context = am.GetAzureADAppOnlyAuthenticatedContext(
                O365ProjectsAppContext.CurrentSiteUrl, O365ProjectsAppSettings.ClientId,
                O365ProjectsAppSettings.TenantId, O365ProjectsAppSettings.AppOnlyCertificate))
            {
                Web web = context.Web;
                List targetLibrary = null;

                // If the target library does not exist (PnP extension method)
                if (!web.ListExists(O365ProjectsAppSettings.LibraryTitle))
                {
                    // Create it using another PnP extension method
                    targetLibrary = web.CreateList(ListTemplateType.DocumentLibrary,
                        O365ProjectsAppSettings.LibraryTitle, true, true);
                }
                else
                {
                    targetLibrary = web.GetListByTitle(O365ProjectsAppSettings.LibraryTitle);
                }

                // If the target library exists
                if (targetLibrary != null)
                {
                    // Try to get the user's custom action
                    UserCustomAction customAction = targetLibrary.GetCustomAction(O365ProjectsAppConstants.ECB_Menu_Name);

                    // If it doesn't exist
                    if (customAction == null)
                    {
                        // Add the user custom action to the list
                        customAction = targetLibrary.UserCustomActions.Add();
                        customAction.Name = O365ProjectsAppConstants.ECB_Menu_Name;
                        customAction.Location = "EditControlBlock";
                        customAction.Sequence = 100;
                        customAction.Title = "Manage Business Project";
                        customAction.Url = $"{O365ProjectsAppContext.CurrentAppSiteUrl}Project/?SiteUrl={{SiteUrl}}&ListId={{ListId}}&ItemId={{ItemId}}&ItemUrl={{ItemUrl}}";
                    }
                    else
                    {
                        // Update the already existing Custom Action
                        customAction.Name = O365ProjectsAppConstants.ECB_Menu_Name;
                        customAction.Location = "EditControlBlock";
                        customAction.Sequence = 100;
                        customAction.Title = "Manage Business Project";
                        customAction.Url = $"{O365ProjectsAppContext.CurrentAppSiteUrl}Project/?SiteUrl={{SiteUrl}}&ListId={{ListId}}&ItemId={{ItemId}}&ItemUrl={{ItemUrl}}";
                    }

                    customAction.Update();
                    context.ExecuteQueryRetry();

                }
            }
        }
        public static ClientContext GetAppOnlyClientContext(String siteUrl)
        {
            string tenantID = ClaimsPrincipal.Current.HasClaim(c => c.Type == "http://schemas.microsoft.com/identity/claims/tenantid") ?
                ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value :
                PnPPartnerPackSettings.Tenant;

            AuthenticationManager authManager = new AuthenticationManager();
            ClientContext context = authManager.GetAzureADAppOnlyAuthenticatedContext(
                siteUrl,
                PnPPartnerPackSettings.ClientId,
                tenantID,
                PnPPartnerPackSettings.AppOnlyCertificate);

            return (context);
        }
Пример #6
0
        internal static SPOnlineConnection InitiateAzureADAppOnlyConnection(Uri url, string clientId, string tenant, string certificatePath, SecureString certificatePassword, int minimalHealthScore, int retryCount, int retryWait, int requestTimeout, bool skipAdminCheck = false)
        {
            var authManager    = new OfficeDevPnP.Core.AuthenticationManager();
            var context        = PnPClientContext.ConvertFrom(authManager.GetAzureADAppOnlyAuthenticatedContext(url.ToString(), clientId, tenant, certificatePath, certificatePassword), retryCount, retryWait * 1000);
            var connectionType = ConnectionType.OnPrem;

            if (url.Host.ToUpperInvariant().EndsWith("SHAREPOINT.COM"))
            {
                connectionType = ConnectionType.O365;
            }
            if (skipAdminCheck == false)
            {
                if (IsTenantAdminSite(context))
                {
                    connectionType = ConnectionType.TenantAdmin;
                }
            }
            return(new SPOnlineConnection(context, connectionType, minimalHealthScore, retryCount, retryWait, null, url.ToString()));
        }
        internal static SPOnlineConnection InitiateAzureADAppOnlyConnection(Uri url, string clientId, string tenant, string certificatePEM, string privateKeyPEM, int minimalHealthScore, int retryCount, int retryWait, int requestTimeout, string tenantAdminUrl, bool skipAdminCheck = false, AzureEnvironment azureEnvironment = AzureEnvironment.Production)
        {
            X509Certificate2 certificate = CertificateHelper.GetCertificateFromPEMstring(certificatePEM, privateKeyPEM);

            var authManager    = new OfficeDevPnP.Core.AuthenticationManager();
            var clientContext  = authManager.GetAzureADAppOnlyAuthenticatedContext(url.ToString(), clientId, tenant, certificate, azureEnvironment);
            var context        = PnPClientContext.ConvertFrom(clientContext, retryCount, retryWait * 1000);
            var connectionType = ConnectionType.OnPrem;

            if (url.Host.ToUpperInvariant().EndsWith("SHAREPOINT.COM"))
            {
                connectionType = ConnectionType.O365;
            }
            if (skipAdminCheck == false)
            {
                if (IsTenantAdminSite(context))
                {
                    connectionType = ConnectionType.TenantAdmin;
                }
            }
            return(new SPOnlineConnection(context, connectionType, minimalHealthScore, retryCount, retryWait, null, url.ToString(), tenantAdminUrl, PnPPSVersionTag));
        }
        internal static SPOnlineConnection InitiateAzureADAppOnlyConnection(Uri url, string clientId, string tenant, string certificatePath, SecureString certificatePassword, int minimalHealthScore, int retryCount, int retryWait, int requestTimeout, string tenantAdminUrl, PSHost host, bool disableTelemetry, bool skipAdminCheck = false, AzureEnvironment azureEnvironment = AzureEnvironment.Production)
        {
            var authManager    = new OfficeDevPnP.Core.AuthenticationManager();
            var context        = PnPClientContext.ConvertFrom(authManager.GetAzureADAppOnlyAuthenticatedContext(url.ToString(), clientId, tenant, certificatePath, certificatePassword, azureEnvironment), retryCount, retryWait * 1000);
            var connectionType = ConnectionType.OnPrem;

            if (url.Host.ToUpperInvariant().EndsWith("SHAREPOINT.COM"))
            {
                connectionType = ConnectionType.O365;
            }
            if (skipAdminCheck == false)
            {
                if (IsTenantAdminSite(context))
                {
                    connectionType = ConnectionType.TenantAdmin;
                }
            }
            var spoConnection = new SPOnlineConnection(context, connectionType, minimalHealthScore, retryCount, retryWait, null, url.ToString(), tenantAdminUrl, PnPPSVersionTag, host, disableTelemetry, InitializationType.AADAppOnly);

            spoConnection.ConnectionMethod = Model.ConnectionMethod.AzureADAppOnly;
            return(spoConnection);
        }
        /// <summary>
        /// Clones a ClientContext object while "taking over" the security context of the existing ClientContext instance
        /// </summary>
        /// <param name="clientContext">ClientContext to be cloned</param>
        /// <param name="siteUrl">Site URL to be used for cloned ClientContext</param>
        /// <param name="accessTokens">Dictionary of access tokens for sites URLs</param>
        /// <returns>A ClientContext object created for the passed site URL</returns>
        public static ClientContext Clone(this ClientRuntimeContext clientContext, Uri siteUrl, Dictionary <String, String> accessTokens = null)
        {
            if (siteUrl == null)
            {
                throw new ArgumentException(CoreResources.ClientContextExtensions_Clone_Url_of_the_site_is_required_, nameof(siteUrl));
            }

            ClientContext clonedClientContext = new ClientContext(siteUrl);

            clonedClientContext.AuthenticationMode = clientContext.AuthenticationMode;
            clonedClientContext.ClientTag          = clientContext.ClientTag;
#if !ONPREMISES || SP2016 || SP2019
            clonedClientContext.DisableReturnValueCache = clientContext.DisableReturnValueCache;
#endif


            // In case of using networkcredentials in on premises or SharePointOnlineCredentials in Office 365
            if (clientContext.Credentials != null)
            {
                clonedClientContext.Credentials = clientContext.Credentials;
            }
            else
            {
                // Check if we do have context settings
                var contextSettings = clientContext.GetContextSettings();

                if (contextSettings != null) // We do have more information about this client context, so let's use it to do a more intelligent clone
                {
                    string newSiteUrl = siteUrl.ToString();

                    // A diffent host = different audience ==> new access token is needed
                    if (contextSettings.UsesDifferentAudience(newSiteUrl))
                    {
                        // We need to create a new context using a new authentication manager as the token expiration is handled in there
                        OfficeDevPnP.Core.AuthenticationManager authManager = new OfficeDevPnP.Core.AuthenticationManager();

                        ClientContext newClientContext = null;
                        if (contextSettings.Type == ClientContextType.SharePointACSAppOnly)
                        {
                            newClientContext = authManager.GetAppOnlyAuthenticatedContext(newSiteUrl, TokenHelper.GetRealmFromTargetUrl(new Uri(newSiteUrl)), contextSettings.ClientId, contextSettings.ClientSecret, contextSettings.AcsHostUrl, contextSettings.GlobalEndPointPrefix);
                        }
#if !ONPREMISES && !NETSTANDARD2_0
                        else if (contextSettings.Type == ClientContextType.AzureADCredentials)
                        {
                            newClientContext = authManager.GetAzureADCredentialsContext(newSiteUrl, contextSettings.UserName, contextSettings.Password);
                        }
                        else if (contextSettings.Type == ClientContextType.AzureADCertificate)
                        {
                            newClientContext = authManager.GetAzureADAppOnlyAuthenticatedContext(newSiteUrl, contextSettings.ClientId, contextSettings.Tenant, contextSettings.Certificate, contextSettings.Environment);
                        }
#endif

                        if (newClientContext != null)
                        {
                            //Take over the form digest handling setting
                            newClientContext.FormDigestHandlingEnabled = (clientContext as ClientContext).FormDigestHandlingEnabled;
                            newClientContext.ClientTag = clientContext.ClientTag;
#if !ONPREMISES || SP2016 || SP2019
                            newClientContext.DisableReturnValueCache = clientContext.DisableReturnValueCache;
#endif
                            return(newClientContext);
                        }
                        else
                        {
                            throw new Exception($"Cloning for context setting type {contextSettings.Type} was not yet implemented");
                        }
                    }
                    else
                    {
                        // Take over the context settings, this is needed if we later on want to clone this context to a different audience
                        contextSettings.SiteUrl = newSiteUrl;
                        clonedClientContext.AddContextSettings(contextSettings);

                        clonedClientContext.ExecutingWebRequest += delegate(object oSender, WebRequestEventArgs webRequestEventArgs)
                        {
                            // Call the ExecutingWebRequest delegate method from the original ClientContext object, but pass along the webRequestEventArgs of
                            // the new delegate method
                            MethodInfo methodInfo      = clientContext.GetType().GetMethod("OnExecutingWebRequest", BindingFlags.Instance | BindingFlags.NonPublic);
                            object[]   parametersArray = new object[] { webRequestEventArgs };
                            methodInfo.Invoke(clientContext, parametersArray);
                        };
                    }
                }
                else // Fallback the default cloning logic if there were not context settings available
                {
                    //Take over the form digest handling setting
                    clonedClientContext.FormDigestHandlingEnabled = (clientContext as ClientContext).FormDigestHandlingEnabled;

                    var originalUri = new Uri(clientContext.Url);
                    // If the cloned host is not the same as the original one
                    // and if there is an active PnPProvisioningContext
                    if (originalUri.Host != siteUrl.Host &&
                        PnPProvisioningContext.Current != null)
                    {
                        // Let's apply that specific Access Token
                        clonedClientContext.ExecutingWebRequest += (sender, args) =>
                        {
                            // We get a fresh new Access Token for every request, to avoid using an expired one
                            var accessToken = PnPProvisioningContext.Current.AcquireToken(siteUrl.Authority, null);
                            args.WebRequestExecutor.RequestHeaders["Authorization"] = "Bearer " + accessToken;
                        };
                    }
                    // Else if the cloned host is not the same as the original one
                    // and if there is a custom Access Token for it in the input arguments
                    else if (originalUri.Host != siteUrl.Host &&
                             accessTokens != null && accessTokens.Count > 0 &&
                             accessTokens.ContainsKey(siteUrl.Authority))
                    {
                        // Let's apply that specific Access Token
                        clonedClientContext.ExecutingWebRequest += (sender, args) =>
                        {
                            args.WebRequestExecutor.RequestHeaders["Authorization"] = "Bearer " + accessTokens[siteUrl.Authority];
                        };
                    }
                    // Else if the cloned host is not the same as the original one
                    // and if the client context is a PnPClientContext with custom access tokens in its property bag
                    else if (originalUri.Host != siteUrl.Host &&
                             accessTokens == null && clientContext is PnPClientContext &&
                             ((PnPClientContext)clientContext).PropertyBag.ContainsKey("AccessTokens") &&
                             ((Dictionary <string, string>)((PnPClientContext)clientContext).PropertyBag["AccessTokens"]).ContainsKey(siteUrl.Authority))
                    {
                        // Let's apply that specific Access Token
                        clonedClientContext.ExecutingWebRequest += (sender, args) =>
                        {
                            args.WebRequestExecutor.RequestHeaders["Authorization"] = "Bearer " + ((Dictionary <string, string>)((PnPClientContext)clientContext).PropertyBag["AccessTokens"])[siteUrl.Authority];
                        };
                    }
                    else
                    {
                        // In case of app only or SAML
                        clonedClientContext.ExecutingWebRequest += (sender, webRequestEventArgs) =>
                        {
                            // Call the ExecutingWebRequest delegate method from the original ClientContext object, but pass along the webRequestEventArgs of
                            // the new delegate method
                            MethodInfo methodInfo      = clientContext.GetType().GetMethod("OnExecutingWebRequest", BindingFlags.Instance | BindingFlags.NonPublic);
                            object[]   parametersArray = new object[] { webRequestEventArgs };
                            methodInfo.Invoke(clientContext, parametersArray);
                        };
                    }
                }
            }

            return(clonedClientContext);
        }
 internal static SPOnlineConnection InitiateAzureADAppOnlyConnection(Uri url, string clientId, string tenant, string certificatePath, SecureString certificatePassword, int minimalHealthScore, int retryCount, int retryWait, int requestTimeout, string tenantAdminUrl, bool skipAdminCheck = false)
 {
     var authManager = new OfficeDevPnP.Core.AuthenticationManager();
     var context = PnPClientContext.ConvertFrom(authManager.GetAzureADAppOnlyAuthenticatedContext(url.ToString(), clientId, tenant, certificatePath, certificatePassword), retryCount, retryWait * 1000);
     var connectionType = ConnectionType.OnPrem;
     if (url.Host.ToUpperInvariant().EndsWith("SHAREPOINT.COM"))
     {
         connectionType = ConnectionType.O365;
     }
     if (skipAdminCheck == false)
     {
         if (IsTenantAdminSite(context))
         {
             connectionType = ConnectionType.TenantAdmin;
         }
     }
     return new SPOnlineConnection(context, connectionType, minimalHealthScore, retryCount, retryWait, null, url.ToString(), tenantAdminUrl, PnPPSVersionTag);
 }