From 1c9147e1fd458805a29cf24a1c1667bba3bc13eb Mon Sep 17 00:00:00 2001 From: Bogdan Gavril Date: Tue, 14 May 2019 14:13:26 +0100 Subject: [PATCH] [System Browser] Refactor passing SeviceBundle in requestContext + test fixes --- LibsUnix.sln => LibsNetCore.sln | 77 ++++++++++- .../ApiConfig/Executors/AbstractExecutor.cs | 6 +- .../Executors/PublicClientExecutor.cs | 3 +- .../ClientApplicationBase.cs | 2 +- .../Core/RequestContext.cs | 25 +--- .../Http/HttpManager.cs | 30 ++-- .../Http/IHttpManager.cs | 8 +- .../AdfsOpenIdConfigurationEndpointManager.cs | 2 +- .../Internal/Requests/InteractiveRequest.cs | 2 +- .../OAuth2/OAuth2Client.cs | 9 +- .../Platforms/Android/AndroidWebUIFactory.cs | 8 +- .../AuthenticationContinuationHelper.cs | 19 ++- .../Platforms/Android/WebviewBase.cs | 5 +- .../AuthenticationAgentNSWindowController.cs | 21 +-- .../Platforms/Mac/MacUIFactory.cs | 4 +- ...MsalAuthenticationAgentUIViewController.cs | 36 ++--- .../WKWebNavigationDelegate.cs | 16 +-- .../Platforms/iOS/IosWebUIFactory.cs | 6 +- .../iOS/SystemWebview/SystemWebUI.cs | 4 +- .../Platforms/net45/NetDesktopWebUIFactory.cs | 2 +- .../WindowsFormsWebAuthenticationDialog.cs | 2 +- ...WindowsFormsWebAuthenticationDialogBase.cs | 10 +- .../OsBrowser/DefaultOsBrowserWebUi.cs | 13 +- .../netcore/OsBrowser/HttpResponseParser.cs | 12 +- .../Platforms/netcore/WebUIFactory.cs | 4 +- .../Platforms/netstandard13/WebUIFactory.cs | 2 +- .../Platforms/uap/WebUI.cs | 11 +- .../Platforms/uap/WebUIFactory.cs | 2 +- .../Interfaces/IPlatformProxy.cs | 2 +- .../TelemetryCore/XmsCliTelemInfoParser.cs | 8 +- .../UI/AuthorizationResult.cs | 130 ++++++++++-------- .../UI/CustomWebUiHandler.cs | 2 +- .../UI/IWebUIFactory.cs | 3 +- .../WsTrust/WsTrustWebRequestManager.cs | 10 +- .../Core/Helpers/TokenCacheExtensions.cs | 7 +- .../Core/Mocks/MockHttpAndServiceBundle.cs | 2 +- .../Mocks/MsalMockHelpers.cs | 2 +- .../AuthorityAliasesTests.cs | 5 +- .../BrokerParametersTest.cs | 4 +- .../CacheTests/TokenCacheNotificationTests.cs | 2 +- .../CacheTests/TokenCacheTests.cs | 42 +----- .../CacheTests/UnifiedCacheFormatTests.cs | 2 - .../CacheTests/UnifiedCacheTests.cs | 2 +- .../CoreTests/HttpTests/HttpManagerTests.cs | 11 +- .../InstanceTests/AadAuthorityTests.cs | 15 +- .../InstanceTests/AdfsAuthorityTests.cs | 24 ++-- .../InstanceTests/B2cAuthorityTests.cs | 9 +- .../OAuth2Tests/TokenResponseTests.cs | 2 +- .../CoreTests/Telemetry/XmsCliTelemTests.cs | 7 +- .../CoreTests/WsTrustTests/MexParserTests.cs | 8 +- .../CoreTests/WsTrustTests/WsTrustTests.cs | 4 +- .../PublicClientApplicationTests.cs | 52 +------ .../RequestsTests/SilentRequestTests.cs | 2 +- .../WebUITests/DefaultOsBrowserWebUiTests.cs | 23 ++-- .../WebUITests/HttpResponseParserTest.cs | 4 +- .../MsalUserAccessTokenControl.cs | 4 +- .../MsalUserRefreshTokenControl.cs | 2 +- tests/devapps/XForms/XForms/CachePage.xaml.cs | 5 +- 58 files changed, 365 insertions(+), 371 deletions(-) rename LibsUnix.sln => LibsNetCore.sln (81%) diff --git a/LibsUnix.sln b/LibsNetCore.sln similarity index 81% rename from LibsUnix.sln rename to LibsNetCore.sln index a122fd7159..6131d04c3e 100644 --- a/LibsUnix.sln +++ b/LibsNetCore.sln @@ -1,7 +1,7 @@  Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio 15 -VisualStudioVersion = 15.0.27130.2020 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.28803.352 MinimumVisualStudioVersion = 10.0.40219.1 Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "tests", "tests", "{9B0B5396-4D95-4C15-82ED-DC22B5A3123F}" EndProject @@ -28,6 +28,8 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "all", "all", "{2918FEF4-675 build\SolutionWideAnalyzerConfig.ruleset = build\SolutionWideAnalyzerConfig.ruleset EndProjectSection EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Identity.Test.Unit.netcore", "tests\Microsoft.Identity.Test.Unit.netcore\Microsoft.Identity.Test.Unit.netcore.csproj", "{5F6E69C1-5E78-4A8D-91F2-EF990CE3B2F7}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Ad-Hoc|Any CPU = Ad-Hoc|Any CPU @@ -347,6 +349,76 @@ Global {81DAEEBC-698C-48E8-BD7D-7BE33CE57177}.Release|x64.Build.0 = Release|Any CPU {81DAEEBC-698C-48E8-BD7D-7BE33CE57177}.Release|x86.ActiveCfg = Release|Any CPU {81DAEEBC-698C-48E8-BD7D-7BE33CE57177}.Release|x86.Build.0 = Release|Any CPU + {5F6E69C1-5E78-4A8D-91F2-EF990CE3B2F7}.Ad-Hoc|Any CPU.ActiveCfg = Debug|Any CPU + {5F6E69C1-5E78-4A8D-91F2-EF990CE3B2F7}.Ad-Hoc|Any CPU.Build.0 = Debug|Any CPU + {5F6E69C1-5E78-4A8D-91F2-EF990CE3B2F7}.Ad-Hoc|ARM.ActiveCfg = Debug|Any CPU + {5F6E69C1-5E78-4A8D-91F2-EF990CE3B2F7}.Ad-Hoc|ARM.Build.0 = Debug|Any CPU + {5F6E69C1-5E78-4A8D-91F2-EF990CE3B2F7}.Ad-Hoc|ARM64.ActiveCfg = Debug|Any CPU + {5F6E69C1-5E78-4A8D-91F2-EF990CE3B2F7}.Ad-Hoc|ARM64.Build.0 = Debug|Any CPU + {5F6E69C1-5E78-4A8D-91F2-EF990CE3B2F7}.Ad-Hoc|iPhone.ActiveCfg = Debug|Any CPU + {5F6E69C1-5E78-4A8D-91F2-EF990CE3B2F7}.Ad-Hoc|iPhone.Build.0 = Debug|Any CPU + {5F6E69C1-5E78-4A8D-91F2-EF990CE3B2F7}.Ad-Hoc|iPhoneSimulator.ActiveCfg = Debug|Any CPU + {5F6E69C1-5E78-4A8D-91F2-EF990CE3B2F7}.Ad-Hoc|iPhoneSimulator.Build.0 = Debug|Any CPU + {5F6E69C1-5E78-4A8D-91F2-EF990CE3B2F7}.Ad-Hoc|x64.ActiveCfg = Debug|Any CPU + {5F6E69C1-5E78-4A8D-91F2-EF990CE3B2F7}.Ad-Hoc|x64.Build.0 = Debug|Any CPU + {5F6E69C1-5E78-4A8D-91F2-EF990CE3B2F7}.Ad-Hoc|x86.ActiveCfg = Debug|Any CPU + {5F6E69C1-5E78-4A8D-91F2-EF990CE3B2F7}.Ad-Hoc|x86.Build.0 = Debug|Any CPU + {5F6E69C1-5E78-4A8D-91F2-EF990CE3B2F7}.AppStore|Any CPU.ActiveCfg = Debug|Any CPU + {5F6E69C1-5E78-4A8D-91F2-EF990CE3B2F7}.AppStore|Any CPU.Build.0 = Debug|Any CPU + {5F6E69C1-5E78-4A8D-91F2-EF990CE3B2F7}.AppStore|ARM.ActiveCfg = Debug|Any CPU + {5F6E69C1-5E78-4A8D-91F2-EF990CE3B2F7}.AppStore|ARM.Build.0 = Debug|Any CPU + {5F6E69C1-5E78-4A8D-91F2-EF990CE3B2F7}.AppStore|ARM64.ActiveCfg = Debug|Any CPU + {5F6E69C1-5E78-4A8D-91F2-EF990CE3B2F7}.AppStore|ARM64.Build.0 = Debug|Any CPU + {5F6E69C1-5E78-4A8D-91F2-EF990CE3B2F7}.AppStore|iPhone.ActiveCfg = Debug|Any CPU + {5F6E69C1-5E78-4A8D-91F2-EF990CE3B2F7}.AppStore|iPhone.Build.0 = Debug|Any CPU + {5F6E69C1-5E78-4A8D-91F2-EF990CE3B2F7}.AppStore|iPhoneSimulator.ActiveCfg = Debug|Any CPU + {5F6E69C1-5E78-4A8D-91F2-EF990CE3B2F7}.AppStore|iPhoneSimulator.Build.0 = Debug|Any CPU + {5F6E69C1-5E78-4A8D-91F2-EF990CE3B2F7}.AppStore|x64.ActiveCfg = Debug|Any CPU + {5F6E69C1-5E78-4A8D-91F2-EF990CE3B2F7}.AppStore|x64.Build.0 = Debug|Any CPU + {5F6E69C1-5E78-4A8D-91F2-EF990CE3B2F7}.AppStore|x86.ActiveCfg = Debug|Any CPU + {5F6E69C1-5E78-4A8D-91F2-EF990CE3B2F7}.AppStore|x86.Build.0 = Debug|Any CPU + {5F6E69C1-5E78-4A8D-91F2-EF990CE3B2F7}.Appveyor|Any CPU.ActiveCfg = Debug|Any CPU + {5F6E69C1-5E78-4A8D-91F2-EF990CE3B2F7}.Appveyor|Any CPU.Build.0 = Debug|Any CPU + {5F6E69C1-5E78-4A8D-91F2-EF990CE3B2F7}.Appveyor|ARM.ActiveCfg = Debug|Any CPU + {5F6E69C1-5E78-4A8D-91F2-EF990CE3B2F7}.Appveyor|ARM.Build.0 = Debug|Any CPU + {5F6E69C1-5E78-4A8D-91F2-EF990CE3B2F7}.Appveyor|ARM64.ActiveCfg = Debug|Any CPU + {5F6E69C1-5E78-4A8D-91F2-EF990CE3B2F7}.Appveyor|ARM64.Build.0 = Debug|Any CPU + {5F6E69C1-5E78-4A8D-91F2-EF990CE3B2F7}.Appveyor|iPhone.ActiveCfg = Debug|Any CPU + {5F6E69C1-5E78-4A8D-91F2-EF990CE3B2F7}.Appveyor|iPhone.Build.0 = Debug|Any CPU + {5F6E69C1-5E78-4A8D-91F2-EF990CE3B2F7}.Appveyor|iPhoneSimulator.ActiveCfg = Debug|Any CPU + {5F6E69C1-5E78-4A8D-91F2-EF990CE3B2F7}.Appveyor|iPhoneSimulator.Build.0 = Debug|Any CPU + {5F6E69C1-5E78-4A8D-91F2-EF990CE3B2F7}.Appveyor|x64.ActiveCfg = Debug|Any CPU + {5F6E69C1-5E78-4A8D-91F2-EF990CE3B2F7}.Appveyor|x64.Build.0 = Debug|Any CPU + {5F6E69C1-5E78-4A8D-91F2-EF990CE3B2F7}.Appveyor|x86.ActiveCfg = Debug|Any CPU + {5F6E69C1-5E78-4A8D-91F2-EF990CE3B2F7}.Appveyor|x86.Build.0 = Debug|Any CPU + {5F6E69C1-5E78-4A8D-91F2-EF990CE3B2F7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {5F6E69C1-5E78-4A8D-91F2-EF990CE3B2F7}.Debug|Any CPU.Build.0 = Debug|Any CPU + {5F6E69C1-5E78-4A8D-91F2-EF990CE3B2F7}.Debug|ARM.ActiveCfg = Debug|Any CPU + {5F6E69C1-5E78-4A8D-91F2-EF990CE3B2F7}.Debug|ARM.Build.0 = Debug|Any CPU + {5F6E69C1-5E78-4A8D-91F2-EF990CE3B2F7}.Debug|ARM64.ActiveCfg = Debug|Any CPU + {5F6E69C1-5E78-4A8D-91F2-EF990CE3B2F7}.Debug|ARM64.Build.0 = Debug|Any CPU + {5F6E69C1-5E78-4A8D-91F2-EF990CE3B2F7}.Debug|iPhone.ActiveCfg = Debug|Any CPU + {5F6E69C1-5E78-4A8D-91F2-EF990CE3B2F7}.Debug|iPhone.Build.0 = Debug|Any CPU + {5F6E69C1-5E78-4A8D-91F2-EF990CE3B2F7}.Debug|iPhoneSimulator.ActiveCfg = Debug|Any CPU + {5F6E69C1-5E78-4A8D-91F2-EF990CE3B2F7}.Debug|iPhoneSimulator.Build.0 = Debug|Any CPU + {5F6E69C1-5E78-4A8D-91F2-EF990CE3B2F7}.Debug|x64.ActiveCfg = Debug|Any CPU + {5F6E69C1-5E78-4A8D-91F2-EF990CE3B2F7}.Debug|x64.Build.0 = Debug|Any CPU + {5F6E69C1-5E78-4A8D-91F2-EF990CE3B2F7}.Debug|x86.ActiveCfg = Debug|Any CPU + {5F6E69C1-5E78-4A8D-91F2-EF990CE3B2F7}.Debug|x86.Build.0 = Debug|Any CPU + {5F6E69C1-5E78-4A8D-91F2-EF990CE3B2F7}.Release|Any CPU.ActiveCfg = Release|Any CPU + {5F6E69C1-5E78-4A8D-91F2-EF990CE3B2F7}.Release|Any CPU.Build.0 = Release|Any CPU + {5F6E69C1-5E78-4A8D-91F2-EF990CE3B2F7}.Release|ARM.ActiveCfg = Release|Any CPU + {5F6E69C1-5E78-4A8D-91F2-EF990CE3B2F7}.Release|ARM.Build.0 = Release|Any CPU + {5F6E69C1-5E78-4A8D-91F2-EF990CE3B2F7}.Release|ARM64.ActiveCfg = Release|Any CPU + {5F6E69C1-5E78-4A8D-91F2-EF990CE3B2F7}.Release|ARM64.Build.0 = Release|Any CPU + {5F6E69C1-5E78-4A8D-91F2-EF990CE3B2F7}.Release|iPhone.ActiveCfg = Release|Any CPU + {5F6E69C1-5E78-4A8D-91F2-EF990CE3B2F7}.Release|iPhone.Build.0 = Release|Any CPU + {5F6E69C1-5E78-4A8D-91F2-EF990CE3B2F7}.Release|iPhoneSimulator.ActiveCfg = Release|Any CPU + {5F6E69C1-5E78-4A8D-91F2-EF990CE3B2F7}.Release|iPhoneSimulator.Build.0 = Release|Any CPU + {5F6E69C1-5E78-4A8D-91F2-EF990CE3B2F7}.Release|x64.ActiveCfg = Release|Any CPU + {5F6E69C1-5E78-4A8D-91F2-EF990CE3B2F7}.Release|x64.Build.0 = Release|Any CPU + {5F6E69C1-5E78-4A8D-91F2-EF990CE3B2F7}.Release|x86.ActiveCfg = Release|Any CPU + {5F6E69C1-5E78-4A8D-91F2-EF990CE3B2F7}.Release|x86.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -357,6 +429,7 @@ Global {81DAEEBC-698C-48E8-BD7D-7BE33CE57177} = {34BE693E-3496-45A4-B1D2-D3A0E068EEDB} {A55E8D37-0DFA-48B6-B08D-AFE5947BBBAB} = {E19B0572-BBD7-424E-81D5-E59E6884EB3A} {2918FEF4-675D-4C4C-9118-F31148CCF11A} = {E19B0572-BBD7-424E-81D5-E59E6884EB3A} + {5F6E69C1-5E78-4A8D-91F2-EF990CE3B2F7} = {9B0B5396-4D95-4C15-82ED-DC22B5A3123F} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {020399A9-DC27-4B82-9CAA-EF488665AC27} diff --git a/src/Microsoft.Identity.Client/ApiConfig/Executors/AbstractExecutor.cs b/src/Microsoft.Identity.Client/ApiConfig/Executors/AbstractExecutor.cs index 0014d28be0..35e69c331b 100644 --- a/src/Microsoft.Identity.Client/ApiConfig/Executors/AbstractExecutor.cs +++ b/src/Microsoft.Identity.Client/ApiConfig/Executors/AbstractExecutor.cs @@ -4,7 +4,6 @@ using System; using System.Globalization; using Microsoft.Identity.Client.Core; -using Microsoft.Identity.Client.Internal; using Microsoft.Identity.Client.Utils; namespace Microsoft.Identity.Client.ApiConfig.Executors @@ -23,10 +22,7 @@ protected AbstractExecutor(IServiceBundle serviceBundle, ClientApplicationBase c protected RequestContext CreateRequestContextAndLogVersionInfo(Guid telemetryCorrelationId) { - var requestContext = new RequestContext( - _clientApplicationBase.AppConfig.ClientId, - MsalLogger.Create(telemetryCorrelationId, ServiceBundle.Config), - telemetryCorrelationId); + var requestContext = new RequestContext(ServiceBundle, telemetryCorrelationId); requestContext.Logger.Info( string.Format( diff --git a/src/Microsoft.Identity.Client/ApiConfig/Executors/PublicClientExecutor.cs b/src/Microsoft.Identity.Client/ApiConfig/Executors/PublicClientExecutor.cs index 1ec99b9fe7..13f813f0b2 100644 --- a/src/Microsoft.Identity.Client/ApiConfig/Executors/PublicClientExecutor.cs +++ b/src/Microsoft.Identity.Client/ApiConfig/Executors/PublicClientExecutor.cs @@ -138,8 +138,7 @@ public PublicClientExecutor(IServiceBundle serviceBundle, PublicClientApplicatio #endif return ServiceBundle.PlatformProxy.GetWebUiFactory().CreateAuthenticationDialog( coreUiParent, - requestContext, - ServiceBundle.PlatformProxy); + requestContext); } } diff --git a/src/Microsoft.Identity.Client/ClientApplicationBase.cs b/src/Microsoft.Identity.Client/ClientApplicationBase.cs index 24865cce7e..c703111080 100644 --- a/src/Microsoft.Identity.Client/ClientApplicationBase.cs +++ b/src/Microsoft.Identity.Client/ClientApplicationBase.cs @@ -153,7 +153,7 @@ internal static Authority GetAuthority(IServiceBundle serviceBundle, IAccount ac // For service calls, the request context should be created in the **Executor classes as part of request execution. private RequestContext CreateRequestContext(Guid telemetryCorrelationId) { - return new RequestContext(AppConfig.ClientId, MsalLogger.Create(telemetryCorrelationId, ServiceBundle.Config), telemetryCorrelationId); + return new RequestContext(ServiceBundle, telemetryCorrelationId); } /// diff --git a/src/Microsoft.Identity.Client/Core/RequestContext.cs b/src/Microsoft.Identity.Client/Core/RequestContext.cs index 1879085601..636b902a3e 100644 --- a/src/Microsoft.Identity.Client/Core/RequestContext.cs +++ b/src/Microsoft.Identity.Client/Core/RequestContext.cs @@ -9,28 +9,15 @@ namespace Microsoft.Identity.Client.Core { internal class RequestContext { - public RequestContext(string clientId, ICoreLogger logger, Guid telemetryCorrelationId) - { - ClientId = string.IsNullOrWhiteSpace(clientId) ? "unset_client_id" : clientId; - Logger = logger; - TelemetryCorrelationId = telemetryCorrelationId.AsMatsCorrelationId(); - } - public string TelemetryCorrelationId { get; } - public string ClientId { get; set; } + public ICoreLogger Logger { get; } + public IServiceBundle ServiceBundle { get; } - public ICoreLogger Logger { get; set; } - - public static RequestContext CreateForTest(IServiceBundle serviceBundle = null) + public RequestContext(IServiceBundle serviceBundle, Guid telemetryCorrelationId) { - var telemetryCorrelationId = Guid.NewGuid(); - - var logger = serviceBundle?.DefaultLogger ?? MsalLogger.Create( - telemetryCorrelationId, - null, - isDefaultPlatformLoggingEnabled: true); - - return new RequestContext(null, logger, telemetryCorrelationId); + ServiceBundle = serviceBundle ?? throw new ArgumentNullException(nameof(serviceBundle)); + Logger = MsalLogger.Create(telemetryCorrelationId, ServiceBundle.Config); + TelemetryCorrelationId = telemetryCorrelationId.AsMatsCorrelationId(); } } } diff --git a/src/Microsoft.Identity.Client/Http/HttpManager.cs b/src/Microsoft.Identity.Client/Http/HttpManager.cs index 43379a2036..8556166001 100644 --- a/src/Microsoft.Identity.Client/Http/HttpManager.cs +++ b/src/Microsoft.Identity.Client/Http/HttpManager.cs @@ -38,31 +38,31 @@ protected virtual HttpClient GetHttpClient() Uri endpoint, IDictionary headers, IDictionary bodyParameters, - RequestContext requestContext) + ICoreLogger logger) { HttpContent body = bodyParameters == null ? null : new FormUrlEncodedContent(bodyParameters); - return await SendPostAsync(endpoint, headers, body, requestContext).ConfigureAwait(false); + return await SendPostAsync(endpoint, headers, body, logger).ConfigureAwait(false); } public async Task SendPostAsync( Uri endpoint, IDictionary headers, HttpContent body, - RequestContext requestContext) + ICoreLogger logger) { - return await ExecuteWithRetryAsync(endpoint, headers, body, HttpMethod.Post, requestContext).ConfigureAwait(false); + return await ExecuteWithRetryAsync(endpoint, headers, body, HttpMethod.Post, logger).ConfigureAwait(false); } public async Task SendGetAsync( Uri endpoint, IDictionary headers, - RequestContext requestContext) + ICoreLogger logger) { - return await ExecuteWithRetryAsync(endpoint, headers, null, HttpMethod.Get, requestContext).ConfigureAwait(false); + return await ExecuteWithRetryAsync(endpoint, headers, null, HttpMethod.Get, logger).ConfigureAwait(false); } /// - /// Performs the POST request just like + /// Performs the POST request just like /// but does not throw a ServiceUnavailable service exception. Instead, it returns the associated /// with the request. /// @@ -70,9 +70,9 @@ protected virtual HttpClient GetHttpClient() Uri uri, Dictionary headers, StringContent body, - RequestContext requestContext) + ICoreLogger logger) { - return await ExecuteWithRetryAsync(uri, headers, body, HttpMethod.Post, requestContext, doNotThrow: true).ConfigureAwait(false); + return await ExecuteWithRetryAsync(uri, headers, body, HttpMethod.Post, logger, doNotThrow: true).ConfigureAwait(false); } private HttpRequestMessage CreateRequestMessage(Uri endpoint, IDictionary headers) @@ -95,7 +95,7 @@ private HttpRequestMessage CreateRequestMessage(Uri endpoint, IDictionary headers, HttpContent body, HttpMethod method, - RequestContext requestContext, + ICoreLogger logger, bool doNotThrow = false, bool retry = true) { @@ -120,7 +120,7 @@ private HttpRequestMessage CreateRequestMessage(Uri endpoint, IDictionary headers, IDictionary bodyParameters, - RequestContext requestContext); + ICoreLogger logger); Task SendPostAsync( Uri endpoint, IDictionary headers, HttpContent body, - RequestContext requestContext); + ICoreLogger logger); Task SendGetAsync( Uri endpoint, IDictionary headers, - RequestContext requestContext); + ICoreLogger logger); Task SendPostForceResponseAsync( Uri uri, Dictionary headers, StringContent body, - RequestContext requestContext); + ICoreLogger logger); } } diff --git a/src/Microsoft.Identity.Client/Instance/AdfsOpenIdConfigurationEndpointManager.cs b/src/Microsoft.Identity.Client/Instance/AdfsOpenIdConfigurationEndpointManager.cs index 87abd12c42..c426d26b2f 100644 --- a/src/Microsoft.Identity.Client/Instance/AdfsOpenIdConfigurationEndpointManager.cs +++ b/src/Microsoft.Identity.Client/Instance/AdfsOpenIdConfigurationEndpointManager.cs @@ -46,7 +46,7 @@ public AdfsOpenIdConfigurationEndpointManager(IServiceBundle serviceBundle) drsResponse.IdentityProviderService.PassiveAuthEndpoint.Host, resource); - var httpResponse = await _serviceBundle.HttpManager.SendGetAsync(new Uri(webFingerUrl), null, requestContext) + var httpResponse = await _serviceBundle.HttpManager.SendGetAsync(new Uri(webFingerUrl), null, requestContext.Logger) .ConfigureAwait(false); if (httpResponse.StatusCode != HttpStatusCode.OK) diff --git a/src/Microsoft.Identity.Client/Internal/Requests/InteractiveRequest.cs b/src/Microsoft.Identity.Client/Internal/Requests/InteractiveRequest.cs index 5572cd2b4b..f693ab4b9b 100644 --- a/src/Microsoft.Identity.Client/Internal/Requests/InteractiveRequest.cs +++ b/src/Microsoft.Identity.Client/Internal/Requests/InteractiveRequest.cs @@ -252,7 +252,7 @@ private void VerifyAuthorizationResult() if (_authorizationResult.Status != AuthorizationStatus.Success) { - throw new MsalServiceException(_authorizationResult.Error, _authorizationResult.ErrorDescription); + throw new MsalClientException(_authorizationResult.Error, _authorizationResult.ErrorDescription ?? "Unkown error."); } } } diff --git a/src/Microsoft.Identity.Client/OAuth2/OAuth2Client.cs b/src/Microsoft.Identity.Client/OAuth2/OAuth2Client.cs index 502e05c1bf..3ca29fcf34 100644 --- a/src/Microsoft.Identity.Client/OAuth2/OAuth2Client.cs +++ b/src/Microsoft.Identity.Client/OAuth2/OAuth2Client.cs @@ -87,12 +87,12 @@ internal async Task ExecuteRequestAsync(Uri endPoint, HttpMethod method, R { if (method == HttpMethod.Post) { - response = await _httpManager.SendPostAsync(endpointUri, _headers, _bodyParameters, requestContext) + response = await _httpManager.SendPostAsync(endpointUri, _headers, _bodyParameters, requestContext.Logger) .ConfigureAwait(false); } else { - response = await _httpManager.SendGetAsync(endpointUri, _headers, requestContext).ConfigureAwait(false); + response = await _httpManager.SendGetAsync(endpointUri, _headers, requestContext.Logger).ConfigureAwait(false); } httpEvent.HttpResponseStatus = (int)response.StatusCode; @@ -109,7 +109,10 @@ internal async Task ExecuteRequestAsync(Uri endPoint, HttpMethod method, R if (headersAsDictionary.ContainsKey("x-ms-clitelem") && headersAsDictionary["x-ms-clitelem"] != null) { - XmsCliTelemInfo xmsCliTeleminfo = new XmsCliTelemInfoParser().ParseXMsTelemHeader(headersAsDictionary["x-ms-clitelem"], requestContext); + XmsCliTelemInfo xmsCliTeleminfo = new XmsCliTelemInfoParser().ParseXMsTelemHeader( + headersAsDictionary["x-ms-clitelem"], + requestContext.Logger); + if (xmsCliTeleminfo != null) { httpEvent.TokenAge = xmsCliTeleminfo.TokenAge; diff --git a/src/Microsoft.Identity.Client/Platforms/Android/AndroidWebUIFactory.cs b/src/Microsoft.Identity.Client/Platforms/Android/AndroidWebUIFactory.cs index 5e521cf1c6..15acfa2b91 100644 --- a/src/Microsoft.Identity.Client/Platforms/Android/AndroidWebUIFactory.cs +++ b/src/Microsoft.Identity.Client/Platforms/Android/AndroidWebUIFactory.cs @@ -12,17 +12,17 @@ namespace Microsoft.Identity.Client.Platforms.Android [global::Android.Runtime.Preserve(AllMembers = true)] internal class AndroidWebUIFactory : IWebUIFactory { - public IWebUI CreateAuthenticationDialog(CoreUIParent coreUIParent, RequestContext requestContext, IPlatformProxy platformProxy) + public IWebUI CreateAuthenticationDialog(CoreUIParent parent, RequestContext requestContext) { - if (coreUIParent.UseEmbeddedWebview) + if (parent.UseEmbeddedWebview) { - return new EmbeddedWebUI(coreUIParent) + return new EmbeddedWebUI(parent) { RequestContext = requestContext }; } - return new SystemWebUI(coreUIParent) + return new SystemWebUI(parent) { RequestContext = requestContext }; diff --git a/src/Microsoft.Identity.Client/Platforms/Android/AuthenticationContinuationHelper.cs b/src/Microsoft.Identity.Client/Platforms/Android/AuthenticationContinuationHelper.cs index f0599de1a2..a6b337a801 100644 --- a/src/Microsoft.Identity.Client/Platforms/Android/AuthenticationContinuationHelper.cs +++ b/src/Microsoft.Identity.Client/Platforms/Android/AuthenticationContinuationHelper.cs @@ -29,13 +29,10 @@ public static void SetAuthenticationContinuationEventArgs(int requestCode, Resul { // TODO(migration): how can a public static method get access to the proper ClientRequestBase to wire into the logger and appropriate requestcontext? // Can we move this call to be somewhere on the ClientApplicationBase or something else that's wired into that? - RequestContext requestContext = new RequestContext(null, MsalLogger.Create(Guid.Empty, null), Guid.Empty); - - requestContext.Logger.Info(string.Format(CultureInfo.InvariantCulture, "Received Activity Result({0})", (int)resultCode)); - AuthorizationResult authorizationResult = null; - - int code = (int)resultCode; + var logger = MsalLogger.Create(Guid.Empty, null); + logger.Info(string.Format(CultureInfo.InvariantCulture, "Received Activity Result({0})", (int)resultCode)); + AuthorizationResult authorizationResult; if (data.Action != null && data.Action.Equals("ReturnFromEmbeddedWebview", StringComparison.OrdinalIgnoreCase)) { authorizationResult = ProcessFromEmbeddedWebview(requestCode, resultCode, data); @@ -45,7 +42,7 @@ public static void SetAuthenticationContinuationEventArgs(int requestCode, Resul authorizationResult = ProcessFromSystemWebview(requestCode, resultCode, data); } - WebviewBase.SetAuthorizationResult(authorizationResult, requestContext); + WebviewBase.SetAuthorizationResult(authorizationResult, logger); } private static AuthorizationResult ProcessFromEmbeddedWebview(int requestCode, Result resultCode, Intent data) @@ -57,10 +54,10 @@ private static AuthorizationResult ProcessFromEmbeddedWebview(int requestCode, R case (int)Result.Canceled: - return new AuthorizationResult(AuthorizationStatus.UserCancel); + return AuthorizationResult.FromStatus(AuthorizationStatus.UserCancel); default: - return new AuthorizationResult(AuthorizationStatus.UnknownError); + return AuthorizationResult.FromStatus(AuthorizationStatus.UnknownError); } } @@ -72,10 +69,10 @@ private static AuthorizationResult ProcessFromSystemWebview(int requestCode, Res return AuthorizationResult.FromUri(data.GetStringExtra("com.microsoft.identity.client.finalUrl")); case AndroidConstants.Cancel: - return new AuthorizationResult(AuthorizationStatus.UserCancel); + return AuthorizationResult.FromStatus(AuthorizationStatus.UserCancel); default: - return new AuthorizationResult(AuthorizationStatus.UnknownError); + return AuthorizationResult.FromStatus(AuthorizationStatus.UnknownError); } } } diff --git a/src/Microsoft.Identity.Client/Platforms/Android/WebviewBase.cs b/src/Microsoft.Identity.Client/Platforms/Android/WebviewBase.cs index eb9b69a72d..994680fc90 100644 --- a/src/Microsoft.Identity.Client/Platforms/Android/WebviewBase.cs +++ b/src/Microsoft.Identity.Client/Platforms/Android/WebviewBase.cs @@ -5,6 +5,7 @@ using System.Threading; using System.Threading.Tasks; using Microsoft.Identity.Client.Core; +using Microsoft.Identity.Client.Internal; using Microsoft.Identity.Client.UI; namespace Microsoft.Identity.Client.Platforms.Android @@ -14,7 +15,7 @@ internal abstract class WebviewBase : IWebUI protected static SemaphoreSlim returnedUriReady; protected static AuthorizationResult authorizationResult; - public static void SetAuthorizationResult(AuthorizationResult authorizationResultInput, RequestContext requestContext) + public static void SetAuthorizationResult(AuthorizationResult authorizationResultInput, ICoreLogger logger) { if (returnedUriReady != null) { @@ -23,7 +24,7 @@ public static void SetAuthorizationResult(AuthorizationResult authorizationResul } else { - requestContext.Logger.Info("No pending request for response from web ui."); + logger.Info("No pending request for response from web ui."); } } diff --git a/src/Microsoft.Identity.Client/Platforms/Mac/AuthenticationAgentNSWindowController.cs b/src/Microsoft.Identity.Client/Platforms/Mac/AuthenticationAgentNSWindowController.cs index 8ea552f858..860f38b38a 100644 --- a/src/Microsoft.Identity.Client/Platforms/Mac/AuthenticationAgentNSWindowController.cs +++ b/src/Microsoft.Identity.Client/Platforms/Mac/AuthenticationAgentNSWindowController.cs @@ -32,7 +32,7 @@ internal class AuthenticationAgentNSWindowController public delegate void ReturnCodeCallback(AuthorizationResult result); public AuthenticationAgentNSWindowController(string url, string callback, ReturnCodeCallback callbackMethod) - : base ("PlaceholderNibNameToForceWindowLoad") + : base("PlaceholderNibNameToForceWindowLoad") { _url = url; _callback = callback; @@ -182,11 +182,10 @@ void DecidePolicyForNavigation(WebView webView, NSDictionary actionInformation, if (requestUrlString.StartsWith(BrokerConstants.BrowserExtPrefix, StringComparison.OrdinalIgnoreCase)) { - var result = new AuthorizationResult(AuthorizationStatus.ProtocolError) - { - Error = "Unsupported request", - ErrorDescription = "Server is redirecting client to browser. This behavior is not yet defined on Mac OS X." - }; + var result = AuthorizationResult.FromStatus( + AuthorizationStatus.ProtocolError, + "Unsupported request", + "Server is redirecting client to browser. This behavior is not yet defined on Mac OS X."); _callbackMethod(result); WebView.DecideIgnore(decisionToken); Close(); @@ -225,9 +224,11 @@ void DecidePolicyForNavigation(WebView webView, NSDictionary actionInformation, if (!request.Url.AbsoluteString.Equals("about:blank", StringComparison.CurrentCultureIgnoreCase) && !request.Url.Scheme.Equals("https", StringComparison.CurrentCultureIgnoreCase)) { - var result = new AuthorizationResult(AuthorizationStatus.ErrorHttp); - result.Error = MsalError.NonHttpsRedirectNotSupported; - result.ErrorDescription = MsalErrorMessage.NonHttpsRedirectNotSupported; + var result = AuthorizationResult.FromStatus( + AuthorizationStatus.ErrorHttp, + MsalError.NonHttpsRedirectNotSupported, + MsalErrorMessage.NonHttpsRedirectNotSupported); + _callbackMethod(result); WebView.DecideIgnore(decisionToken); Close(); @@ -247,7 +248,7 @@ public void FinishedLoad(WebView sender, WebFrame forFrame) void CancelAuthentication() { - _callbackMethod(new AuthorizationResult(AuthorizationStatus.UserCancel)); + _callbackMethod(AuthorizationResult.FromStatus(AuthorizationStatus.UserCancel)); } [Export("windowShouldClose:")] diff --git a/src/Microsoft.Identity.Client/Platforms/Mac/MacUIFactory.cs b/src/Microsoft.Identity.Client/Platforms/Mac/MacUIFactory.cs index 97d2a60c4b..cfed10e471 100644 --- a/src/Microsoft.Identity.Client/Platforms/Mac/MacUIFactory.cs +++ b/src/Microsoft.Identity.Client/Platforms/Mac/MacUIFactory.cs @@ -10,11 +10,11 @@ namespace Microsoft.Identity.Client.Platforms.Mac { internal class MacUIFactory : IWebUIFactory { - public IWebUI CreateAuthenticationDialog(CoreUIParent coreUIParent, RequestContext requestContext, IPlatformProxy platformProxy) + public IWebUI CreateAuthenticationDialog(CoreUIParent parent, RequestContext requestContext) { return new MacEmbeddedWebUI() { - CoreUIParent = coreUIParent, + CoreUIParent = parent, RequestContext = requestContext }; } diff --git a/src/Microsoft.Identity.Client/Platforms/iOS/EmbeddedWebview/MsalAuthenticationAgentUIViewController.cs b/src/Microsoft.Identity.Client/Platforms/iOS/EmbeddedWebview/MsalAuthenticationAgentUIViewController.cs index 00bbf21f4d..356b917464 100644 --- a/src/Microsoft.Identity.Client/Platforms/iOS/EmbeddedWebview/MsalAuthenticationAgentUIViewController.cs +++ b/src/Microsoft.Identity.Client/Platforms/iOS/EmbeddedWebview/MsalAuthenticationAgentUIViewController.cs @@ -14,59 +14,61 @@ namespace Microsoft.Identity.Client.Platforms.iOS.EmbeddedWebview [Foundation.Register("MsalAuthenticationAgentUIViewController")] internal class MsalAuthenticationAgentUIViewController : UIViewController { - private readonly string url; - public readonly string callback; - private WKWebView wkWebView; - - public readonly ReturnCodeCallback callbackMethod; - - public delegate void ReturnCodeCallback(AuthorizationResult result); + private readonly string _url; + private WKWebView _wkWebView; public MsalAuthenticationAgentUIViewController(string url, string callback, ReturnCodeCallback callbackMethod) { - this.url = url; - this.callback = callback; - this.callbackMethod = callbackMethod; + _url = url; + Callback = callback; + CallbackMethod = callbackMethod; NSUrlProtocol.RegisterClass(new ObjCRuntime.Class(typeof(CoreCustomUrlProtocol))); } + public delegate void ReturnCodeCallback(AuthorizationResult result); + + public ReturnCodeCallback CallbackMethod { get; } + + public string Callback { get; } + + public override void ViewDidLoad() { base.ViewDidLoad(); View.BackgroundColor = UIColor.White; - wkWebView = PrepareWKWebView(); + _wkWebView = PrepareWKWebView(); EvaluateJava(); - this.View.AddSubview(wkWebView); + this.View.AddSubview(_wkWebView); this.NavigationItem.LeftBarButtonItem = new UIBarButtonItem(UIBarButtonSystemItem.Cancel, CancelAuthentication); - wkWebView.LoadRequest(new NSUrlRequest(new NSUrl(this.url))); + _wkWebView.LoadRequest(new NSUrlRequest(new NSUrl(this._url))); } protected WKWebView PrepareWKWebView() { WKWebViewConfiguration wkconfg = new WKWebViewConfiguration() { }; - wkWebView = new WKWebView(View.Bounds, wkconfg) + _wkWebView = new WKWebView(View.Bounds, wkconfg) { UIDelegate = new WKWebNavigationDelegate.WKWebViewUIDelegate(this), NavigationDelegate = new WKWebNavigationDelegate(this), AutoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight }; - return wkWebView; + return _wkWebView; } private void EvaluateJava() { WKJavascriptEvaluationResult handler = HandleWKJavascriptEvaluationResult; - wkWebView.EvaluateJavaScript((NSString)@"navigator.userAgent", handler); + _wkWebView.EvaluateJavaScript((NSString)@"navigator.userAgent", handler); } private static void HandleWKJavascriptEvaluationResult(NSObject result, NSError err) @@ -85,7 +87,7 @@ private static void HandleWKJavascriptEvaluationResult(NSObject result, NSError public void CancelAuthentication(object sender, EventArgs e) { this.DismissViewController(true, () => - callbackMethod(new AuthorizationResult(AuthorizationStatus.UserCancel))); + CallbackMethod(AuthorizationResult.FromStatus(AuthorizationStatus.UserCancel))); } public override void DismissViewController(bool animated, Action completionHandler) diff --git a/src/Microsoft.Identity.Client/Platforms/iOS/EmbeddedWebview/WKWebNavigationDelegate.cs b/src/Microsoft.Identity.Client/Platforms/iOS/EmbeddedWebview/WKWebNavigationDelegate.cs index 01965f1aef..43b9731b51 100644 --- a/src/Microsoft.Identity.Client/Platforms/iOS/EmbeddedWebview/WKWebNavigationDelegate.cs +++ b/src/Microsoft.Identity.Client/Platforms/iOS/EmbeddedWebview/WKWebNavigationDelegate.cs @@ -46,11 +46,11 @@ public override void DecidePolicy(WKWebView webView, WKNavigationAction navigati return; } - if (requestUrlString.StartsWith(AuthenticationAgentUIViewController.callback, StringComparison.OrdinalIgnoreCase) || + if (requestUrlString.StartsWith(AuthenticationAgentUIViewController.Callback, StringComparison.OrdinalIgnoreCase) || requestUrlString.StartsWith(iOSBrokerConstants.BrowserExtInstallPrefix, StringComparison.OrdinalIgnoreCase)) { AuthenticationAgentUIViewController.DismissViewController(true, () => - AuthenticationAgentUIViewController.callbackMethod(AuthorizationResult.FromUri(requestUrlString))); + AuthenticationAgentUIViewController.CallbackMethod(AuthorizationResult.FromUri(requestUrlString))); decisionHandler(WKNavigationActionPolicy.Cancel); return; } @@ -78,12 +78,12 @@ public override void DecidePolicy(WKWebView webView, WKNavigationAction navigati if (!navigationAction.Request.Url.AbsoluteString.Equals(AboutBlankUri, StringComparison.OrdinalIgnoreCase) && !navigationAction.Request.Url.Scheme.Equals(Uri.UriSchemeHttps, StringComparison.OrdinalIgnoreCase)) { - AuthorizationResult result = new AuthorizationResult(AuthorizationStatus.ErrorHttp) - { - Error = MsalError.NonHttpsRedirectNotSupported, - ErrorDescription = MsalErrorMessage.NonHttpsRedirectNotSupported - }; - AuthenticationAgentUIViewController.DismissViewController(true, () => AuthenticationAgentUIViewController.callbackMethod(result)); + AuthorizationResult result = AuthorizationResult.FromStatus( + AuthorizationStatus.ErrorHttp, + MsalError.NonHttpsRedirectNotSupported, + MsalErrorMessage.NonHttpsRedirectNotSupported); + + AuthenticationAgentUIViewController.DismissViewController(true, () => AuthenticationAgentUIViewController.CallbackMethod(result)); decisionHandler(WKNavigationActionPolicy.Cancel); return; } diff --git a/src/Microsoft.Identity.Client/Platforms/iOS/IosWebUIFactory.cs b/src/Microsoft.Identity.Client/Platforms/iOS/IosWebUIFactory.cs index 3baa373f9c..9eaa5b8976 100644 --- a/src/Microsoft.Identity.Client/Platforms/iOS/IosWebUIFactory.cs +++ b/src/Microsoft.Identity.Client/Platforms/iOS/IosWebUIFactory.cs @@ -11,14 +11,14 @@ namespace Microsoft.Identity.Client.Platforms.iOS { internal class IosWebUIFactory : IWebUIFactory { - public IWebUI CreateAuthenticationDialog(CoreUIParent coreUIParent, RequestContext requestContext, IPlatformProxy platformProxy) + public IWebUI CreateAuthenticationDialog(CoreUIParent parent, RequestContext requestContext) { - if (coreUIParent.UseEmbeddedWebview) + if (parent.UseEmbeddedWebview) { return new EmbeddedWebUI() { RequestContext = requestContext, - CoreUIParent = coreUIParent + CoreUIParent = parent }; } diff --git a/src/Microsoft.Identity.Client/Platforms/iOS/SystemWebview/SystemWebUI.cs b/src/Microsoft.Identity.Client/Platforms/iOS/SystemWebview/SystemWebUI.cs index f5527789f4..86a7c1e967 100644 --- a/src/Microsoft.Identity.Client/Platforms/iOS/SystemWebview/SystemWebUI.cs +++ b/src/Microsoft.Identity.Client/Platforms/iOS/SystemWebview/SystemWebUI.cs @@ -133,7 +133,7 @@ public void ProcessCompletionHandlerError(NSError error) // The authorizationResult is set on the class and sent back to the InteractiveRequest // There it's processed in VerifyAuthorizationResult() and an MsalClientException // will be thrown. - authorizationResult = new AuthorizationResult(AuthorizationStatus.UserCancel); + authorizationResult = AuthorizationResult.FromStatus(AuthorizationStatus.UserCancel); returnedUriReady.Release(); } } @@ -145,7 +145,7 @@ public void DidFinish(SFSafariViewController controller) if (returnedUriReady != null) { - authorizationResult = new AuthorizationResult(AuthorizationStatus.UserCancel); + authorizationResult = AuthorizationResult.FromStatus(AuthorizationStatus.UserCancel); returnedUriReady.Release(); } } diff --git a/src/Microsoft.Identity.Client/Platforms/net45/NetDesktopWebUIFactory.cs b/src/Microsoft.Identity.Client/Platforms/net45/NetDesktopWebUIFactory.cs index 29a752aeec..4a9ad63478 100644 --- a/src/Microsoft.Identity.Client/Platforms/net45/NetDesktopWebUIFactory.cs +++ b/src/Microsoft.Identity.Client/Platforms/net45/NetDesktopWebUIFactory.cs @@ -9,7 +9,7 @@ namespace Microsoft.Identity.Client.Platforms.net45 { internal class NetDesktopWebUIFactory : IWebUIFactory { - public IWebUI CreateAuthenticationDialog(CoreUIParent parent, RequestContext requestContext, IPlatformProxy platformProxy) + public IWebUI CreateAuthenticationDialog(CoreUIParent parent, RequestContext requestContext) { if (parent.UseHiddenBrowser) { diff --git a/src/Microsoft.Identity.Client/Platforms/net45/WindowsFormsWebAuthenticationDialog.cs b/src/Microsoft.Identity.Client/Platforms/net45/WindowsFormsWebAuthenticationDialog.cs index 270349dc3a..868a8f120a 100644 --- a/src/Microsoft.Identity.Client/Platforms/net45/WindowsFormsWebAuthenticationDialog.cs +++ b/src/Microsoft.Identity.Client/Platforms/net45/WindowsFormsWebAuthenticationDialog.cs @@ -53,7 +53,7 @@ public void ShowBrowser() case DialogResult.OK: break; case DialogResult.Cancel: - Result = new AuthorizationResult(AuthorizationStatus.UserCancel); + Result = AuthorizationResult.FromStatus(AuthorizationStatus.UserCancel); break; default: throw CreateExceptionForAuthenticationUiFailed(_statusCode); diff --git a/src/Microsoft.Identity.Client/Platforms/net45/WindowsFormsWebAuthenticationDialogBase.cs b/src/Microsoft.Identity.Client/Platforms/net45/WindowsFormsWebAuthenticationDialogBase.cs index 2da31ef758..684ffc8c30 100644 --- a/src/Microsoft.Identity.Client/Platforms/net45/WindowsFormsWebAuthenticationDialogBase.cs +++ b/src/Microsoft.Identity.Client/Platforms/net45/WindowsFormsWebAuthenticationDialogBase.cs @@ -204,11 +204,9 @@ private bool CheckForClosingUrl(Uri url) { RequestContext.Logger.Error(string.Format(CultureInfo.InvariantCulture, "Redirection to non-HTTPS scheme ({0}) found! Webview will fail...", url.Scheme)); - Result = new AuthorizationResult(AuthorizationStatus.ErrorHttp) - { - Error = MsalError.NonHttpsRedirectNotSupported, - ErrorDescription = MsalErrorMessage.NonHttpsRedirectNotSupported - }; + Result = AuthorizationResult.FromStatus(AuthorizationStatus.ErrorHttp); + Result.Error = MsalError.NonHttpsRedirectNotSupported; + Result.ErrorDescription = MsalErrorMessage.NonHttpsRedirectNotSupported; readyToClose = true; } @@ -305,7 +303,7 @@ private void InitializeComponent() : Screen.PrimaryScreen; // Window height is set to 70% of the screen height. - int uiHeight = (int) (Math.Max(screen.WorkingArea.Height, 160) * 70.0 / DpiHelper.ZoomPercent); + int uiHeight = (int)(Math.Max(screen.WorkingArea.Height, 160) * 70.0 / DpiHelper.ZoomPercent); _webBrowserPanel = new Panel(); _webBrowserPanel.SuspendLayout(); SuspendLayout(); diff --git a/src/Microsoft.Identity.Client/Platforms/netcore/OsBrowser/DefaultOsBrowserWebUi.cs b/src/Microsoft.Identity.Client/Platforms/netcore/OsBrowser/DefaultOsBrowserWebUi.cs index 7fd642935b..9347d9f50a 100644 --- a/src/Microsoft.Identity.Client/Platforms/netcore/OsBrowser/DefaultOsBrowserWebUi.cs +++ b/src/Microsoft.Identity.Client/Platforms/netcore/OsBrowser/DefaultOsBrowserWebUi.cs @@ -39,12 +39,13 @@ internal class DefaultOsBrowserWebUi : IWebUI private readonly IPlatformProxy _platformProxy; public DefaultOsBrowserWebUi( + IPlatformProxy proxy, ICoreLogger logger, - IPlatformProxy platformProxy, /* for test */ ITcpInterceptor tcpInterceptor = null) { - _logger = logger; - _platformProxy = platformProxy; + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + _platformProxy = proxy ?? throw new ArgumentNullException(nameof(proxy)); + _tcpInterceptor = tcpInterceptor ?? new TcpInterceptor(_logger); } @@ -80,7 +81,10 @@ public void ValidateRedirectUri(Uri redirectUri) { throw new MsalClientException( MsalError.LoopbackRedirectUri, - "Only loopback redirect uri is supported with this WebUI. Configure http://localhost or http://localhost:port during app registration. See https://aka.ms/msal-net-os-browser for details"); + string.Format(CultureInfo.InvariantCulture, + "Only loopback redirect uri is supported, but {0} was found. " + + "Configure http://localhost or http://localhost:port both during app registration and when you create the PublicClientApplication object. " + + "See https://aka.ms/msal-net-os-browser for details", redirectUri.AbsoluteUri)); } int port = redirectUri.Port; @@ -93,7 +97,6 @@ public void ValidateRedirectUri(Uri redirectUri) } } - private async Task InterceptAuthorizationUriAsync( Uri authorizationUri, Uri redirectUri, diff --git a/src/Microsoft.Identity.Client/Platforms/netcore/OsBrowser/HttpResponseParser.cs b/src/Microsoft.Identity.Client/Platforms/netcore/OsBrowser/HttpResponseParser.cs index f0b7a9ed68..8e52101464 100644 --- a/src/Microsoft.Identity.Client/Platforms/netcore/OsBrowser/HttpResponseParser.cs +++ b/src/Microsoft.Identity.Client/Platforms/netcore/OsBrowser/HttpResponseParser.cs @@ -64,12 +64,12 @@ private static string ExtractQuery(string httpRequest, ICoreLogger logger) if (!match.Success || match.Groups.Count != 2) { logger.ErrorPii( - "Could not extract the query from the authrorization response: " + httpRequest, - "Could not extract the query from the authrorization response. Enable Pii on to see the request"); + "Could not extract the query from the authorization response: " + httpRequest, + "Could not extract the query from the authorization response. Enable Pii on to see the request"); throw new MsalClientException( MsalError.InvalidAuthorizationUri, - "Could not extract the query from the authrorization response - check Pii enabled logs for details"); + "Could not extract the query from the authorization response - check Pii enabled logs for details"); } return match.Groups[1].Value; @@ -83,12 +83,12 @@ private static string ExtractHost(string httpRequest, ICoreLogger logger) if (!match.Success || match.Groups.Count != 2) { logger.ErrorPii( - "Could not extract the host from the authrorization response: " + httpRequest, - "Could not extract the host from the authrorization response. Enable Pii on to see the request"); + "Could not extract the host from the authorization response: " + httpRequest, + "Could not extract the host from the authorization response. Enable Pii on to see the request"); throw new MsalClientException( MsalError.InvalidAuthorizationUri, - "Could not extract the host from the authrorization response - check Pii enabled logs for details"); + "Could not extract the host from the authorization response - check Pii enabled logs for details"); } return match.Groups[1].Value.Trim(); diff --git a/src/Microsoft.Identity.Client/Platforms/netcore/WebUIFactory.cs b/src/Microsoft.Identity.Client/Platforms/netcore/WebUIFactory.cs index bec061154f..d504ccde69 100644 --- a/src/Microsoft.Identity.Client/Platforms/netcore/WebUIFactory.cs +++ b/src/Microsoft.Identity.Client/Platforms/netcore/WebUIFactory.cs @@ -11,9 +11,9 @@ namespace Microsoft.Identity.Client.Platforms.netcore { internal class WebUIFactory : IWebUIFactory { - public IWebUI CreateAuthenticationDialog(CoreUIParent parent, RequestContext requestContext, IPlatformProxy platformProxy) + public IWebUI CreateAuthenticationDialog(CoreUIParent parent, RequestContext requestContext) { - return new DefaultOsBrowserWebUi(requestContext.Logger, platformProxy); + return new DefaultOsBrowserWebUi(requestContext.ServiceBundle.PlatformProxy, requestContext.Logger); } } } diff --git a/src/Microsoft.Identity.Client/Platforms/netstandard13/WebUIFactory.cs b/src/Microsoft.Identity.Client/Platforms/netstandard13/WebUIFactory.cs index ccc6f8681d..e81f71368a 100644 --- a/src/Microsoft.Identity.Client/Platforms/netstandard13/WebUIFactory.cs +++ b/src/Microsoft.Identity.Client/Platforms/netstandard13/WebUIFactory.cs @@ -10,7 +10,7 @@ namespace Microsoft.Identity.Client.Platforms.netstandard13 { internal class WebUIFactory : IWebUIFactory { - public IWebUI CreateAuthenticationDialog(CoreUIParent parent, RequestContext requestContext, IPlatformProxy platformProxy) + public IWebUI CreateAuthenticationDialog(CoreUIParent parent, RequestContext requestContext) { throw new PlatformNotSupportedException("Possible Cause: If you are using an XForms app, or generally a netstandard assembly, " + "make sure you add a reference to Microsoft.Identity.Client.dll from each platform assembly " + diff --git a/src/Microsoft.Identity.Client/Platforms/uap/WebUI.cs b/src/Microsoft.Identity.Client/Platforms/uap/WebUI.cs index 1424ea3e35..893911c548 100644 --- a/src/Microsoft.Identity.Client/Platforms/uap/WebUI.cs +++ b/src/Microsoft.Identity.Client/Platforms/uap/WebUI.cs @@ -104,23 +104,20 @@ private void ThrowOnNetworkDown() result = AuthorizationResult.FromUri(webAuthenticationResult.ResponseData); break; case WebAuthenticationStatus.ErrorHttp: - result = new AuthorizationResult(AuthorizationStatus.ErrorHttp) - { - Code = webAuthenticationResult.ResponseErrorDetail.ToString(CultureInfo.InvariantCulture) - }; + result = AuthorizationResult.FromStatus(AuthorizationStatus.ErrorHttp); + result.Code = webAuthenticationResult.ResponseErrorDetail.ToString(CultureInfo.InvariantCulture); break; case WebAuthenticationStatus.UserCancel: - result = new AuthorizationResult(AuthorizationStatus.UserCancel); + result = AuthorizationResult.FromStatus(AuthorizationStatus.UserCancel); break; default: - result = new AuthorizationResult(AuthorizationStatus.UnknownError); + result = AuthorizationResult.FromStatus(AuthorizationStatus.UnknownError); break; } return result; } - public void ValidateRedirectUri(Uri redirectUri) { RedirectUriHelper.Validate(redirectUri, usesSystemBrowser: false); diff --git a/src/Microsoft.Identity.Client/Platforms/uap/WebUIFactory.cs b/src/Microsoft.Identity.Client/Platforms/uap/WebUIFactory.cs index ecded20435..87574cd9b0 100644 --- a/src/Microsoft.Identity.Client/Platforms/uap/WebUIFactory.cs +++ b/src/Microsoft.Identity.Client/Platforms/uap/WebUIFactory.cs @@ -9,7 +9,7 @@ namespace Microsoft.Identity.Client.Platforms.uap { internal class WebUIFactory : IWebUIFactory { - public IWebUI CreateAuthenticationDialog(CoreUIParent parent, RequestContext requestContext, IPlatformProxy platformProxy) + public IWebUI CreateAuthenticationDialog(CoreUIParent parent, RequestContext requestContext) { return new WebUI(parent, requestContext); } diff --git a/src/Microsoft.Identity.Client/PlatformsCommon/Interfaces/IPlatformProxy.cs b/src/Microsoft.Identity.Client/PlatformsCommon/Interfaces/IPlatformProxy.cs index dcea388bf0..9a9b64e09b 100644 --- a/src/Microsoft.Identity.Client/PlatformsCommon/Interfaces/IPlatformProxy.cs +++ b/src/Microsoft.Identity.Client/PlatformsCommon/Interfaces/IPlatformProxy.cs @@ -96,7 +96,7 @@ internal interface IPlatformProxy void /* for test */ SetFeatureFlags(IFeatureFlags featureFlags); /// - /// Open an url using the OS default browser. + /// Go to a Url using the OS default browser. /// Task StartDefaultOsBrowserAsync(string url); } diff --git a/src/Microsoft.Identity.Client/TelemetryCore/XmsCliTelemInfoParser.cs b/src/Microsoft.Identity.Client/TelemetryCore/XmsCliTelemInfoParser.cs index aba6fd83ab..8f35182d37 100644 --- a/src/Microsoft.Identity.Client/TelemetryCore/XmsCliTelemInfoParser.cs +++ b/src/Microsoft.Identity.Client/TelemetryCore/XmsCliTelemInfoParser.cs @@ -15,7 +15,7 @@ internal class XmsCliTelemInfoParser private const int TokenAgeIndex = 3; private const int SpeInfoIndex = 4; - internal XmsCliTelemInfo ParseXMsTelemHeader(string headerValue, RequestContext requestContext) + internal XmsCliTelemInfo ParseXMsTelemHeader(string headerValue, ICoreLogger logger) { if (string.IsNullOrEmpty(headerValue)) { @@ -25,7 +25,7 @@ internal XmsCliTelemInfo ParseXMsTelemHeader(string headerValue, RequestContext string[] headerSegments = headerValue.Split(','); if (headerSegments.Length == 0) { - requestContext.Logger.Warning( + logger.Warning( FormatLogMessage(TelemetryError.XmsCliTelemMalformed, headerValue)); return null; } @@ -38,7 +38,7 @@ internal XmsCliTelemInfo ParseXMsTelemHeader(string headerValue, RequestContext if (!string.Equals(headerVersion, ExpectedCliTelemHeaderVersion)) { - requestContext.Logger.Warning( + logger.Warning( FormatLogMessage(TelemetryError.XmsUnrecognizedHeaderVersion, headerVersion)); return xMsTelemetryInfo; } @@ -46,7 +46,7 @@ internal XmsCliTelemInfo ParseXMsTelemHeader(string headerValue, RequestContext MatchCollection formatMatcher = MatchHeaderToExpectedFormat(headerValue); if (formatMatcher.Count < 1) { - requestContext.Logger.Warning( + logger.Warning( FormatLogMessage(TelemetryError.XmsCliTelemMalformed, headerValue)); return xMsTelemetryInfo; } diff --git a/src/Microsoft.Identity.Client/UI/AuthorizationResult.cs b/src/Microsoft.Identity.Client/UI/AuthorizationResult.cs index 20c5e2c1d7..37fedd252a 100644 --- a/src/Microsoft.Identity.Client/UI/AuthorizationResult.cs +++ b/src/Microsoft.Identity.Client/UI/AuthorizationResult.cs @@ -21,58 +21,13 @@ internal enum AuthorizationStatus [DataContract] internal class AuthorizationResult { - internal AuthorizationResult(AuthorizationStatus status) - { - Status = status; - - if (Status == AuthorizationStatus.UserCancel) - { - Error = MsalError.AuthenticationCanceledError; -#if ANDROID - ErrorDescription = MsalErrorMessage.AuthenticationCanceledAndroid; -#else - ErrorDescription = MsalErrorMessage.AuthenticationCanceled; -#endif - } - else if (Status == AuthorizationStatus.UnknownError) - { - Error = MsalError.UnknownError; - ErrorDescription = MsalErrorMessage.Unknown; - } - } - - public AuthorizationStatus Status { get; private set; } - - [DataMember] - public string Code { get; set; } - - [DataMember] - public string Error { get; set; } - - [DataMember] - public string ErrorDescription { get; set; } - - [DataMember] - public string CloudInstanceHost { get; set; } - - /// - /// A string that is added to each Authroization Request and is expected to be sent back along with the - /// authorization code. MSAL is responsible for validating that the state sent is identical to the state received. - /// - /// - /// This is in addition to PKCE, which is validated by the server to ensure that the system redeeming the auth code - /// is the same as the system who asked for it. It protects against XSRF https://openid.net/specs/openid-connect-core-1_0.html - /// - public string State { get; set; } - public static AuthorizationResult FromUri(string webAuthenticationResult) { if (String.IsNullOrWhiteSpace(webAuthenticationResult)) { - return CreateFailedAuthResult( - MsalError.AuthenticationFailed, - MsalErrorMessage.AuthorizationServerInvalidResponse, //TODO: bogavril - different error message ? - AuthorizationStatus.UnknownError); + return FromStatus(AuthorizationStatus.UnknownError, + MsalError.AuthenticationFailed, + MsalErrorMessage.AuthorizationServerInvalidResponse); } var resultUri = new Uri(webAuthenticationResult); @@ -82,28 +37,26 @@ public static AuthorizationResult FromUri(string webAuthenticationResult) if (string.IsNullOrWhiteSpace(resultData)) { - return CreateFailedAuthResult( + return FromStatus(AuthorizationStatus.UnknownError, MsalError.AuthenticationFailed, - MsalErrorMessage.AuthorizationServerInvalidResponse, //TODO: bogavril - different error message ? - AuthorizationStatus.UnknownError); + MsalErrorMessage.AuthorizationServerInvalidResponse); } - // RemoveAccount the leading '?' first Dictionary uriParams = CoreHelpers.ParseKeyValueList(resultData.Substring(1), '&', true, null); if (uriParams.ContainsKey(TokenResponseClaim.Error)) { - return CreateFailedAuthResult( + return FromStatus(AuthorizationStatus.ProtocolError, uriParams[TokenResponseClaim.Error], uriParams.ContainsKey(TokenResponseClaim.ErrorDescription) ? uriParams[TokenResponseClaim.ErrorDescription] - : null, - AuthorizationStatus.ProtocolError); + : null); } - var result = new AuthorizationResult(AuthorizationStatus.Success); + var result = new AuthorizationResult(); + result.Status = AuthorizationStatus.Success; if (uriParams.ContainsKey(OAuth2Parameter.State)) { @@ -125,22 +78,77 @@ public static AuthorizationResult FromUri(string webAuthenticationResult) } else { - return CreateFailedAuthResult( + return FromStatus( + AuthorizationStatus.UnknownError, MsalError.AuthenticationFailed, - MsalErrorMessage.AuthorizationServerInvalidResponse, //TODO: bogavril - different error message ? - AuthorizationStatus.UnknownError); + MsalErrorMessage.AuthorizationServerInvalidResponse); + } + + return result; + } + + internal static AuthorizationResult FromStatus(AuthorizationStatus status) + { + if (status == AuthorizationStatus.Success) + { + throw new InvalidOperationException("Use the FromUri builder"); + } + + var result = new AuthorizationResult() { Status = status }; + + if (status == AuthorizationStatus.UserCancel) + { + result.Error = MsalError.AuthenticationCanceledError; +#if ANDROID + result.ErrorDescription = MsalErrorMessage.AuthenticationCanceledAndroid; +#else + result.ErrorDescription = MsalErrorMessage.AuthenticationCanceled; +#endif + } + else if (status == AuthorizationStatus.UnknownError) + { + result.Error = MsalError.UnknownError; + result.ErrorDescription = MsalErrorMessage.Unknown; } return result; } - private static AuthorizationResult CreateFailedAuthResult(string error, string errorDescription, AuthorizationStatus status) + public static AuthorizationResult FromStatus(AuthorizationStatus status, string error, string errorDescription) { - return new AuthorizationResult(status) + return new AuthorizationResult() { + Status = status, Error = error, ErrorDescription = errorDescription, }; } + + public AuthorizationStatus Status { get; private set; } + + [DataMember] + public string Code { get; set; } + + [DataMember] + public string Error { get; set; } + + [DataMember] + public string ErrorDescription { get; set; } + + [DataMember] + public string CloudInstanceHost { get; set; } + + /// + /// A string that is added to each Authroization Request and is expected to be sent back along with the + /// authorization code. MSAL is responsible for validating that the state sent is identical to the state received. + /// + /// + /// This is in addition to PKCE, which is validated by the server to ensure that the system redeeming the auth code + /// is the same as the system who asked for it. It protects against XSRF https://openid.net/specs/openid-connect-core-1_0.html + /// + public string State { get; set; } + + + } } diff --git a/src/Microsoft.Identity.Client/UI/CustomWebUiHandler.cs b/src/Microsoft.Identity.Client/UI/CustomWebUiHandler.cs index 10e3b64223..949fd35633 100644 --- a/src/Microsoft.Identity.Client/UI/CustomWebUiHandler.cs +++ b/src/Microsoft.Identity.Client/UI/CustomWebUiHandler.cs @@ -61,7 +61,7 @@ public CustomWebUiHandler(ICustomWebUi customWebUi) catch (OperationCanceledException) { requestContext.Logger.Info(LogMessages.CustomWebUiOperationCancelled); - return new AuthorizationResult(AuthorizationStatus.UserCancel); + return AuthorizationResult.FromStatus(AuthorizationStatus.UserCancel); } catch (Exception ex) { diff --git a/src/Microsoft.Identity.Client/UI/IWebUIFactory.cs b/src/Microsoft.Identity.Client/UI/IWebUIFactory.cs index bdb7e1b639..7c10672923 100644 --- a/src/Microsoft.Identity.Client/UI/IWebUIFactory.cs +++ b/src/Microsoft.Identity.Client/UI/IWebUIFactory.cs @@ -10,7 +10,6 @@ internal interface IWebUIFactory { IWebUI CreateAuthenticationDialog( CoreUIParent coreUIParent, - RequestContext requestContext, - IPlatformProxy platformProxy); + RequestContext requestContext); } } diff --git a/src/Microsoft.Identity.Client/WsTrust/WsTrustWebRequestManager.cs b/src/Microsoft.Identity.Client/WsTrust/WsTrustWebRequestManager.cs index 60e8cb0bbb..ac434d8793 100644 --- a/src/Microsoft.Identity.Client/WsTrust/WsTrustWebRequestManager.cs +++ b/src/Microsoft.Identity.Client/WsTrust/WsTrustWebRequestManager.cs @@ -27,7 +27,7 @@ public WsTrustWebRequestManager(IHttpManager httpManager) public async Task GetMexDocumentAsync(string federationMetadataUrl, RequestContext requestContext) { var uri = new UriBuilder(federationMetadataUrl); - HttpResponse httpResponse = await _httpManager.SendGetAsync(uri.Uri, null, requestContext).ConfigureAwait(false); + HttpResponse httpResponse = await _httpManager.SendGetAsync(uri.Uri, null, requestContext.Logger).ConfigureAwait(false); if (httpResponse.StatusCode != System.Net.HttpStatusCode.OK) { string message = string.Format(CultureInfo.CurrentCulture, @@ -65,7 +65,7 @@ public async Task GetMexDocumentAsync(string federationMetadataUrl, wsTrustRequest, Encoding.UTF8, headers["ContentType"]); - HttpResponse resp = await _httpManager.SendPostForceResponseAsync(wsTrustEndpoint.Uri, headers, body, requestContext).ConfigureAwait(false); + HttpResponse resp = await _httpManager.SendPostForceResponseAsync(wsTrustEndpoint.Uri, headers, body, requestContext.Logger).ConfigureAwait(false); if (resp.StatusCode != System.Net.HttpStatusCode.OK) { @@ -111,7 +111,11 @@ public async Task GetMexDocumentAsync(string federationMetadataUrl, var uri = new UriBuilder(userRealmUriPrefix + userName + "?api-version=1.0").Uri; - var httpResponse = await _httpManager.SendGetAsync(uri, MsalIdHelper.GetMsalIdParameters(requestContext.Logger), requestContext).ConfigureAwait(false); + var httpResponse = await _httpManager.SendGetAsync( + uri, + MsalIdHelper.GetMsalIdParameters(requestContext.Logger), + requestContext.Logger).ConfigureAwait(false); + return httpResponse.StatusCode == System.Net.HttpStatusCode.OK ? JsonHelper.DeserializeFromJson(httpResponse.Body) : null; diff --git a/tests/Microsoft.Identity.Test.Common/Core/Helpers/TokenCacheExtensions.cs b/tests/Microsoft.Identity.Test.Common/Core/Helpers/TokenCacheExtensions.cs index f02aef8dd1..74eec1da0c 100644 --- a/tests/Microsoft.Identity.Test.Common/Core/Helpers/TokenCacheExtensions.cs +++ b/tests/Microsoft.Identity.Test.Common/Core/Helpers/TokenCacheExtensions.cs @@ -45,9 +45,7 @@ public static void AddAccessTokenCacheItem(this ITokenCacheInternal tokenCache, public static void DeleteAccessToken( this ITokenCacheInternal tokenCache, - MsalAccessTokenCacheItem msalAccessTokenCacheItem, - MsalIdTokenCacheItem msalIdTokenCacheItem, - RequestContext requestContext) + MsalAccessTokenCacheItem msalAccessTokenCacheItem) { tokenCache.Semaphore.Wait(); try @@ -62,8 +60,7 @@ public static void AddAccessTokenCacheItem(this ITokenCacheInternal tokenCache, public static async Task GetAccountAsync( this ITokenCacheInternal tokenCache, - MsalRefreshTokenCacheItem refreshTokenCacheItem, - RequestContext requestContext) + MsalRefreshTokenCacheItem refreshTokenCacheItem) { IEnumerable accounts = await tokenCache.GetAllAccountsAsync().ConfigureAwait(false); diff --git a/tests/Microsoft.Identity.Test.Common/Core/Mocks/MockHttpAndServiceBundle.cs b/tests/Microsoft.Identity.Test.Common/Core/Mocks/MockHttpAndServiceBundle.cs index 534180365b..7c992824ed 100644 --- a/tests/Microsoft.Identity.Test.Common/Core/Mocks/MockHttpAndServiceBundle.cs +++ b/tests/Microsoft.Identity.Test.Common/Core/Mocks/MockHttpAndServiceBundle.cs @@ -55,7 +55,7 @@ public void Dispose() ServiceBundle, tokenCache, commonParameters, - RequestContext.CreateForTest(ServiceBundle)) + new RequestContext(ServiceBundle, Guid.NewGuid())) { Account = account, Authority = Authority.CreateAuthority(ServiceBundle, authority) diff --git a/tests/Microsoft.Identity.Test.Common/Mocks/MsalMockHelpers.cs b/tests/Microsoft.Identity.Test.Common/Mocks/MsalMockHelpers.cs index 494b6254a2..6af34fa2bc 100644 --- a/tests/Microsoft.Identity.Test.Common/Mocks/MsalMockHelpers.cs +++ b/tests/Microsoft.Identity.Test.Common/Mocks/MsalMockHelpers.cs @@ -46,7 +46,7 @@ public static void ConfigureMockWebUI(IPlatformProxy platformProxy, Authorizatio public static void ConfigureMockWebUI(IPlatformProxy platformProxy, MockWebUI webUi) { IWebUIFactory mockFactory = Substitute.For(); - mockFactory.CreateAuthenticationDialog(Arg.Any(), Arg.Any(), platformProxy).Returns(webUi); + mockFactory.CreateAuthenticationDialog(Arg.Any(), Arg.Any()).Returns(webUi); platformProxy.SetWebUiFactory(mockFactory); } } diff --git a/tests/Microsoft.Identity.Test.Unit.net45/AuthorityAliasesTests.cs b/tests/Microsoft.Identity.Test.Unit.net45/AuthorityAliasesTests.cs index 047a566158..e1cf5f1f68 100644 --- a/tests/Microsoft.Identity.Test.Unit.net45/AuthorityAliasesTests.cs +++ b/tests/Microsoft.Identity.Test.Unit.net45/AuthorityAliasesTests.cs @@ -16,6 +16,7 @@ using Microsoft.Identity.Test.Common.Core.Mocks; using Microsoft.Identity.Test.Common.Mocks; using Microsoft.VisualStudio.TestTools.UnitTesting; +using NSubstitute; namespace Microsoft.Identity.Test.Unit { @@ -151,7 +152,7 @@ public async Task AuthorityMigrationTestAsync() private async Task ValidateCacheEntitiesEnvironmentAsync(ITokenCacheInternal cache, string expectedEnvironment) { - var requestContext = RequestContext.CreateForTest(); + var logger = Substitute.For(); var accessTokens = await cache.GetAllAccessTokensAsync(true).ConfigureAwait(false); foreach (var at in accessTokens) { @@ -177,7 +178,7 @@ private async Task ValidateCacheEntitiesEnvironmentAsync(ITokenCacheInternal cac } IDictionary adalCache = - AdalCacheOperations.Deserialize(requestContext.Logger, cache.LegacyPersistence.LoadCache()); + AdalCacheOperations.Deserialize(logger, cache.LegacyPersistence.LoadCache()); foreach (KeyValuePair kvp in adalCache) { diff --git a/tests/Microsoft.Identity.Test.Unit.net45/BrokerParametersTest.cs b/tests/Microsoft.Identity.Test.Unit.net45/BrokerParametersTest.cs index 2ab64fb8fb..81443737f0 100644 --- a/tests/Microsoft.Identity.Test.Unit.net45/BrokerParametersTest.cs +++ b/tests/Microsoft.Identity.Test.Unit.net45/BrokerParametersTest.cs @@ -8,6 +8,7 @@ using Microsoft.Identity.Client.Core; using Microsoft.Identity.Client.Internal.Broker; using Microsoft.Identity.Client; +using System; namespace Microsoft.Identity.Test.Unit { @@ -47,7 +48,8 @@ public void BrokerInteractiveRequest_CreateBrokerParametersTest() Assert.AreEqual(MsalTestConstants.ScopeStr, brokerInteractiveRequest._brokerPayload[BrokerParameter.RequestScopes]); Assert.AreEqual(MsalTestConstants.ClientId, brokerInteractiveRequest._brokerPayload[BrokerParameter.ClientId]); - Assert.AreEqual(harness.ServiceBundle.DefaultLogger.CorrelationId.ToString(), brokerInteractiveRequest._brokerPayload[BrokerParameter.CorrelationId]); + Assert.IsFalse(String.IsNullOrEmpty(brokerInteractiveRequest._brokerPayload[BrokerParameter.CorrelationId])); + Assert.AreNotEqual(Guid.Empty.ToString(), brokerInteractiveRequest._brokerPayload[BrokerParameter.CorrelationId]); Assert.AreEqual(MsalIdHelper.GetMsalVersion(), brokerInteractiveRequest._brokerPayload[BrokerParameter.ClientVersion]); Assert.AreEqual("NO", brokerInteractiveRequest._brokerPayload[BrokerParameter.Force]); Assert.AreEqual(string.Empty, brokerInteractiveRequest._brokerPayload[BrokerParameter.Username]); diff --git a/tests/Microsoft.Identity.Test.Unit.net45/CacheTests/TokenCacheNotificationTests.cs b/tests/Microsoft.Identity.Test.Unit.net45/CacheTests/TokenCacheNotificationTests.cs index 01fcdde1e3..e3fa539577 100644 --- a/tests/Microsoft.Identity.Test.Unit.net45/CacheTests/TokenCacheNotificationTests.cs +++ b/tests/Microsoft.Identity.Test.Unit.net45/CacheTests/TokenCacheNotificationTests.cs @@ -136,7 +136,7 @@ public async Task TestSerializationViaAsync() MsalMockHelpers.ConfigureMockWebUI( pca.ServiceBundle.PlatformProxy, - new AuthorizationResult(AuthorizationStatus.Success, pca.AppConfig.RedirectUri + "?code=some-code")); + AuthorizationResult.FromUri(pca.AppConfig.RedirectUri + "?code=some-code")); harness.HttpManager.AddMockHandlerForTenantEndpointDiscovery(MsalTestConstants.AuthorityCommonTenant); harness.HttpManager.AddSuccessTokenResponseMockHandlerForPost(MsalTestConstants.AuthorityCommonTenant); diff --git a/tests/Microsoft.Identity.Test.Unit.net45/CacheTests/TokenCacheTests.cs b/tests/Microsoft.Identity.Test.Unit.net45/CacheTests/TokenCacheTests.cs index d09448e3b9..5456d6c5f6 100644 --- a/tests/Microsoft.Identity.Test.Unit.net45/CacheTests/TokenCacheTests.cs +++ b/tests/Microsoft.Identity.Test.Unit.net45/CacheTests/TokenCacheTests.cs @@ -787,7 +787,7 @@ public async Task SerializeDeserializeCacheTestAsync() MsalTokenResponse response = MsalTestConstants.CreateMsalTokenResponse(); - var requestContext = RequestContext.CreateForTest(serviceBundle); + var requestContext = new RequestContext(serviceBundle, Guid.NewGuid()); var requestParams = CreateAuthenticationRequestParameters(serviceBundle, requestContext: requestContext); requestParams.TenantUpdatedCanonicalAuthority = MsalTestConstants.AuthorityTestTenant; @@ -870,7 +870,7 @@ public void CacheB2CTokenTest() // creating IDToken with empty tenantID and displayableID/PreferredUserName for B2C scenario MsalTokenResponse response = MsalTestConstants.CreateMsalTokenResponse(); - var requestContext = RequestContext.CreateForTest(serviceBundle); + var requestContext = new RequestContext(serviceBundle, Guid.NewGuid()); var requestParams = CreateAuthenticationRequestParameters(serviceBundle, authority, requestContext: requestContext); requestParams.TenantUpdatedCanonicalAuthority = MsalTestConstants.AuthorityTestTenant; @@ -895,7 +895,7 @@ public void CacheB2CTokenTest() serviceBundle, null, commonParameters, - requestContext ?? RequestContext.CreateForTest(serviceBundle)) + requestContext ?? new RequestContext(serviceBundle, Guid.NewGuid())) { Authority = authority ?? Authority.CreateAuthority(serviceBundle, MsalTestConstants.AuthorityTestTenant) }; @@ -993,41 +993,5 @@ public void TestIsFociMember_EnvAlias() Assert.AreEqual(expectedResult, result, errMessage); Assert.AreEqual(1, cache.Accessor.GetAllAppMetadata().Count()); } - - /* - [TestMethod] - [TestCategory("TokenCacheTests")] - public void DeserializeCacheItemWithNoVersion() - { - string noVersionCacheEntry = "{\"client_id\":\"client_id\",\"client_info\":\"eyJ1aWQiOiJteS1VSUQiLCJ1dGlkIjoibXktVVRJRCJ9\",\"access_token\":\"access-token\",\"authority\":\"https:\\\\/\\\\/login.microsoftonline.com\\\\/home\\\\/\",\"expires_on\":1494025355,\"id_token\":\"someheader.eyJhdWQiOiAiZTg1NGE0YTctNmMzNC00NDljLWIyMzctZmM3YTI4MDkzZDg0IiwiaXNzIjogImh0dHBzOi8vbG9naW4ubWljcm9zb2Z0b25saW5lLmNvbS82YzNkNTFkZC1mMGU1LTQ5NTktYjRlYS1hODBjNGUzNmZlNWUvdjIuMC8iLCJpYXQiOiAxNDU1ODMzODI4LCJuYmYiOiAxNDU1ODMzODI4LCJleHAiOiAxNDU1ODM3NzI4LCJpcGFkZHIiOiAiMTMxLjEwNy4xNTkuMTE3IiwibmFtZSI6ICJNYXJycnJyaW8gQm9zc3kiLCJvaWQiOiAidW5pcXVlX2lkIiwicHJlZmVycmVkX3VzZXJuYW1lIjogImRpc3BsYXlhYmxlQGlkLmNvbSIsInN1YiI6ICJLNF9TR0d4S3FXMVN4VUFtaGc2QzFGNlZQaUZ6Y3gtUWQ4MGVoSUVkRnVzIiwidGlkIjogIm15LWlkcCIsInZlciI6ICIyLjAifQ.somesignature\",\"scope\":\"r1\\\\/scope1 r1\\\\/scope2\",\"token_type\":\"Bearer\",\"user_assertion_hash\":null}"; - - TokenCache cache = new TokenCache() - { - ClientId = TestConstants.ClientId - }; - cache.AddAccessTokenCacheItem(JsonHelper.DeserializeFromJson(noVersionCacheEntry)); - ICollection items = cache.GetAllAccessTokensForClient(new RequestContext(new MsalLogger(Guid.NewGuid(), null))); - Assert.AreEqual(1, items.Count); - MsalAccessTokenCacheItem item = items.First(); - Assert.AreEqual(0, item.Version); - } - - [TestMethod] - [TestCategory("TokenCacheTests")] - public void DeserializeCacheItemWithDifferentVersion() - { - string differentVersionEntry = "{\"client_id\":\"client_id\",\"client_info\":\"eyJ1aWQiOiJteS1VSUQiLCJ1dGlkIjoibXktVVRJRCJ9\",\"ver\":5,\"access_token\":\"access-token\",\"authority\":\"https:\\\\/\\\\/login.microsoftonline.com\\\\/home\\\\/\",\"expires_on\":1494025355,\"id_token\":\"someheader.eyJhdWQiOiAiZTg1NGE0YTctNmMzNC00NDljLWIyMzctZmM3YTI4MDkzZDg0IiwiaXNzIjogImh0dHBzOi8vbG9naW4ubWljcm9zb2Z0b25saW5lLmNvbS82YzNkNTFkZC1mMGU1LTQ5NTktYjRlYS1hODBjNGUzNmZlNWUvdjIuMC8iLCJpYXQiOiAxNDU1ODMzODI4LCJuYmYiOiAxNDU1ODMzODI4LCJleHAiOiAxNDU1ODM3NzI4LCJpcGFkZHIiOiAiMTMxLjEwNy4xNTkuMTE3IiwibmFtZSI6ICJNYXJycnJyaW8gQm9zc3kiLCJvaWQiOiAidW5pcXVlX2lkIiwicHJlZmVycmVkX3VzZXJuYW1lIjogImRpc3BsYXlhYmxlQGlkLmNvbSIsInN1YiI6ICJLNF9TR0d4S3FXMVN4VUFtaGc2QzFGNlZQaUZ6Y3gtUWQ4MGVoSUVkRnVzIiwidGlkIjogIm15LWlkcCIsInZlciI6ICIyLjAifQ.somesignature\",\"scope\":\"r1\\\\/scope1 r1\\\\/scope2\",\"token_type\":\"Bearer\",\"user_assertion_hash\":null}"; - - TokenCache cache = new TokenCache() - { - ClientId = TestConstants.ClientId - }; - cache.AddAccessTokenCacheItem(JsonHelper.DeserializeFromJson(differentVersionEntry)); - ICollection items = cache.GetAllAccessTokensForClient(new RequestContext(new MsalLogger(Guid.NewGuid(), null))); - Assert.AreEqual(1, items.Count); - MsalAccessTokenCacheItem item = items.First(); - Assert.AreEqual(5, item.Version); - } - */ } } diff --git a/tests/Microsoft.Identity.Test.Unit.net45/CacheTests/UnifiedCacheFormatTests.cs b/tests/Microsoft.Identity.Test.Unit.net45/CacheTests/UnifiedCacheFormatTests.cs index 6519da3350..853abfda57 100644 --- a/tests/Microsoft.Identity.Test.Unit.net45/CacheTests/UnifiedCacheFormatTests.cs +++ b/tests/Microsoft.Identity.Test.Unit.net45/CacheTests/UnifiedCacheFormatTests.cs @@ -75,8 +75,6 @@ private void Init(MockHttpManager httpManager) private string _expectedAccountCacheValue; private string _expectedRtCacheValue; - private readonly RequestContext _requestContext = RequestContext.CreateForTest(); - private void IntitTestData(string fileName) { using (StreamReader r = new StreamReader(fileName)) diff --git a/tests/Microsoft.Identity.Test.Unit.net45/CacheTests/UnifiedCacheTests.cs b/tests/Microsoft.Identity.Test.Unit.net45/CacheTests/UnifiedCacheTests.cs index 7fbd4e5513..c7082b80d4 100644 --- a/tests/Microsoft.Identity.Test.Unit.net45/CacheTests/UnifiedCacheTests.cs +++ b/tests/Microsoft.Identity.Test.Unit.net45/CacheTests/UnifiedCacheTests.cs @@ -61,7 +61,7 @@ public void UnifiedCache_MsalStoresToAndReadRtFromAdalCache() Assert.IsTrue(adalCacheDictionary.Count == 1); - var requestContext = RequestContext.CreateForTest(app.ServiceBundle); + var requestContext = new RequestContext(app.ServiceBundle, Guid.NewGuid()); var accounts = app.UserTokenCacheInternal.GetAccountsAsync( MsalTestConstants.AuthorityCommonTenant, requestContext).Result; foreach (IAccount account in accounts) diff --git a/tests/Microsoft.Identity.Test.Unit.net45/CoreTests/HttpTests/HttpManagerTests.cs b/tests/Microsoft.Identity.Test.Unit.net45/CoreTests/HttpTests/HttpManagerTests.cs index 4fd3c1d12c..328bf74d6e 100644 --- a/tests/Microsoft.Identity.Test.Unit.net45/CoreTests/HttpTests/HttpManagerTests.cs +++ b/tests/Microsoft.Identity.Test.Unit.net45/CoreTests/HttpTests/HttpManagerTests.cs @@ -13,6 +13,7 @@ using Microsoft.Identity.Test.Common.Core.Mocks; using Microsoft.VisualStudio.TestTools.UnitTesting; using Microsoft.Identity.Test.Common; +using NSubstitute; namespace Microsoft.Identity.Test.Unit.CoreTests.HttpTests { @@ -115,7 +116,7 @@ public async Task TestSendGetWithHttp500TypeFailureAsync() var msalHttpResponse = await httpManager.SendGetAsync( new Uri(MsalTestConstants.AuthorityHomeTenant + "oauth2/token"), new Dictionary(), - RequestContext.CreateForTest()) + Substitute.For()) .ConfigureAwait(false); Assert.Fail("request should have failed"); } @@ -140,7 +141,7 @@ public async Task TestSendGetWithHttp500TypeFailure2Async() new Uri(MsalTestConstants.AuthorityHomeTenant + "oauth2/token"), new Dictionary(), new StringContent("body"), - RequestContext.CreateForTest()) + Substitute.For()) .ConfigureAwait(false); Assert.AreEqual(HttpStatusCode.BadGateway, msalHttpResponse.StatusCode); @@ -162,7 +163,7 @@ public async Task TestSendPostWithHttp500TypeFailureAsync() new Uri(MsalTestConstants.AuthorityHomeTenant + "oauth2/token"), new Dictionary(), (IDictionary)null, - RequestContext.CreateForTest()) + Substitute.For()) .ConfigureAwait(false); Assert.Fail("request should have failed"); } @@ -188,7 +189,7 @@ public async Task TestSendGetWithRetryOnTimeoutFailureAsync() var msalHttpResponse = await httpManager.SendGetAsync( new Uri(MsalTestConstants.AuthorityHomeTenant + "oauth2/token"), new Dictionary(), - RequestContext.CreateForTest()) + Substitute.For()) .ConfigureAwait(false); Assert.Fail("request should have failed"); } @@ -216,7 +217,7 @@ public async Task TestSendPostWithRetryOnTimeoutFailureAsync() new Uri(MsalTestConstants.AuthorityHomeTenant + "oauth2/token"), new Dictionary(), new Dictionary(), - RequestContext.CreateForTest()) + Substitute.For()) .ConfigureAwait(false); Assert.Fail("request should have failed"); } diff --git a/tests/Microsoft.Identity.Test.Unit.net45/CoreTests/InstanceTests/AadAuthorityTests.cs b/tests/Microsoft.Identity.Test.Unit.net45/CoreTests/InstanceTests/AadAuthorityTests.cs index 382aa78ac5..29284a5de7 100644 --- a/tests/Microsoft.Identity.Test.Unit.net45/CoreTests/InstanceTests/AadAuthorityTests.cs +++ b/tests/Microsoft.Identity.Test.Unit.net45/CoreTests/InstanceTests/AadAuthorityTests.cs @@ -72,7 +72,8 @@ public void SuccessfulValidationTest() var endpoints = resolver.ResolveEndpointsAsync( instance.AuthorityInfo, null, - RequestContext.CreateForTest(harness.ServiceBundle)).ConfigureAwait(false).GetAwaiter().GetResult(); + new RequestContext(harness.ServiceBundle, Guid.NewGuid())) + .GetAwaiter().GetResult(); Assert.AreEqual( "https://login.microsoftonline.com/6babcaad-604b-40ac-a9d7-9fd97c0b779f/oauth2/v2.0/authorize", @@ -109,7 +110,8 @@ public void ValidationOffSuccessTest() var endpoints = resolver.ResolveEndpointsAsync( instance.AuthorityInfo, null, - RequestContext.CreateForTest(harness.ServiceBundle)).ConfigureAwait(false).GetAwaiter().GetResult(); + new RequestContext(harness.ServiceBundle, Guid.NewGuid())) + .ConfigureAwait(false).GetAwaiter().GetResult(); Assert.AreEqual( "https://login.microsoftonline.com/6babcaad-604b-40ac-a9d7-9fd97c0b779f/oauth2/v2.0/authorize", @@ -160,7 +162,8 @@ public void FailedValidationTest() var endpoints = resolver.ResolveEndpointsAsync( instance.AuthorityInfo, null, - RequestContext.CreateForTest(harness.ServiceBundle)).ConfigureAwait(false).GetAwaiter().GetResult(); + new RequestContext(harness.ServiceBundle, Guid.NewGuid())) + .ConfigureAwait(false).GetAwaiter().GetResult(); Assert.Fail("validation should have failed here"); } @@ -201,7 +204,8 @@ public void FailedValidationMissingFieldsTest() var endpoints = resolver.ResolveEndpointsAsync( instance.AuthorityInfo, null, - RequestContext.CreateForTest(harness.ServiceBundle)).ConfigureAwait(false).GetAwaiter().GetResult(); + new RequestContext(harness.ServiceBundle, Guid.NewGuid())) + .ConfigureAwait(false).GetAwaiter().GetResult(); Assert.Fail("validation should have failed here"); } @@ -238,7 +242,8 @@ public void FailedTenantDiscoveryMissingEndpointsTest() var endpoints = resolver.ResolveEndpointsAsync( instance.AuthorityInfo, null, - RequestContext.CreateForTest(harness.ServiceBundle)).ConfigureAwait(false).GetAwaiter().GetResult(); + new RequestContext(harness.ServiceBundle, Guid.NewGuid())) + .ConfigureAwait(false).GetAwaiter().GetResult(); Assert.Fail("validation should have failed here"); } diff --git a/tests/Microsoft.Identity.Test.Unit.net45/CoreTests/InstanceTests/AdfsAuthorityTests.cs b/tests/Microsoft.Identity.Test.Unit.net45/CoreTests/InstanceTests/AdfsAuthorityTests.cs index 8b11eb9b51..4846515ca2 100644 --- a/tests/Microsoft.Identity.Test.Unit.net45/CoreTests/InstanceTests/AdfsAuthorityTests.cs +++ b/tests/Microsoft.Identity.Test.Unit.net45/CoreTests/InstanceTests/AdfsAuthorityTests.cs @@ -93,7 +93,8 @@ public void SuccessfulValidationUsingOnPremiseDrsTest() var endpoints = harness.ServiceBundle.AuthorityEndpointResolutionManager.ResolveEndpointsAsync( instance.AuthorityInfo, MsalTestConstants.FabrikamDisplayableId, - RequestContext.CreateForTest(harness.ServiceBundle)).ConfigureAwait(false).GetAwaiter().GetResult(); + new RequestContext(harness.ServiceBundle, Guid.NewGuid())) + .GetAwaiter().GetResult(); Assert.AreEqual("https://fs.contoso.com/adfs/oauth2/authorize/", endpoints.AuthorizationEndpoint); Assert.AreEqual("https://fs.contoso.com/adfs/oauth2/token/", endpoints.TokenEndpoint); @@ -107,7 +108,8 @@ public void SuccessfulValidationUsingOnPremiseDrsTest() endpoints = harness.ServiceBundle.AuthorityEndpointResolutionManager.ResolveEndpointsAsync( instance.AuthorityInfo, MsalTestConstants.FabrikamDisplayableId, - RequestContext.CreateForTest(harness.ServiceBundle)).ConfigureAwait(false).GetAwaiter().GetResult(); + new RequestContext(harness.ServiceBundle, Guid.NewGuid())) + .GetAwaiter().GetResult(); Assert.AreEqual("https://fs.contoso.com/adfs/oauth2/authorize/", endpoints.AuthorizationEndpoint); Assert.AreEqual("https://fs.contoso.com/adfs/oauth2/token/", endpoints.TokenEndpoint); @@ -182,7 +184,8 @@ public void SuccessfulValidationUsingCloudDrsFallbackTest() var endpoints = resolver.ResolveEndpointsAsync( instance.AuthorityInfo, MsalTestConstants.FabrikamDisplayableId, - RequestContext.CreateForTest(harness.ServiceBundle)).ConfigureAwait(false).GetAwaiter().GetResult(); + new RequestContext(harness.ServiceBundle, Guid.NewGuid())) + .GetAwaiter().GetResult(); Assert.AreEqual("https://fs.contoso.com/adfs/oauth2/authorize/", endpoints.AuthorizationEndpoint); Assert.AreEqual("https://fs.contoso.com/adfs/oauth2/token/", endpoints.TokenEndpoint); @@ -214,7 +217,8 @@ public void ValidationOffSuccessTest() var endpoints = resolver.ResolveEndpointsAsync( instance.AuthorityInfo, MsalTestConstants.FabrikamDisplayableId, - RequestContext.CreateForTest(harness.ServiceBundle)).ConfigureAwait(false).GetAwaiter().GetResult(); + new RequestContext(harness.ServiceBundle, Guid.NewGuid())) + .GetAwaiter().GetResult(); Assert.AreEqual("https://fs.contoso.com/adfs/oauth2/authorize/", endpoints.AuthorizationEndpoint); Assert.AreEqual("https://fs.contoso.com/adfs/oauth2/token/", endpoints.TokenEndpoint); @@ -267,7 +271,8 @@ public void FailedValidationTest() var endpoints = resolver.ResolveEndpointsAsync( instance.AuthorityInfo, MsalTestConstants.FabrikamDisplayableId, - RequestContext.CreateForTest(harness.ServiceBundle)).ConfigureAwait(false).GetAwaiter().GetResult(); + new RequestContext(harness.ServiceBundle, Guid.NewGuid())) + .GetAwaiter().GetResult(); Assert.Fail("ResolveEndpointsAsync should have failed here"); } catch (Exception exc) @@ -321,7 +326,8 @@ public void FailedValidationResourceNotInTrustedRealmTest() var endpoints = resolver.ResolveEndpointsAsync( instance.AuthorityInfo, MsalTestConstants.FabrikamDisplayableId, - RequestContext.CreateForTest(harness.ServiceBundle)).ConfigureAwait(false).GetAwaiter().GetResult(); + new RequestContext(harness.ServiceBundle, Guid.NewGuid())) + .GetAwaiter().GetResult(); Assert.Fail("ResolveEndpointsAsync should have failed here"); } catch (Exception exc) @@ -361,7 +367,8 @@ public void FailedValidationMissingFieldsInDrsResponseTest() var endpoints = resolver.ResolveEndpointsAsync( instance.AuthorityInfo, MsalTestConstants.FabrikamDisplayableId, - RequestContext.CreateForTest(harness.ServiceBundle)).ConfigureAwait(false).GetAwaiter().GetResult(); + new RequestContext(harness.ServiceBundle, Guid.NewGuid())) + .GetAwaiter().GetResult(); Assert.Fail("ResolveEndpointsAsync should have failed here"); } catch (Exception exc) @@ -396,7 +403,8 @@ public void FailedTenantDiscoveryMissingEndpointsTest() var endpoints = resolver.ResolveEndpointsAsync( instance.AuthorityInfo, MsalTestConstants.FabrikamDisplayableId, - RequestContext.CreateForTest(harness.ServiceBundle)).ConfigureAwait(false).GetAwaiter().GetResult(); + new RequestContext(harness.ServiceBundle, Guid.NewGuid())) + .GetAwaiter().GetResult(); Assert.Fail("validation should have failed here"); } catch (MsalServiceException exc) diff --git a/tests/Microsoft.Identity.Test.Unit.net45/CoreTests/InstanceTests/B2cAuthorityTests.cs b/tests/Microsoft.Identity.Test.Unit.net45/CoreTests/InstanceTests/B2cAuthorityTests.cs index c4e512725f..cb2594422a 100644 --- a/tests/Microsoft.Identity.Test.Unit.net45/CoreTests/InstanceTests/B2cAuthorityTests.cs +++ b/tests/Microsoft.Identity.Test.Unit.net45/CoreTests/InstanceTests/B2cAuthorityTests.cs @@ -44,7 +44,8 @@ public void NotEnoughPathSegmentsTest() var endpoints = resolver.ResolveEndpointsAsync( instance.AuthorityInfo, null, - RequestContext.CreateForTest(serviceBundle)).ConfigureAwait(false).GetAwaiter().GetResult(); + new RequestContext(serviceBundle, Guid.NewGuid())) + .GetAwaiter().GetResult(); Assert.Fail("test should have failed"); } catch (Exception exc) @@ -87,7 +88,8 @@ public void B2CLoginAuthorityCreateAuthority() var endpoints = resolver.ResolveEndpointsAsync( instance.AuthorityInfo, null, - RequestContext.CreateForTest(serviceBundle)).ConfigureAwait(false).GetAwaiter().GetResult(); + new RequestContext(serviceBundle, Guid.NewGuid())) + .GetAwaiter().GetResult(); Assert.AreEqual( "https://sometenantid.b2clogin.com/6babcaad-604b-40ac-a9d7-9fd97c0b779f/policy/oauth2/v2.0/authorize", @@ -126,7 +128,8 @@ public void B2CMicrosoftOnlineCreateAuthority() var endpoints = resolver.ResolveEndpointsAsync( instance.AuthorityInfo, null, - RequestContext.CreateForTest(harness.ServiceBundle)).ConfigureAwait(false).GetAwaiter().GetResult(); + new RequestContext(harness.ServiceBundle, Guid.NewGuid())) + .GetAwaiter().GetResult(); Assert.AreEqual( "https://login.microsoftonline.com/6babcaad-604b-40ac-a9d7-9fd97c0b779f/my-policy/oauth2/v2.0/authorize", diff --git a/tests/Microsoft.Identity.Test.Unit.net45/CoreTests/OAuth2Tests/TokenResponseTests.cs b/tests/Microsoft.Identity.Test.Unit.net45/CoreTests/OAuth2Tests/TokenResponseTests.cs index 7d64b6a9a5..09d73e23eb 100644 --- a/tests/Microsoft.Identity.Test.Unit.net45/CoreTests/OAuth2Tests/TokenResponseTests.cs +++ b/tests/Microsoft.Identity.Test.Unit.net45/CoreTests/OAuth2Tests/TokenResponseTests.cs @@ -53,7 +53,7 @@ public void JsonDeserializationTest() Task task = client.GetTokenAsync( new Uri(MsalTestConstants.AuthorityCommonTenant + "oauth2/v2.0/token"), - RequestContext.CreateForTest(harness.ServiceBundle)); + new RequestContext(harness.ServiceBundle, Guid.NewGuid())); MsalTokenResponse response = task.Result; Assert.IsNotNull(response); } diff --git a/tests/Microsoft.Identity.Test.Unit.net45/CoreTests/Telemetry/XmsCliTelemTests.cs b/tests/Microsoft.Identity.Test.Unit.net45/CoreTests/Telemetry/XmsCliTelemTests.cs index 37384c0dc5..e06a3b2da5 100644 --- a/tests/Microsoft.Identity.Test.Unit.net45/CoreTests/Telemetry/XmsCliTelemTests.cs +++ b/tests/Microsoft.Identity.Test.Unit.net45/CoreTests/Telemetry/XmsCliTelemTests.cs @@ -25,7 +25,6 @@ public void TestInitialize() // Methods in XmsCliTelemTests log errors when parsing response headers; _coreLogger = Substitute.For(); - _requestContext = new RequestContext(null, _coreLogger, Guid.Empty); } [TestMethod] @@ -39,7 +38,7 @@ public void XmsClientTelemInfoParseTest_XmsCliTelemInfoCorrectFormat() }; var xmsCliTeleminfo = - new XmsCliTelemInfoParser().ParseXMsTelemHeader(responseHeaders["x-ms-clitelem"], _requestContext); + new XmsCliTelemInfoParser().ParseXMsTelemHeader(responseHeaders["x-ms-clitelem"], _coreLogger); // Assert Assert.AreEqual(xmsCliTeleminfo.Version, "1"); @@ -60,7 +59,7 @@ public void XmsClientTelemInfoParseTest_IncorrectFormat() }; var xmsCliTeleminfo = - new XmsCliTelemInfoParser().ParseXMsTelemHeader(responseHeaders["x-ms-clitelem"], _requestContext); + new XmsCliTelemInfoParser().ParseXMsTelemHeader(responseHeaders["x-ms-clitelem"], _coreLogger); // Assert _coreLogger.Received().Warning( @@ -82,7 +81,7 @@ public void XmsClientTelemInfoParseTest_IncorrectHeaderVersion() }; var xmsCliTeleminfo = - new XmsCliTelemInfoParser().ParseXMsTelemHeader(responseHeaders["x-ms-clitelem"], _requestContext); + new XmsCliTelemInfoParser().ParseXMsTelemHeader(responseHeaders["x-ms-clitelem"], _coreLogger); // Assert _coreLogger.Received().Warning( diff --git a/tests/Microsoft.Identity.Test.Unit.net45/CoreTests/WsTrustTests/MexParserTests.cs b/tests/Microsoft.Identity.Test.Unit.net45/CoreTests/WsTrustTests/MexParserTests.cs index 5ddcc7ce01..5e10041dae 100644 --- a/tests/Microsoft.Identity.Test.Unit.net45/CoreTests/WsTrustTests/MexParserTests.cs +++ b/tests/Microsoft.Identity.Test.Unit.net45/CoreTests/WsTrustTests/MexParserTests.cs @@ -1,6 +1,7 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. +using System; using System.IO; using System.Net.Http; using System.Threading.Tasks; @@ -18,14 +19,12 @@ namespace Microsoft.Identity.Test.Unit.CoreTests.WsTrustTests [DeploymentItem(@"Resources\TestMex2005.xml")] public class MexParserTests { - private RequestContext _requestContext; public TestContext TestContext { get; set; } [TestInitialize] public void TestInitialize() { TestCommon.ResetInternalStaticCaches(); - _requestContext = RequestContext.CreateForTest(); } [TestMethod] @@ -65,7 +64,10 @@ public async Task MexEndpointFailsToResolveTestAsync() try { - await harness.ServiceBundle.WsTrustWebRequestManager.GetMexDocumentAsync("http://somehost", _requestContext).ConfigureAwait(false); + await harness.ServiceBundle.WsTrustWebRequestManager.GetMexDocumentAsync("http://somehost", + new RequestContext(harness.ServiceBundle, Guid.NewGuid()) + + ).ConfigureAwait(false); Assert.Fail("We expect an exception to be thrown here"); } catch (MsalException ex) diff --git a/tests/Microsoft.Identity.Test.Unit.net45/CoreTests/WsTrustTests/WsTrustTests.cs b/tests/Microsoft.Identity.Test.Unit.net45/CoreTests/WsTrustTests/WsTrustTests.cs index dacc034569..7c154d94ab 100644 --- a/tests/Microsoft.Identity.Test.Unit.net45/CoreTests/WsTrustTests/WsTrustTests.cs +++ b/tests/Microsoft.Identity.Test.Unit.net45/CoreTests/WsTrustTests/WsTrustTests.cs @@ -46,7 +46,7 @@ public async Task WsTrustRequestTestAsync() } }); - var requestContext = RequestContext.CreateForTest(harness.ServiceBundle); + var requestContext = new RequestContext(harness.ServiceBundle, Guid.NewGuid()); var wsTrustRequest = endpoint.BuildTokenRequestMessageWindowsIntegratedAuth("urn:federation:SomeAudience"); var wsTrustResponse = await harness.ServiceBundle.WsTrustWebRequestManager.GetWsTrustResponseAsync(endpoint, wsTrustRequest, requestContext) .ConfigureAwait(false); @@ -66,7 +66,7 @@ public async Task WsTrustRequestFailureTestAsync() { harness.HttpManager.AddMockHandlerContentNotFound(HttpMethod.Post, url: uri); - var requestContext = RequestContext.CreateForTest(harness.ServiceBundle); + var requestContext = new RequestContext(harness.ServiceBundle, Guid.NewGuid()); try { var message = endpoint.BuildTokenRequestMessageWindowsIntegratedAuth("urn:federation:SomeAudience"); diff --git a/tests/Microsoft.Identity.Test.Unit.net45/PublicApiTests/PublicClientApplicationTests.cs b/tests/Microsoft.Identity.Test.Unit.net45/PublicApiTests/PublicClientApplicationTests.cs index 79b9d0c691..23728a6ed2 100644 --- a/tests/Microsoft.Identity.Test.Unit.net45/PublicApiTests/PublicClientApplicationTests.cs +++ b/tests/Microsoft.Identity.Test.Unit.net45/PublicApiTests/PublicClientApplicationTests.cs @@ -662,9 +662,9 @@ public async Task AcquireTokenWithAuthenticationCanceledTestAsync() .BuildConcrete(); // Interactive call and user cancels authentication - MockWebUI ui = new MockWebUI() + var ui = new MockWebUI() { - MockResult = new AuthorizationResult(AuthorizationStatus.UserCancel) + MockResult = AuthorizationResult.FromStatus(AuthorizationStatus.UserCancel) }; httpManager.AddMockHandlerForTenantEndpointDiscovery(MsalTestConstants.AuthorityCommonTenant); @@ -726,7 +726,7 @@ public async Task AcquireTokenWithAccessDeniedErrorTestAsync() .ExecuteAsync(CancellationToken.None) .ConfigureAwait(false); } - catch (MsalServiceException exc) + catch (MsalClientException exc) { Assert.IsNotNull(exc); Assert.AreEqual("access_denied", exc.ErrorCode); @@ -1139,52 +1139,6 @@ public void EnsurePublicApiSurfaceExistsOnInterface() #endif -#if NET_CORE - - [TestMethod] - public async Task NetCore_AcquireToken_ThrowsPlatformNotSupportedAsync() - { - // Arrange - PublicClientApplication pca = PublicClientApplicationBuilder.Create(MsalTestConstants.ClientId).BuildConcrete(); - var account = new Account("a.b", null, null); - - // All interactive auth overloads - IEnumerable>> acquireTokenInteractiveMethods = new List>> - { - // without UI Parent - async () => await pca.AcquireTokenInteractive(MsalTestConstants.Scope).ExecuteAsync(CancellationToken.None).ConfigureAwait(false), - async () => await pca.AcquireTokenInteractive(MsalTestConstants.Scope).WithLoginHint("login hint").ExecuteAsync(CancellationToken.None).ConfigureAwait(false), - async () => await pca.AcquireTokenInteractive(MsalTestConstants.Scope).WithAccount(account).ExecuteAsync(CancellationToken.None).ConfigureAwait(false), - async () => await pca.AcquireTokenInteractive(MsalTestConstants.Scope).WithLoginHint("login hint").WithPrompt(Prompt.Consent).WithExtraQueryParameters("extra_query_params").ExecuteAsync(CancellationToken.None).ConfigureAwait(false), - async () => await pca.AcquireTokenInteractive(MsalTestConstants.Scope).WithAccount(account).WithPrompt(Prompt.Consent).WithExtraQueryParameters("extra_query_params").ExecuteAsync(CancellationToken.None).ConfigureAwait(false), - async () => await pca.AcquireTokenInteractive(MsalTestConstants.Scope) - .WithLoginHint("login hint") - .WithPrompt(Prompt.Consent) - .WithExtraQueryParameters("extra_query_params") - .WithExtraScopesToConsent(new[] {"extra scopes" }) - .WithAuthority(MsalTestConstants.AuthorityCommonTenant) - .ExecuteAsync(CancellationToken.None) - .ConfigureAwait(false), - - async () => await pca.AcquireTokenInteractive(MsalTestConstants.Scope) - .WithAccount(account) - .WithPrompt(Prompt.Consent) - .WithExtraQueryParameters("extra_query_params") - .WithExtraScopesToConsent(new[] {"extra scopes" }) - .WithAuthority(MsalTestConstants.AuthorityCommonTenant) - .ExecuteAsync(CancellationToken.None) - .ConfigureAwait(false), - - async () => await pca.AcquireTokenByIntegratedWindowsAuth(MsalTestConstants.Scope).ExecuteAsync(CancellationToken.None).ConfigureAwait(false) - }; - - // Act and Assert - foreach (var acquireTokenInteractiveMethod in acquireTokenInteractiveMethods) - { - await AssertException.TaskThrowsAsync(acquireTokenInteractiveMethod).ConfigureAwait(false); - } - } -#endif public static void CheckBuilderCommonMethods(AbstractAcquireTokenParameterBuilder builder) where T : AbstractAcquireTokenParameterBuilder { builder.WithAuthority(AadAuthorityAudience.AzureAdAndPersonalMicrosoftAccount, true) diff --git a/tests/Microsoft.Identity.Test.Unit.net45/RequestsTests/SilentRequestTests.cs b/tests/Microsoft.Identity.Test.Unit.net45/RequestsTests/SilentRequestTests.cs index 6fd7b655b1..6e2922a6ce 100644 --- a/tests/Microsoft.Identity.Test.Unit.net45/RequestsTests/SilentRequestTests.cs +++ b/tests/Microsoft.Identity.Test.Unit.net45/RequestsTests/SilentRequestTests.cs @@ -221,7 +221,7 @@ public void Dispose() ServiceBundle, cache, commonParameters, - RequestContext.CreateForTest(ServiceBundle)) + new RequestContext(ServiceBundle, Guid.NewGuid())) { Account = new Account(MsalTestConstants.UserIdentifier, MsalTestConstants.DisplayableId, null), }; diff --git a/tests/Microsoft.Identity.Test.Unit.net45/WebUITests/DefaultOsBrowserWebUiTests.cs b/tests/Microsoft.Identity.Test.Unit.net45/WebUITests/DefaultOsBrowserWebUiTests.cs index 4cc2d30397..67d048f627 100644 --- a/tests/Microsoft.Identity.Test.Unit.net45/WebUITests/DefaultOsBrowserWebUiTests.cs +++ b/tests/Microsoft.Identity.Test.Unit.net45/WebUITests/DefaultOsBrowserWebUiTests.cs @@ -27,18 +27,18 @@ public class DefaultOsBrowserWebUiTests private const string TestAuthorizationResponseUri = "http://localhost:50997/?code=OAQABAAIAAADCoMpjJXrxTq9VG9te-7FX1n0H3n1cOvvLstfUYt_wAqcm96iwQKYzTWLqkz44aUnx4mswa7tn53DFy03fIJie9zOUjk5y6R9vU-rhCSUTLTJR6wUdqsbZfqgRpcCHRPHgmOFk7c3MqJ6WF5Y9AfQgXLaXsZN5vy7ZqS9viU0-NXxKDuBx17yqsT0FPvuoO_0yEZkuVkwd_x_fuUpejHqmORRPfdS-rN6e-7TwfbpsjvUl_eZ2BbzOSJu9rRltWqK-cBVkBhmt3jYEXVWsuTFRD9GHPELscdMJxkwqeOyA8-Lt6zCskKQMq_aAwSPR34CxA9YXoLy-psqjeMDLA5ieP5rmdoNcGBPSXS-imNMKfFSxHN_df6rqpQCOShJ_SmuBFY6qfcARgXpAlobRiUHat-K5heDVJTude47uE_NCSdmRJVZzY1dOeVEJ6f6O1TgR8EHq_MOSyc9HTUU0CpYvf8zePZIjn4jFPv4CZwvdmc4sOCntWrPxxj0JfRval58-aueRgnyhkm9G23FG4oCWWjydaKp5EytHhyYYf_qztsycUkL3Z2Ox7brQ8_Sj1IQr14J3G2FUYgwjuvi6RYK3cvXPM6oUrhOlQcvx03y10xAtizogcA5UR2m8GIpDkm4GEMYX4yYcvBUI6y0qKHmjnZuS5UsymUhUbNG8kEsnI0WTODZ4zYlEHweTsTXq1QNawZqxAW-ZsQ9EbrEbuDFaybJtNYFuHkm1kUjUwpsbZXFLnTUI6CKKDNlUdvPpbiENgapB_p_AgLl3L5KihfY8AkVbVgHZVAcpDClEu_autQZa2jGvPEQka-oKpHqIFZbDEi4qB4yrkU_hDsjf-EqnIAA&state=901e7d87-6f49-4f9f-9fa7-e6b8c32d5b9595bc1797-dacc-4ff1-b9e9-0df81be286c7&session_state=1b37b349-61fe-4ad5-a049-9f8eadfded26"; private const int TestPort = 50997; - ICoreLogger _logger; ITcpInterceptor _tcpInterceptor; IPlatformProxy _platformProxy; + ICoreLogger _logger; [TestInitialize] public void TestInitialize() { TestCommon.ResetInternalStaticCaches(); - _logger = Substitute.For(); _tcpInterceptor = Substitute.For(); _platformProxy = Substitute.For(); + _logger = Substitute.For(); } [TestMethod] @@ -56,12 +56,13 @@ public async Task DefaultOsBrowserWebUi_HappyPath_Async() } [TestMethod] // TODO: bogavril - expect this case to be removed - MSAL should accept different port - public void DefaultOsBrowserWebUi_ReturnUriInvalid() + public async Task DefaultOsBrowserWebUi_ReturnUriInvalid_Async() { string differentPortRedirectUri = TestAuthorizationResponseUri.Replace(TestRedirectUri, "http://localhost:1111"); - MsalClientException ex = AssertException.TaskThrows(() => AcquireAuthCodeAsync( - responseUriString: differentPortRedirectUri)); + MsalClientException ex = await AssertException.TaskThrowsAsync( + () => AcquireAuthCodeAsync(responseUriString: differentPortRedirectUri)) + .ConfigureAwait(false); Assert.AreEqual(MsalError.LoopbackResponseUriMisatch, ex.ErrorCode); } @@ -72,8 +73,9 @@ public void DefaultOsBrowserWebUi_ReturnUriInvalid() string responseUriString = TestAuthorizationResponseUri) { // Arrange + var requestContext = new RequestContext(TestCommon.CreateDefaultServiceBundle(), Guid.NewGuid()); var responseUri = new Uri(responseUriString); - IWebUI webUI = new DefaultOsBrowserWebUi(_logger, _platformProxy, _tcpInterceptor); + IWebUI webUI = new DefaultOsBrowserWebUi(_platformProxy, _logger, _tcpInterceptor); _tcpInterceptor.ListenToSingleRequestAndRespondAsync( TestPort, @@ -85,7 +87,7 @@ public void DefaultOsBrowserWebUi_ReturnUriInvalid() AuthorizationResult authorizationResult = await webUI.AcquireAuthorizationAsync( new Uri(requestUri), new Uri(redirectUri), - RequestContext.CreateForTest(), + requestContext, CancellationToken.None).ConfigureAwait(false); // Assert that we opened the browser @@ -100,11 +102,9 @@ await _platformProxy.Received(1).StartDefaultOsBrowserAsync(requestUri) public void ValidateRedirectUri() { // Arrange - var logger = Substitute.For(); var tcpInterceptor = Substitute.For(); - var platformProxy = Substitute.For(); - IWebUI webUi = new DefaultOsBrowserWebUi(logger, platformProxy, tcpInterceptor); + IWebUI webUi = new DefaultOsBrowserWebUi(_platformProxy, _logger, tcpInterceptor); // Act webUi.ValidateRedirectUri(new Uri("http://localhost:12345")); @@ -123,10 +123,7 @@ private static void AssertInvalidRedirectUri(IWebUI webUI, string uri) var ex = AssertException.Throws(() => webUI.ValidateRedirectUri(new Uri(uri))); Assert.AreEqual(MsalError.LoopbackRedirectUri, ex.ErrorCode); } - } - - } #endif diff --git a/tests/Microsoft.Identity.Test.Unit.net45/WebUITests/HttpResponseParserTest.cs b/tests/Microsoft.Identity.Test.Unit.net45/WebUITests/HttpResponseParserTest.cs index 63d81fd3e7..1b260251fa 100644 --- a/tests/Microsoft.Identity.Test.Unit.net45/WebUITests/HttpResponseParserTest.cs +++ b/tests/Microsoft.Identity.Test.Unit.net45/WebUITests/HttpResponseParserTest.cs @@ -17,7 +17,7 @@ namespace Microsoft.Identity.Test.Unit.WebUITests public class HttpResponseParserTest { [TestMethod] - public void HappyPath() + public void CanParseValidHttpGet() { // Arrange const string ValidTcpMessage = @" @@ -42,7 +42,7 @@ public void HappyPath() } [TestMethod] - public void BadMessages() + public void WillRejectPostAndNoHost() { const string PostTcpMessage = @" {POST /?code=_some-code_ HTTP/1.1 diff --git a/tests/devapps/DesktopTestApp/MsalUserAccessTokenControl.cs b/tests/devapps/DesktopTestApp/MsalUserAccessTokenControl.cs index 081fbd4b3c..791a229398 100644 --- a/tests/devapps/DesktopTestApp/MsalUserAccessTokenControl.cs +++ b/tests/devapps/DesktopTestApp/MsalUserAccessTokenControl.cs @@ -47,9 +47,7 @@ private void expireAccessTokenButton_Click(object sender, System.EventArgs e) private void deleteAccessTokenButton_Click(object sender, EventArgs e) { - var requestContext = RequestContext.CreateForTest(); - - _cache.DeleteAccessToken(_item, null, requestContext); + _cache.DeleteAccessToken(_item); RefreshViewAsyncDelegate?.Invoke(); } } diff --git a/tests/devapps/DesktopTestApp/MsalUserRefreshTokenControl.cs b/tests/devapps/DesktopTestApp/MsalUserRefreshTokenControl.cs index 6735d13854..538330d4e4 100644 --- a/tests/devapps/DesktopTestApp/MsalUserRefreshTokenControl.cs +++ b/tests/devapps/DesktopTestApp/MsalUserRefreshTokenControl.cs @@ -29,7 +29,7 @@ internal MsalUserRefreshTokenControl(PublicClientApplication publicClient, MsalR _cache = publicClient.UserTokenCacheInternal; _rtItem = rtItem; - _accountItem = _cache.GetAccountAsync(_rtItem, RequestContext.CreateForTest()).GetAwaiter().GetResult(); // todo: yuck + _accountItem = _cache.GetAccountAsync(_rtItem).GetAwaiter().GetResult(); // todo: yuck upnLabel.Text = _accountItem.PreferredUsername; invalidateRefreshTokenBtn.Enabled = !_rtItem.Secret.Equals(GarbageRtValue, StringComparison.OrdinalIgnoreCase); diff --git a/tests/devapps/XForms/XForms/CachePage.xaml.cs b/tests/devapps/XForms/XForms/CachePage.xaml.cs index 031b03fa7a..1ffb0fbbe4 100644 --- a/tests/devapps/XForms/XForms/CachePage.xaml.cs +++ b/tests/devapps/XForms/XForms/CachePage.xaml.cs @@ -96,10 +96,7 @@ public void OnAtDelete(object sender, EventArgs e) var accessTokenCacheItem = (MsalAccessTokenCacheItem)mi.CommandParameter; var tokenCache = App.MsalPublicClient.UserTokenCacheInternal; - // todo pass idToken instead of null - var requestContext = RequestContext.CreateForTest(); - - tokenCache.DeleteAccessToken(accessTokenCacheItem, null, requestContext); + tokenCache.DeleteAccessToken(accessTokenCacheItem); RefreshCacheViewAsync().ConfigureAwait(true); }