Ejemplo n.º 1
0
        public async Task OnBehalfOfProvider_ShouldGetNewAccessTokenWithNoUserAssertion()
        {
            HttpRequestMessage httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, "http://example.org/foo");

            httpRequestMessage.Properties.Add(typeof(GraphRequestContext).ToString(), new GraphRequestContext
            {
                MiddlewareOptions = new Dictionary <string, IMiddlewareOption>
                {
                    {
                        typeof(AuthenticationHandlerOption).ToString(),
                        new AuthenticationHandlerOption
                        {
                            AuthenticationProviderOption = new MsalAuthenticationProviderOption
                            {
                                UserAssertion = null
                            }
                        }
                    }
                }
            });

            AuthenticationResult expectedAuthResult = MockAuthResult.GetAuthenticationResult(new GraphAccount(_graphUserAccount));

            _mockClientApplicationBase.Setup((cca) => cca.AcquireTokenOnBehalfOfAsync(_scopes, It.IsAny <UserAssertion>(), "common"))
            .ReturnsAsync(expectedAuthResult);

            OnBehalfOfProvider authProvider = new OnBehalfOfProvider(_mockClientApplicationBase.Object, _scopes);
            await authProvider.AuthenticateRequestAsync(httpRequestMessage);

            Assert.IsInstanceOfType(authProvider.ClientApplication, typeof(IConfidentialClientApplication), "Unexpected client application set.");
            Assert.IsNotNull(httpRequestMessage.Headers.Authorization, "Unexpected auhtorization header set.");
            Assert.AreEqual(expectedAuthResult.AccessToken, httpRequestMessage.Headers.Authorization.Parameter, "Unexpected access token set.");
        }
Ejemplo n.º 2
0
        public async Task OnBehalfOfProvider_ShouldGetCachedAccessTokenForUserAssertion()
        {
            UserAssertion      assertion          = new UserAssertion(_jwtAccessToken);
            HttpRequestMessage httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, "http://example.org/foo");

            httpRequestMessage.Properties.Add(typeof(GraphRequestContext).ToString(), new GraphRequestContext
            {
                MiddlewareOptions = new Dictionary <string, IMiddlewareOption>
                {
                    {
                        typeof(AuthenticationHandlerOption).ToString(),
                        new AuthenticationHandlerOption
                        {
                            AuthenticationProviderOption = new MsalAuthenticationProviderOption
                            {
                                UserAssertion = assertion
                            }
                        }
                    }
                }
            });

            OnBehalfOfProvider authProvider = new OnBehalfOfProvider(_mockClientApplicationBase.Object, _scopes);
            await authProvider.AuthenticateRequestAsync(httpRequestMessage);

            Assert.IsInstanceOfType(authProvider.ClientApplication, typeof(IConfidentialClientApplication), "Unexpected client application set.");
            Assert.IsNotNull(httpRequestMessage.Headers.Authorization, "Unexpected auhtorization header set.");
            Assert.AreEqual(_silentAuthResult.AccessToken, httpRequestMessage.Headers.Authorization.Parameter, "Unexpected access token set.");
        }
        static GraphService()
        {
            var graphConfig = LoadAppSettings();
            var oboSettings = graphConfig.GetSection("onBehalfClientSettings");

            var scopes      = oboSettings["scopes"];
            var scopesArray = scopes.Split(',');

            // Initialize the Graph client to make calls on behalf of the user
            var userClientCreds = new ClientCredential(oboSettings["appSecret"]);
            var oboMsalClient   = OnBehalfOfProvider.CreateClientApplication(
                oboSettings["appId"],
                oboSettings["redirect"],
                userClientCreds, null,
                graphConfig["tenantId"]);

            var oboAuthProvider = new OnBehalfOfProvider(oboMsalClient, scopesArray);

            userClient = new GraphServiceClient(oboAuthProvider);

            var appOnlySettings = graphConfig.GetSection("appOnlyClientSettings");

            // Initialize the Graph client to make app-only calls
            var appClientCreds = new ClientCredential(appOnlySettings["appSecret"]);
            var appMsalClient  = ClientCredentialProvider.CreateClientApplication(
                appOnlySettings["appId"], appClientCreds, null, graphConfig["tenantId"]);
            var appAuthProvider = new ClientCredentialProvider(appMsalClient);

            appClient = new GraphServiceClient(appAuthProvider);

            flightAdminSite = graphConfig["flightAdminSite"];
            flightList      = graphConfig["flightList"];
        }
Ejemplo n.º 4
0
        public void OnBehalfOfProvider_ShouldCreateConfidentialClientApplicationWithMandatoryParams()
        {
            IClientApplicationBase clientApp = OnBehalfOfProvider.CreateClientApplication(_clientId, _redirectUri, _clientCredential);

            Assert.IsInstanceOfType(clientApp, typeof(ConfidentialClientApplication), "Unexpected client application set.");
            Assert.AreEqual(_clientId, clientApp.ClientId, "Wrong client id set.");
            Assert.AreEqual(string.Format(AuthConstants.CloudList[NationalCloud.Global], AuthConstants.Tenants.Common), clientApp.Authority, "Wrong authority set.");
        }
Ejemplo n.º 5
0
        public void OnBehalfOfProvider_ShouldCreateConfidentialClientApplicationForConfiguredCloud()
        {
            string testTenant = "infotest";
            IClientApplicationBase clientApp = OnBehalfOfProvider.CreateClientApplication(_clientId, _redirectUri, _clientCredential, null, testTenant, NationalCloud.China);

            Assert.IsInstanceOfType(clientApp, typeof(ConfidentialClientApplication), "Unexpected client application set.");
            Assert.AreEqual(_clientId, clientApp.ClientId, "Wrong client id set.");
            Assert.AreEqual(string.Format(AuthConstants.CloudList[NationalCloud.China], testTenant), clientApp.Authority, "Wrong authority set.");
        }
Ejemplo n.º 6
0
        public void OnBehalfOfProvider_ShouldConstructAuthProviderWithConfidentialClientApp()
        {
            ConfidentialClientApplication cca  = new ConfidentialClientApplication(_clientId, _redirectUri, _clientCredential, new TokenCache(), null);
            OnBehalfOfProvider            auth = new OnBehalfOfProvider(cca, _scopes);

            Assert.IsInstanceOfType(auth, typeof(IAuthenticationProvider), "Unexpected auth provider set.");
            Assert.IsNotNull(auth.ClientApplication, "Client application not initialized.");
            Assert.AreSame(cca, auth.ClientApplication, "Wrong client application set.");
        }
Ejemplo n.º 7
0
        public void ShouldUseDefaultScopeUrlWhenScopeIsNull()
        {
            var mock = Mock.Of <IConfidentialClientApplication>();

            OnBehalfOfProvider onBehalfOfProvider = new OnBehalfOfProvider(mock, null);

            Assert.NotNull(onBehalfOfProvider.Scopes);
            Assert.True(onBehalfOfProvider.Scopes.Count().Equals(1));
            Assert.Equal(AuthConstants.DefaultScopeUrl, onBehalfOfProvider.Scopes.FirstOrDefault());
        }
Ejemplo n.º 8
0
        public OnBehalfOfProvider CreateOnBehalfOfProvider(string[] scopes = null)
        {
            scopes ??= Config.Scopes;

            var confidentialClientApplication = ConfidentialClientApplicationBuilder
                                                .Create(Config.ClientId)
                                                .WithAuthority(Config.AuthorityUrl)
                                                .WithClientSecret(Config.ClientSecret)
                                                .Build();

            var authProvider = new OnBehalfOfProvider(confidentialClientApplication, scopes);

            return(authProvider);
        }
Ejemplo n.º 9
0
        public void ShouldGetGraphUserAccountFromJwtString()
        {
            IEnumerable <string> scopes = new List <string> {
                "User.ReadBasic.All"
            };
            string jwtAccessToken = "eyJ0eXAiOiJKV1QiLCJub25jZSI6IkFBMjMyVEVTVCIsImFsZyI6IkhTMjU2In0.eyJmYW1pbHlfbmFtZSI6IkRvZSIsImdpdmVuX25hbWUiOiJKb2huIiwibmFtZSI6IkpvaG4gRG9lIiwib2lkIjoiZTYwMmFkYTctNmVmZC00ZTE4LWE5NzktNjNjMDJiOWYzYzc2Iiwic2NwIjoiVXNlci5SZWFkQmFzaWMuQWxsIiwidGlkIjoiNmJjMTUzMzUtZTJiOC00YTlhLTg2ODMtYTUyYTI2YzhjNTgzIiwidW5pcXVlX25hbWUiOiJqb2huQGRvZS50ZXN0LmNvbSIsInVwbiI6ImpvaG5AZG9lLnRlc3QuY29tIn0.hf9xI5XYBjGec-4n4_Kxj8Nd2YHBtihdevYhzFxbpXQ";

            var mock = Mock.Of <IConfidentialClientApplication>();

            OnBehalfOfProvider authProvider = new OnBehalfOfProvider(mock, scopes);
            GraphUserAccount   userAccount  = authProvider.GetGraphUserAccountFromJwt(jwtAccessToken);

            Assert.NotNull(userAccount);
            Assert.Equal("e602ada7-6efd-4e18-a979-63c02b9f3c76", userAccount?.ObjectId);
            Assert.Equal("6bc15335-e2b8-4a9a-8683-a52a26c8c583", userAccount?.TenantId);
            Assert.Equal("*****@*****.**", userAccount?.Email);
        }
Ejemplo n.º 10
0
        public MicrosoftGraphService(IHttpContextAccessor httpContextAccessor, IConfiguration configuration)
        {
            _httpContextAccessor = httpContextAccessor;
            _configuration       = configuration;
            _scopes = new List <string> {
                "User.Read", "User.Read.All", "Directory.Read.All"
            };

            _clientApp = ConfidentialClientApplicationBuilder
                         .Create(_configuration["AzureAd:ClientId"])
                         .WithTenantId(_configuration["AzureAd:TenantId"])
                         .WithRedirectUri(_configuration["AzureAd:BaseUrl"] + "/signin")
                         .WithClientSecret(_configuration["AzureAd:ClientSecret"])
                         .Build();

            _authProvider = new OnBehalfOfProvider(_clientApp, _scopes);
        }
Ejemplo n.º 11
0
        public async Task <ActionResult> Get()
        {
            var header = Request.Headers["Authorization"];
            var token  = header.First().Split(' ')[1];

            OnBehalfOfProvider onBehalfOfProvider =
                new OnBehalfOfProvider(ConfidentialClientApplication);

            var graphClient = new GraphServiceClient(onBehalfOfProvider);
            var me          = await graphClient.Me.Request().WithUserAssertion(new UserAssertion(token)).GetAsync();

            return(Ok(new {
                Office = me.OfficeLocation,
                Mail = me.Mail,
                Name = me.DisplayName
            }));
        }
Ejemplo n.º 12
0
        public void ShouldConstructAuthProviderWithConfidentialClientApp()
        {
            string clientId             = "00000000-0000-0000-0000-000000000000";
            string clientSecret         = "00000000-0000-0000-0000-000000000000";
            string authority            = "https://login.microsoftonline.com/organizations/";
            string redirectUri          = "https://login.microsoftonline.com/common/oauth2/deviceauth";
            IEnumerable <string> scopes = new List <string> {
                "User.ReadBasic.All"
            };

            IConfidentialClientApplication confidentialClientApplication = ConfidentialClientApplicationBuilder
                                                                           .Create(clientId)
                                                                           .WithRedirectUri(redirectUri)
                                                                           .WithClientSecret(clientSecret)
                                                                           .WithAuthority(authority)
                                                                           .Build();

            OnBehalfOfProvider auth = new OnBehalfOfProvider(confidentialClientApplication, scopes);

            Assert.IsAssignableFrom <IAuthenticationProvider>(auth);
            Assert.NotNull(auth.ClientApplication);
            Assert.Same(confidentialClientApplication, auth.ClientApplication);
        }