예제 #1
0
        public void GetAuthorizationRequestUrlDuplicateParamsTest()
        {
            ConfidentialClientApplication app = new ConfidentialClientApplication(TestConstants.ClientId,
                                                                                  TestConstants.RedirectUri, new ClientCredential(TestConstants.ClientSecret),
                                                                                  new TokenCache(), new TokenCache())
            {
                ValidateAuthority = false
            };

            //add mock response for tenant endpoint discovery
            HttpMessageHandlerFactory.AddMockHandler(new MockHttpMessageHandler
            {
                Method          = HttpMethod.Get,
                ResponseMessage = MockHelpers.CreateOpenIdConfigurationResponse(app.Authority)
            });

            try
            {
                Task <Uri> task = app.GetAuthorizationRequestUrlAsync(TestConstants.Scope.AsArray(),
                                                                      TestConstants.DisplayableId, "[email protected]");
                Uri uri = task.Result;
                Assert.Fail("MSALException should be thrown here");
            }
            catch (Exception exc)
            {
                Assert.IsTrue(exc.InnerException is MsalException);
                Assert.AreEqual("duplicate_query_parameter", ((MsalException)exc.InnerException).ErrorCode);
                Assert.AreEqual("Duplicate query parameter 'login_hint' in extraQueryParameters",
                                ((MsalException)exc.InnerException).Message);
            }

            Assert.IsTrue(HttpMessageHandlerFactory.IsMocksQueueEmpty, "All mocks should have been consumed");
        }
        public void GetAuthorizationRequestUrlCustomRedirectUriTest()
        {
            ConfidentialClientApplication app = new ConfidentialClientApplication(TestConstants.DefaultClientId,
                                                                                  TestConstants.DefaultRedirectUri, new ClientCredential(TestConstants.DefaultClientSecret), new TokenCache());
            Task <Uri> task = app.GetAuthorizationRequestUrlAsync(TestConstants.DefaultScope.AsArray(),
                                                                  "custom://redirect-uri", TestConstants.DefaultDisplayableId, "extra=qp&prompt=none",
                                                                  TestConstants.ScopeForAnotherResource.AsArray(), TestConstants.DefaultAuthorityGuestTenant,
                                                                  TestConstants.DefaultPolicy);
            Uri uri = task.Result;

            Assert.IsNotNull(uri);
            Assert.IsTrue(uri.AbsoluteUri.StartsWith(TestConstants.DefaultAuthorityGuestTenant, StringComparison.CurrentCulture));
            Dictionary <string, string> qp = EncodingHelper.ParseKeyValueList(uri.Query.Substring(1), '&', true, null);

            Assert.IsNotNull(qp);
            Assert.AreEqual(12, qp.Count);
            Assert.AreEqual("r1/scope1 r1/scope2 r2/scope1 r2/scope2 openid offline_access", qp["scope"]);
            Assert.AreEqual(TestConstants.DefaultClientId, qp["client_id"]);
            Assert.AreEqual("code", qp["response_type"]);
            Assert.AreEqual("custom://redirect-uri", qp["redirect_uri"]);
            Assert.AreEqual(TestConstants.DefaultDisplayableId, qp["login_hint"]);
            Assert.AreEqual("MSAL.Desktop", qp["x-client-sku"]);
            Assert.IsFalse(string.IsNullOrEmpty(qp["x-client-ver"]));
            Assert.IsFalse(string.IsNullOrEmpty(qp["x-client-cpu"]));
            Assert.IsFalse(string.IsNullOrEmpty(qp["x-client-os"]));
            Assert.AreEqual("qp", qp["extra"]);
            Assert.AreEqual("none", qp["prompt"]);
            Assert.AreEqual(TestConstants.DefaultPolicy, qp["p"]);
        }
예제 #3
0
        public async Task GetAuthorizationRequestUrlNoRedirectUriTestAsync()
        {
            await RunWithMockHttpAsync(
                async (httpManager, serviceBundle, receiver) =>
            {
                httpManager.AddInstanceDiscoveryMockHandler();

                var app = new ConfidentialClientApplication(
                    serviceBundle,
                    MsalTestConstants.ClientId,
                    ClientApplicationBase.DefaultAuthority,
                    MsalTestConstants.RedirectUri,
                    new ClientCredential(MsalTestConstants.ClientSecret),
                    new TokenCache(),
                    new TokenCache())
                {
                    ValidateAuthority = false
                };

                httpManager.AddMockHandlerForTenantEndpointDiscovery(app.Authority);

                var uri = await app.GetAuthorizationRequestUrlAsync(
                    MsalTestConstants.Scope,
                    MsalTestConstants.DisplayableId,
                    null).ConfigureAwait(false);
                Assert.IsNotNull(uri);
                Dictionary <string, string> qp = CoreHelpers.ParseKeyValueList(uri.Query.Substring(1), '&', true, null);
                ValidateCommonQueryParams(qp);
                Assert.AreEqual("offline_access openid profile r1/scope1 r1/scope2", qp["scope"]);
            }).ConfigureAwait(false);
        }
        public static async Task <string> GetAuthUrlAsync(ConversationReference cf)
        {
            //encode the conversation reference to pass it to the callback controller
            //it will be use to resume the context after the Sign In process
            var extraQueryParameters = WebEncoders.Base64UrlEncode(System.Text.Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(cf)));

            //create client passing information about the registered application in Azure AD
            //registration is explained here https://docs.microsoft.com/en-us/azure/active-directory/develop/active-directory-v2-app-registration
            ConfidentialClientApplication client = new ConfidentialClientApplication(
                Environment.GetEnvironmentVariable("aad:ClientId"),
                "https://login.microsoftonline.com/" + Environment.GetEnvironmentVariable("aad:Tenant") + "/oauth2/v2.0",
                new Uri(Environment.GetEnvironmentVariable("aad:RedirectUrl")).ToString(),
                new ClientCredential(Environment.GetEnvironmentVariable("aad:ClientSecret")),
                null, null
                );

            List <string> listscopes = Environment.GetEnvironmentVariable("aad:Scopes").Split(',').ToList();

            //obtain the Authorization url
            var uri = await client.GetAuthorizationRequestUrlAsync(
                listscopes,
                null,
                $"state={extraQueryParameters}"
                );

            return(uri.ToString());
        }
예제 #5
0
        public async Task <string> GetAuthUrlAsync(AuthenticationOptions authOptions, string state)
        {
            var redirectUri = new Uri(authOptions.RedirectUrl);
            var tokenCache  = new AuthTokenCache().GetCacheInstance();
            var client      = new ConfidentialClientApplication(authOptions.ClientId, redirectUri.ToString(), new ClientCredential(authOptions.ClientSecret), tokenCache, null);
            var uri         = await client.GetAuthorizationRequestUrlAsync(authOptions.Scopes, null, $"state={state}");

            return(uri.ToString());
        }
예제 #6
0
        public async Task <IActionResult> AuthorizeAsync()
        {
            // 認証を行うための URL にリダイレクトします
            var clientCredential  = new ClientCredential(ClientSecret);
            var clientApplication = new ConfidentialClientApplication(ClientId, RedirectUrl, clientCredential, null, null);
            var requestUrl        = await clientApplication.GetAuthorizationRequestUrlAsync(new[] { Scope }, null, null);

            return(this.Redirect(requestUrl.ToString()));
        }
예제 #7
0
        public async Task <string> GetAuthUrlAsync(AuthenticationOptions authOptions, string state)
        {
            Uri redirectUri = new Uri(authOptions.RedirectUrl);
            InMemoryTokenCacheMSAL        tokenCache = new InMemoryTokenCacheMSAL();
            ConfidentialClientApplication client     = new ConfidentialClientApplication(authOptions.ClientId, redirectUri.ToString(),
                                                                                         new ClientCredential(authOptions.ClientSecret),
                                                                                         tokenCache);
            var uri = await client.GetAuthorizationRequestUrlAsync(authOptions.Scopes, null, $"state={state}");

            return(uri.ToString());
        }
        public static async Task <string> GenerateAuthorizationRequestUrl(string[] scopes, ConfidentialClientApplication cca, HttpContextBase httpcontext, UrlHelper url)
        {
            string signedInUserID          = ClaimsPrincipal.Current.FindFirst(System.IdentityModel.Claims.ClaimTypes.NameIdentifier).Value;
            string preferredUserName       = ClaimsPrincipal.Current.FindFirst("preferred_name").Value;
            Uri    oauthCodeProcessingPath = new Uri(httpcontext.Request.Url.GetLeftPart(UriPartial.Authority).ToString());
            string state    = GenerateState(httpcontext.Request.Url.ToString(), httpcontext, url, scopes);
            string tenantID = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;


            // 9188040d-6c67-4c5b-b112-36a304b66dad is the GUID that indicates that the user is a consumer user from a Microsoft account. All personal account will have this tenant id.

            string domain_hint     = (tenantID == "9188040d-6c67-4c5b-b112-36a304b66dad") ? "customers" : "organizations";
            Uri    authzMessageUri = await cca.GetAuthorizationRequestUrlAsync(scopes, oauthCodeProcessingPath.ToString(), preferredUserName, state == null?null : "&state" + state + "&domain_hint" + domain_hint, null, cca.Authority);

            return(authzMessageUri.ToString());
        }
예제 #9
0
        public void GetAuthorizationRequestUrlCustomRedirectUriTest()
        {
            ConfidentialClientApplication app =
                new ConfidentialClientApplication(TestConstants.ClientId, TestConstants.AuthorityGuestTenant,
                                                  TestConstants.RedirectUri, new ClientCredential(TestConstants.ClientSecret),
                                                  new TokenCache(), new TokenCache())
            {
                ValidateAuthority = false
            };

            //add mock response for tenant endpoint discovery
            HttpMessageHandlerFactory.AddMockHandler(new MockHttpMessageHandler
            {
                Method          = HttpMethod.Get,
                ResponseMessage = MockHelpers.CreateOpenIdConfigurationResponse(app.Authority)
            });

            const string CustomRedirectUri = "custom://redirect-uri";
            Task <Uri>   task = app.GetAuthorizationRequestUrlAsync(TestConstants.Scope.AsArray(),
                                                                    CustomRedirectUri, TestConstants.DisplayableId, "extra=qp",
                                                                    TestConstants.ScopeForAnotherResource.AsArray(), TestConstants.AuthorityGuestTenant);
            Uri uri = task.Result;

            Assert.IsNotNull(uri);
            Assert.IsTrue(uri.AbsoluteUri.StartsWith(TestConstants.AuthorityGuestTenant, StringComparison.CurrentCulture));
            Dictionary <string, string> qp = MsalHelpers.ParseKeyValueList(uri.Query.Substring(1), '&', true, null);

            Assert.IsNotNull(qp);
            Assert.AreEqual(12, qp.Count);
            Assert.IsTrue(qp.ContainsKey("client-request-id"));
            Assert.IsFalse(qp.ContainsKey("client_secret"));
            Assert.AreEqual("offline_access openid profile r1/scope1 r1/scope2 r2/scope1 r2/scope2", qp["scope"]);
            Assert.AreEqual(TestConstants.ClientId, qp["client_id"]);
            Assert.AreEqual("code", qp["response_type"]);
            Assert.AreEqual(CustomRedirectUri, qp["redirect_uri"]);
            Assert.AreEqual(TestConstants.DisplayableId, qp["login_hint"]);
            Assert.AreEqual("MSAL.Desktop", qp["x-client-sku"]);
            Assert.IsFalse(string.IsNullOrEmpty(qp["x-client-ver"]));
            Assert.IsFalse(string.IsNullOrEmpty(qp["x-client-cpu"]));
            Assert.IsFalse(string.IsNullOrEmpty(qp["x-client-os"]));
            Assert.AreEqual("qp", qp["extra"]);
            Assert.AreEqual("select_account", qp["prompt"]);

            Assert.IsTrue(HttpMessageHandlerFactory.IsMocksQueueEmpty, "All mocks should have been consumed");
        }
        public void GetAuthorizationRequestUrlDuplicateParamsTest()
        {
            ConfidentialClientApplication app = new ConfidentialClientApplication(TestConstants.DefaultClientId,
                                                                                  TestConstants.DefaultRedirectUri, new ClientCredential(TestConstants.DefaultClientSecret), new TokenCache());

            try
            {
                Task <Uri> task = app.GetAuthorizationRequestUrlAsync(TestConstants.DefaultScope.AsArray(),
                                                                      TestConstants.DefaultDisplayableId, "[email protected]");
                Uri uri = task.Result;
                Assert.Fail("MSALException should be thrown here");
            }
            catch (Exception exc)
            {
                Assert.IsTrue(exc.InnerException is MsalException);
                Assert.AreEqual("duplicate_query_parameter", ((MsalException)exc.InnerException).ErrorCode);
                Assert.AreEqual("Duplicate query parameter 'login_hint' in extraQueryParameters", ((MsalException)exc.InnerException).Message);
            }
        }
예제 #11
0
        public async Task GetAuthorizationRequestUrlB2CTestAsync()
        {
            await RunWithMockHttpAsync(
                async (httpManager, serviceBundle, receiver) =>
            {
                httpManager.AddInstanceDiscoveryMockHandler();

                var app = new ConfidentialClientApplication(
                    serviceBundle,
                    MsalTestConstants.ClientId,
                    ClientApplicationBase.DefaultAuthority,
                    MsalTestConstants.RedirectUri,
                    new ClientCredential(MsalTestConstants.ClientSecret),
                    new TokenCache(),
                    new TokenCache())
                {
                    ValidateAuthority = false
                };

                //add mock response for tenant endpoint discovery
                httpManager.AddMockHandler(
                    new MockHttpMessageHandler
                {
                    Method          = HttpMethod.Get,
                    ResponseMessage = MockHelpers.CreateSuccessResponseMessage(
                        File.ReadAllText(
                            ResourceHelper.GetTestResourceRelativePath(@"OpenidConfiguration-QueryParams-B2C.json")))
                });

                var uri = await app.GetAuthorizationRequestUrlAsync(
                    MsalTestConstants.Scope,
                    MsalTestConstants.DisplayableId,
                    null).ConfigureAwait(false);
                Assert.IsNotNull(uri);
                Dictionary <string, string> qp = CoreHelpers.ParseKeyValueList(uri.Query.Substring(1), '&', true, null);
                Assert.IsNotNull(qp);

                Assert.AreEqual("my-policy", qp["p"]);
                ValidateCommonQueryParams(qp);
                Assert.AreEqual("offline_access openid profile r1/scope1 r1/scope2", qp["scope"]);
            }).ConfigureAwait(false);
        }
        /// <summary>
        /// Given a set of scopes, uses MSAL to formulate the proper Uri for the first part of the Code auth flow.
        /// See https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-auth-code-flow for more details on the flow.
        /// </summary>
        /// <param name="scopes">List of desired scopes for the Access Token.  For the Worker classes in this library,
        /// this should be set to <code>$api://{configurationManager["ClientId"]}/access_as_user</code></param>
        /// <returns>Auth Uri that should be requested via GET to start the Code auth flow</returns>
        /// <exception cref="Microsoft.Identity.Client.MsalException">Throws an MsalException if there are any authentication issues</exception>
        public async Task <Uri> GetAuthUriAsync(IEnumerable <string> scopes)
        {
            try
            {
                logger.LogInformation("Getting Auth Request Uri using scopes: [{0}]...", string.Join(", ", scopes));

                var clientTokenCache = new TokenCache();
                var userTokenCache   = tokenCacheService.FetchUserCache();
                var appTokenCache    = new TokenCache();

                var msalApp = new ConfidentialClientApplication(configuration["ClientId"], configuration["RedirectUri"], new ClientCredential(configuration["ClientSecret"]), userTokenCache, appTokenCache);
                var result  = await msalApp.GetAuthorizationRequestUrlAsync(scopes, null, null);

                return(result);
            }
            catch (MsalException msalException)
            {
                logger.LogError(new EventId(0), msalException, $"Exception getting Auth Request Uri using scopes: [string.Join(", ", scopes)]. Look at the app registration and make sure you have the correct ClientId, ClientSecret and RedirectUri configured in the app settings...");
                throw msalException;
            }
        }
예제 #13
0
        public void GetAuthorizationRequestUrlB2CTest()
        {
            ConfidentialClientApplication app = new ConfidentialClientApplication(TestConstants.ClientId,
                                                                                  TestConstants.RedirectUri, new ClientCredential(TestConstants.ClientSecret),
                                                                                  new TokenCache(), new TokenCache())
            {
                ValidateAuthority = false
            };

            //add mock response for tenant endpoint discovery
            HttpMessageHandlerFactory.AddMockHandler(new MockHttpMessageHandler
            {
                Method          = HttpMethod.Get,
                ResponseMessage = MockHelpers.CreateSuccessResponseMessage(File.ReadAllText(@"OpenidConfiguration-B2C.json"))
            });

            Task <Uri> task = app.GetAuthorizationRequestUrlAsync(TestConstants.Scope.AsArray(),
                                                                  TestConstants.DisplayableId, null);
            Uri uri = task.Result;

            Assert.IsNotNull(uri);
            Dictionary <string, string> qp = MsalHelpers.ParseKeyValueList(uri.Query.Substring(1), '&', true, null);

            Assert.IsNotNull(qp);
            Assert.AreEqual(12, qp.Count);
            Assert.AreEqual("my-policy", qp["p"]);
            Assert.IsTrue(qp.ContainsKey("client-request-id"));
            Assert.AreEqual("offline_access openid profile r1/scope1 r1/scope2", qp["scope"]);
            Assert.AreEqual(TestConstants.ClientId, qp["client_id"]);
            Assert.AreEqual("code", qp["response_type"]);
            Assert.AreEqual(TestConstants.RedirectUri, qp["redirect_uri"]);
            Assert.AreEqual(TestConstants.DisplayableId, qp["login_hint"]);
            Assert.AreEqual(UIBehavior.SelectAccount.PromptValue, qp["prompt"]);
            Assert.AreEqual("MSAL.Desktop", qp["x-client-sku"]);
            Assert.IsFalse(string.IsNullOrEmpty(qp["x-client-ver"]));
            Assert.IsFalse(string.IsNullOrEmpty(qp["x-client-cpu"]));
            Assert.IsFalse(string.IsNullOrEmpty(qp["x-client-os"]));

            Assert.IsTrue(HttpMessageHandlerFactory.IsMocksQueueEmpty, "All mocks should have been consumed");
        }
예제 #14
0
        public void GetAuthorizationRequestUrlCustomRedirectUriTest()
        {
            RunWithMockHttp(
                (httpManager, serviceBundle, receiver) =>
            {
                httpManager.AddInstanceDiscoveryMockHandler();

                var app = new ConfidentialClientApplication(
                    serviceBundle,
                    MsalTestConstants.ClientId,
                    MsalTestConstants.AuthorityGuestTenant,
                    MsalTestConstants.RedirectUri,
                    new ClientCredential(MsalTestConstants.ClientSecret),
                    new TokenCache(),
                    new TokenCache())
                {
                    ValidateAuthority = false
                };

                httpManager.AddMockHandlerForTenantEndpointDiscovery(app.Authority);

                const string CustomRedirectUri = "custom://redirect-uri";
                Task <Uri> task = app.GetAuthorizationRequestUrlAsync(
                    MsalTestConstants.Scope,
                    CustomRedirectUri,
                    MsalTestConstants.DisplayableId,
                    "extra=qp",
                    MsalTestConstants.ScopeForAnotherResource,
                    MsalTestConstants.AuthorityGuestTenant);
                var uri = task.Result;
                Assert.IsNotNull(uri);
                Assert.IsTrue(
                    uri.AbsoluteUri.StartsWith(MsalTestConstants.AuthorityGuestTenant, StringComparison.CurrentCulture));
                Dictionary <string, string> qp = CoreHelpers.ParseKeyValueList(uri.Query.Substring(1), '&', true, null);
                ValidateCommonQueryParams(qp, CustomRedirectUri);
                Assert.AreEqual("offline_access openid profile r1/scope1 r1/scope2 r2/scope1 r2/scope2", qp["scope"]);
                Assert.IsFalse(qp.ContainsKey("client_secret"));
                Assert.AreEqual("qp", qp["extra"]);
            });
        }
예제 #15
0
        public async Task GetAuthorizationRequestUrlDuplicateParamsTestAsync()
        {
            await RunWithMockHttpAsync(
                async (httpManager, serviceBundle, receiver) =>
            {
                httpManager.AddInstanceDiscoveryMockHandler();

                var app = new ConfidentialClientApplication(
                    serviceBundle,
                    MsalTestConstants.ClientId,
                    ClientApplicationBase.DefaultAuthority,
                    MsalTestConstants.RedirectUri,
                    new ClientCredential(MsalTestConstants.ClientSecret),
                    new TokenCache(),
                    new TokenCache())
                {
                    ValidateAuthority = false
                };

                httpManager.AddMockHandlerForTenantEndpointDiscovery(app.Authority);

                try
                {
                    var uri = await app.GetAuthorizationRequestUrlAsync(
                        MsalTestConstants.Scope,
                        MsalTestConstants.DisplayableId,
                        "[email protected]").ConfigureAwait(false);
                    Assert.Fail("MSALException should be thrown here");
                }
                catch (MsalException exc)
                {
                    Assert.AreEqual("duplicate_query_parameter", exc.ErrorCode);
                    Assert.AreEqual("Duplicate query parameter 'login_hint' in extraQueryParameters", exc.Message);
                }
                catch (Exception ex)
                {
                    Assert.Fail("Wrong type of exception thrown: " + ex);
                }
            }).ConfigureAwait(false);
        }