/// <summary> /// Creates a new instance of the Authentication Manager to acquire authenticated ClientContexts. /// </summary> /// <param name="clientId">The client id of the Azure AD application to use for authentication</param> /// <param name="certificatePath">A valid path to a certificate file</param> /// <param name="certificatePassword">The password for the certificate</param> /// <param name="redirectUrl">Optional redirect URL to use for authentication as set up in the Azure AD Application</param> /// <param name="azureEnvironment">The azure environment to use. Defaults to AzureEnvironment.Production</param> /// <param name="tokenCacheCallback">If present, after setting up the base flow for authentication this callback will be called register a custom tokencache. See https://aka.ms/msal-net-token-cache-serialization.</param> public AuthenticationManager(string clientId, string certificatePath, string certificatePassword, string redirectUrl = null, AzureEnvironment azureEnvironment = AzureEnvironment.Production, Action <ITokenCache> tokenCacheCallback = null) : this() { azureADEndPoint = GetAzureADLoginEndPoint(azureEnvironment); if (System.IO.File.Exists(certificatePath)) { var certfile = System.IO.File.OpenRead(certificatePath); var certificateBytes = new byte[certfile.Length]; certfile.Read(certificateBytes, 0, (int)certfile.Length); var certificate = new X509Certificate2( certificateBytes, certificatePassword, X509KeyStorageFlags.Exportable | X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet); var builder = ConfidentialClientApplicationBuilder.Create(clientId).WithCertificate(certificate).WithAuthority($"{azureADEndPoint}/organizations/"); if (!string.IsNullOrEmpty(redirectUrl)) { builder = builder.WithRedirectUri(redirectUrl); } confidentialClientApplication = builder.Build(); // register tokencache if callback provided. ApptokenCache as AcquireTokenForClient is beind called to acquire tokens. tokenCacheCallback?.Invoke(confidentialClientApplication.AppTokenCache); authenticationType = ClientContextType.AzureADCertificate; } else { throw new Exception("Certificate path not found"); } }
/// <summary> /// Creates a new instance of the Authentication Manager to acquire authenticated ClientContexts. /// </summary> /// <param name="clientId">The client id of the Azure AD application to use for authentication</param> /// <param name="certificate">A valid certificate</param> /// <param name="redirectUrl">Optional redirect URL to use for authentication as set up in the Azure AD Application</param> /// <param name="azureEnvironment">The azure environment to use. Defaults to AzureEnvironment.Production</param> /// <param name="tokenCacheCallback">If present, after setting up the base flow for authentication this callback will be called register a custom tokencache. See https://aka.ms/msal-net-token-cache-serialization.</param> public AuthenticationManager(string clientId, X509Certificate2 certificate, string tenantId, string redirectUrl = null, AzureEnvironment azureEnvironment = AzureEnvironment.Production, Action <ITokenCache> tokenCacheCallback = null) : this() { azureADEndPoint = GetAzureADLoginEndPoint(azureEnvironment); var builder = ConfidentialClientApplicationBuilder.Create(clientId).WithCertificate(certificate).WithTenantId(tenantId); //.WithAuthority($"{azureADEndPoint}/organizations/"); if (!string.IsNullOrEmpty(redirectUrl)) { builder = builder.WithRedirectUri(redirectUrl); } confidentialClientApplication = builder.Build(); // register tokencache if callback provided tokenCacheCallback?.Invoke(confidentialClientApplication.UserTokenCache); authenticationType = ClientContextType.AzureADCertificate; }
/// <summary> /// Creates a new instance of the Authentication Manager to acquire authenticated ClientContexts. /// </summary> /// <param name="clientId">The client id of the Azure AD application to use for authentication</param> /// <param name="username">The username to use for authentication</param> /// <param name="password">The password to use for authentication</param> /// <param name="redirectUrl">Optional redirect URL to use for authentication as set up in the Azure AD Application</param> /// <param name="azureEnvironment">The azure environment to use. Defaults to AzureEnvironment.Production</param> /// <param name="tokenCacheCallback">If present, after setting up the base flow for authentication this callback will be called register a custom tokencache. See https://aka.ms/msal-net-token-cache-serialization.</param> public AuthenticationManager(string clientId, string username, SecureString password, string redirectUrl = null, AzureEnvironment azureEnvironment = AzureEnvironment.Production, Action <ITokenCache> tokenCacheCallback = null) : this() { azureADEndPoint = GetAzureADLoginEndPoint(azureEnvironment); var builder = PublicClientApplicationBuilder.Create(clientId).WithAuthority($"{azureADEndPoint}/organizations/"); if (!string.IsNullOrEmpty(redirectUrl)) { builder = builder.WithRedirectUri(redirectUrl); } this.username = username; this.password = password; publicClientApplication = builder.Build(); // register tokencache if callback provided tokenCacheCallback?.Invoke(publicClientApplication.UserTokenCache); authenticationType = ClientContextType.AzureADCredentials; }
/// <summary> /// Creates a new instance of the Authentication Manager to acquire authenticated ClientContexts. /// </summary> /// <param name="clientId">The client id of the Azure AD application to use for authentication</param> /// <param name="storeName">The name of the certificate store to find the certificate in.</param> /// <param name="storeLocation">The location of the certificate store to find the certificate in.</param> /// <param name="thumbPrint">The thumbprint of the certificate to use.</param> /// <param name="redirectUrl">Optional redirect URL to use for authentication as set up in the Azure AD Application</param> /// <param name="azureEnvironment">The azure environment to use. Defaults to AzureEnvironment.Production</param> /// <param name="tokenCacheCallback">If present, after setting up the base flow for authentication this callback will be called register a custom tokencache. See https://aka.ms/msal-net-token-cache-serialization.</param> public AuthenticationManager(string clientId, StoreName storeName, StoreLocation storeLocation, string thumbPrint, string redirectUrl = null, AzureEnvironment azureEnvironment = AzureEnvironment.Production, Action <ITokenCache> tokenCacheCallback = null) : this() { azureADEndPoint = GetAzureADLoginEndPoint(azureEnvironment); var certificate = Utilities.X509CertificateUtility.LoadCertificate(storeName, storeLocation, thumbPrint);; var builder = ConfidentialClientApplicationBuilder.Create(clientId).WithCertificate(certificate).WithAuthority($"{azureADEndPoint}/organizations/"); if (!string.IsNullOrEmpty(redirectUrl)) { builder = builder.WithRedirectUri(redirectUrl); } confidentialClientApplication = builder.Build(); // register tokencache if callback provided. ApptokenCache as AcquireTokenForClient is beind called to acquire tokens. tokenCacheCallback?.Invoke(confidentialClientApplication.AppTokenCache); authenticationType = ClientContextType.AzureADCertificate; }
private ClientContext BuildClientContext(IClientApplicationBase application, string siteUrl, string[] scopes, ClientContextType contextType) { var clientContext = new ClientContext(siteUrl) { DisableReturnValueCache = true }; clientContext.ExecutingWebRequest += (sender, args) => { AuthenticationResult ar = null; var accounts = application.GetAccountsAsync().GetAwaiter().GetResult(); if (accounts.Count() > 0) { ar = application.AcquireTokenSilent(scopes, accounts.First()).ExecuteAsync().GetAwaiter().GetResult(); } else { switch (contextType) { case ClientContextType.AzureADCertificate: { ar = ((IConfidentialClientApplication)application).AcquireTokenForClient(scopes).ExecuteAsync().GetAwaiter().GetResult(); break; } case ClientContextType.AzureADCredentials: { ar = ((IPublicClientApplication)application).AcquireTokenByUsernamePassword(scopes, username, password).ExecuteAsync().GetAwaiter().GetResult(); break; } case ClientContextType.AzureADInteractive: { ar = ((IPublicClientApplication)application).AcquireTokenInteractive(scopes).ExecuteAsync().GetAwaiter().GetResult(); break; } } } if (ar != null && ar.AccessToken != null) { args.WebRequestExecutor.RequestHeaders["Authorization"] = "Bearer " + ar.AccessToken; } }; ClientContextSettings clientContextSettings = new ClientContextSettings() { Type = contextType, SiteUrl = siteUrl, AuthenticationManager = this, }; clientContext.AddContextSettings(clientContextSettings); return(clientContext); }