public GetAppOnlyAuthenticatedContext ( string siteUrl, string appId, string appSecret ) : ClientContext | ||
siteUrl | string | Site for which the ClientContext object will be instantiated |
appId | string | Application ID which is requesting the ClientContext object |
appSecret | string | Application secret of the Application which is requesting the ClientContext object |
return | ClientContext |
protected static void UsingTenantContext(Action<ClientContext> action) { var auth = new OfficeDevPnP.Core.AuthenticationManager(); var tenenatUrl = ConfigurationManager.AppSettings["TenantAdminUrl"]; var realm = ConfigurationManager.AppSettings["Realm"]; var appId = ConfigurationManager.AppSettings["ClientId"]; var appSecret = ConfigurationManager.AppSettings["ClientSecret"]; using (var context = auth.GetAppOnlyAuthenticatedContext(tenenatUrl, realm, appId, appSecret)) { action(context); } }
//internal static Uri RedirectUri; //internal static string ClientId; internal static SPOnlineConnection InstantiateSPOnlineConnection(Uri url, string realm, string clientId, string clientSecret, PSHost host, int minimalHealthScore, int retryCount, int retryWait, int requestTimeout, bool skipAdminCheck = false) { var authManager = new OfficeDevPnP.Core.AuthenticationManager(); if (realm == null) { realm = GetRealmFromTargetUrl(url); } var context = PnPClientContext.ConvertFrom(authManager.GetAppOnlyAuthenticatedContext(url.ToString(), realm, clientId, clientSecret), retryCount, retryWait * 1000); context.ApplicationName = Properties.Resources.ApplicationName; context.RequestTimeout = requestTimeout; #if !ONPREMISES context.DisableReturnValueCache = true; #elif SP2016 context.DisableReturnValueCache = true; #endif 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())); }
/// <summary> /// REtrieve an authenticated ClientContext using AppOnly auth /// </summary> /// <param name="Url">The SharePoint Online site Url</param> /// <param name="AppID">The App id</param> /// <param name="AppSecret">The App secret</param> /// <returns>A tested authenticated ClientContext</returns> public static ClientContext GetAuthenticatedContext(string Url, string AppID, string AppSecret) { var am = new OfficeDevPnP.Core.AuthenticationManager(); var context = am.GetAppOnlyAuthenticatedContext(Url, AppID, AppSecret); // We try to call for the SPO site title validateAuthentication(context); return(context); }
internal static SPOnlineConnection InstantiateSPOnlineConnection(Uri url, string realm, string clientId, string clientSecret, PSHost host, int minimalHealthScore, int retryCount, int retryWait, int requestTimeout, string tenantAdminUrl, bool disableTelemetry, bool skipAdminCheck = false, AzureEnvironment azureEnvironment = AzureEnvironment.Production) { var authManager = new OfficeDevPnP.Core.AuthenticationManager(); if (realm == null) { realm = GetRealmFromTargetUrl(url); } PnPClientContext context; if (url.DnsSafeHost.Contains("spoppe.com")) { context = PnPClientContext.ConvertFrom(authManager.GetAppOnlyAuthenticatedContext(url.ToString(), realm, clientId, clientSecret, acsHostUrl: "windows-ppe.net", globalEndPointPrefix: "login"), retryCount, retryWait * 1000); } else { context = PnPClientContext.ConvertFrom(authManager.GetAppOnlyAuthenticatedContext(url.ToString(), realm, clientId, clientSecret, acsHostUrl: authManager.GetAzureADACSEndPoint(azureEnvironment), globalEndPointPrefix: authManager.GetAzureADACSEndPointPrefix(azureEnvironment)), retryCount, retryWait * 1000); } context.ApplicationName = Properties.Resources.ApplicationName; context.RequestTimeout = requestTimeout; #if !ONPREMISES context.DisableReturnValueCache = true; #elif SP2016 || SP2019 context.DisableReturnValueCache = true; #endif 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, clientId, clientSecret, url.ToString(), tenantAdminUrl, PnPPSVersionTag, host, disableTelemetry, InitializationType.SPClientSecret)); }
protected static void UsingTenantContext(Action <ClientContext> action) { var auth = new OfficeDevPnP.Core.AuthenticationManager(); var tenenatUrl = ConfigurationManager.AppSettings["TenantAdminUrl"]; var realm = ConfigurationManager.AppSettings["Realm"]; var appId = ConfigurationManager.AppSettings["ClientId"]; var appSecret = ConfigurationManager.AppSettings["ClientSecret"]; using (var context = auth.GetAppOnlyAuthenticatedContext(tenenatUrl, realm, appId, appSecret)) { action(context); } }
internal static SPOnlineConnection InstantiateSPOnlineConnection(Uri url, string realm, string clientId, string clientSecret, PSHost host, int minimalHealthScore, int retryCount, int retryWait, int requestTimeout, string tenantAdminUrl, bool skipAdminCheck = false) { var authManager = new OfficeDevPnP.Core.AuthenticationManager(); if (realm == null) { realm = GetRealmFromTargetUrl(url); } PnPClientContext context = null; if (url.DnsSafeHost.Contains("spoppe.com")) { context = PnPClientContext.ConvertFrom(authManager.GetAppOnlyAuthenticatedContext(url.ToString(), realm, clientId, clientSecret, acsHostUrl: "windows-ppe.net", globalEndPointPrefix: "login"), retryCount, retryWait * 1000); } else { context = PnPClientContext.ConvertFrom(authManager.GetAppOnlyAuthenticatedContext(url.ToString(), realm, clientId, clientSecret), retryCount, retryWait * 1000); } context.ApplicationName = Properties.Resources.ApplicationName; context.RequestTimeout = requestTimeout; #if !ONPREMISES context.DisableReturnValueCache = true; #elif SP2016 context.DisableReturnValueCache = true; #endif 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); }
// This function will get triggered/executed when a new message is written // on an Azure Queue called queue. public static void ExecuteTimer([TimerTrigger("0 */5 * * * *", RunOnStartup = true)] TimerInfo timer, TextWriter log) { OfficeDevPnP.Core.AuthenticationManager authMan = new OfficeDevPnP.Core.AuthenticationManager(); using (ClientContext ctx = authMan.GetAppOnlyAuthenticatedContext(ConfigurationManager.AppSettings["PiwikAdminSiteUrl"], ConfigurationManager.AppSettings["PiwikAzureAppKey"], ConfigurationManager.AppSettings["PiwikAzureAppSecret"])) { Functions f = new Functions(); AzureLogger splogger = new AzureLogger(); splogger.WriteLog(Category.Information, "Piwik PRO Job", "Started"); Configuration cfg = new Configuration(splogger, ctx); PiwikPROJobOperations pbjo = new PiwikPROJobOperations(cfg, splogger); pbjo.GetAllNewSitesAndOperate(ctx, ConfigurationManager.AppSettings["PiwikAzureAppKey"], ConfigurationManager.AppSettings["PiwikAzureAppSecret"], ConfigurationManager.AppSettings["PiwikAdminTenantSiteUrl"]); pbjo.GetAllDeactivatingSitesAndOperate(ctx, ConfigurationManager.AppSettings["PiwikAzureAppKey"], ConfigurationManager.AppSettings["PiwikAzureAppSecret"], ConfigurationManager.AppSettings["PiwikAdminTenantSiteUrl"]); splogger.WriteLog(Category.Information, "Piwik PRO Job", "Finished"); } }
private static ClientContext CreateContext(string contextUrl, ICredentials credentials) { ClientContext context = null; if (!String.IsNullOrEmpty(AppId) && !String.IsNullOrEmpty(AppSecret)) { OfficeDevPnP.Core.AuthenticationManager am = new OfficeDevPnP.Core.AuthenticationManager(); context = am.GetAppOnlyAuthenticatedContext(contextUrl, AppId, AppSecret); } else { context = new ClientContext(contextUrl); context.Credentials = credentials; } context.RequestTimeout = 1000 * 60 * 15; return(context); }
/// <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); }