internal static SPOnlineConnection InitiateAzureADNativeApplicationConnection(Uri url, string clientId, Uri redirectUri, int minimalHealthScore, int retryCount, int retryWait, int requestTimeout, bool skipAdminCheck = false) { Core.AuthenticationManager authManager = new Core.AuthenticationManager(); string appDataFolder = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); string configFile = Path.Combine(appDataFolder, "OfficeDevPnP.PowerShell\\tokencache.dat"); FileTokenCache cache = new FileTokenCache(configFile); var context = PnPClientContext.ConvertFrom(authManager.GetAzureADNativeApplicationAuthenticatedContext(url.ToString(), clientId, redirectUri, cache), retryCount, retryWait * 10000); 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 InitiateAzureADNativeApplicationConnection(Uri url, string clientId, Uri redirectUri, 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(); string appDataFolder = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); string configFile = Path.Combine(appDataFolder, "SharePointPnP.PowerShell\\tokencache.dat"); FileTokenCache cache = new FileTokenCache(configFile); var context = PnPClientContext.ConvertFrom(authManager.GetAzureADNativeApplicationAuthenticatedContext(url.ToString(), clientId, redirectUri, cache, azureEnvironment), retryCount, retryWait * 10000); 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.AADNativeApp); spoConnection.ConnectionMethod = Model.ConnectionMethod.AzureADNativeApplication; return(spoConnection); }
public async Task Used_For_PublicClientApplication_Succeeds() { var app = new PublicClientApplication(publicClientId, authority, FileTokenCache.GetUserCache(/* cacheFilePath: "d://temp//my.msalcache.bin", */ cacheFileProtect: false)); //var app = new PublicClientApplication(publicClientId, authority, RedisTokenCache.GetAppOrUserCache(uniqueId)); var accounts = await app.GetAccountsAsync(); AuthenticationResult authResult = null; try { // attempt to acquire valid token from cache or if expired use refresh token to silently acquire and cache new one authResult = await app.AcquireTokenSilentAsync(scopes, accounts.FirstOrDefault()); } catch (MsalUiRequiredException ex) { // A MsalUiRequiredException happened on AcquireTokenSilentAsync. This indicates you need to call AcquireTokenAsync to acquire a token. Debug.WriteLine($"MsalUiRequiredException: {ex.Message}"); try { //authResult = await app.AcquireTokenAsync(scopes); // not availabe in .net core environments var securePassword = new NetworkCredential("", password).SecurePassword; authResult = await app.AcquireTokenByUsernamePasswordAsync(scopes, username, securePassword); //authResult = await app.AcquireTokenWithDeviceCodeAsync(scopes, deviceCodeResult => //{ // // this will ouput the message telling automated test user where to go signin using browser and code to enter that will // // complete this signin process w/o needing to have access to credentials here in unit, integration or web/load test code // Debug.WriteLine(deviceCodeResult.Message); // return Task.FromResult(0); //}, CancellationToken.None); } catch (MsalException msalex) { // ErrorCode: invalid_grant, StatusCode: 400 implies you need app registrations | {public client} | api permissions | grant admin consent for {tenant name} Debug.WriteLine($"Error Acquiring Token:{System.Environment.NewLine}{msalex}"); } } catch (Exception ex) { Debug.WriteLine($"Error Acquiring Token Silently:{System.Environment.NewLine}{ex}"); } //var jwt = GetJsonWebToken(authResult.AccessToken); var actual = jwt["body"]["oid"].Value<string>(); //var jwt = new JwtSecurityTokenHandler().ReadJwtToken(authResult.AccessToken); var actual = jwt.Payload["oid"]; var actual = authResult.UniqueId; var expected = uniqueId; Assert.True(actual == expected); }
public async Task Used_For_ConfidentialClientApplication_Succeeds() { // msal acquiretokenbyauthorizationcodeasync -> // https://azure.microsoft.com/en-us/resources/samples/active-directory-dotnet-webapp-openidconnect-v2/ // https://github.com/AzureAD/microsoft-authentication-library-for-dotnet/wiki/Acquiring-tokens-with-authorization-codes-on-web-apps // app registrations | {confidential client} | api permissions | add a permission | see best practices for requesting permissions -> // https://docs.microsoft.com/en-us/azure/active-directory/develop/v1-permissions-and-consent var app = new ConfidentialClientApplication(confidentialClientId, confidentialClientRedirectUri, new ClientCredential(confidentialClientSecret), FileTokenCache.GetUserCache(/* cacheFilePath: "d://temp//my.msalcache.bin", */ cacheFileProtect: false), null); //new ClientCredential(confidentialClientSecret), RedisTokenCache.GetAppOrUserCache(uniqueId), null); var accounts = await app.GetAccountsAsync(); AuthenticationResult authResult = null; //scopes = new string[] { msftGraphResource }; //scopes = new string[] { "openid profile offline_access Mail.Read Mail.Send" }; try { // attempt to acquire valid token from cache or if expired use refresh token to silently acquire and cache new one authResult = await app.AcquireTokenSilentAsync(scopes, accounts.FirstOrDefault()); } catch (MsalUiRequiredException ex) { // A MsalUiRequiredException happened on AcquireTokenSilentAsync. This indicates you need to call AcquireTokenAsync to acquire a token. Debug.WriteLine($"MsalUiRequiredException: {ex.Message}"); try { authResult = await app.AcquireTokenByAuthorizationCodeAsync(authorizationCode, scopes); //authResult = await app.AcquireTokenOnBehalfOfAsync(scopes, new UserAssertion(accessToken)); } catch (MsalException msalex) { // ErrorCode: invalid_grant, StatusCode: 400 implies you need ??? // ErrorCode: invalid_scope StatusCode: 400 implies you need ??? Debug.WriteLine($"Error Acquiring Token:{System.Environment.NewLine}{msalex}"); } } catch (Exception ex) { Debug.WriteLine($"Error Acquiring Token Silently:{System.Environment.NewLine}{ex}"); } //var jwt = GetJsonWebToken(authResult.AccessToken); var actual = jwt["body"]["oid"].Value<string>(); //var jwt = new JwtSecurityTokenHandler().ReadJwtToken(authResult.AccessToken); var actual = jwt.Payload["oid"]; var actual = authResult.UniqueId; var expected = uniqueId; Assert.True(actual == expected); }
private void uxLinkLabelClearTokenCache_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { FileTokenCache.ClearAllFileTokenCaches(); }
/// <summary> /// Delete Token cache on Application Exit /// </summary> private static void DeleteTokenCacheOnApplicationExit() { FileTokenCache.ClearAllFileTokenCaches(); }