コード例 #1
0
        private IGraphServiceClient buildClient(AuthenticationResult authenticationResult)
        {
            logDebug("buildClient...");


            //DeviceCodeProvider authenticationProvider = new DeviceCodeProvider(_publicClientApp, Scopes);
            var authenticationProvider = new DelegateAuthenticationProvider(
                (requestMessage) =>
            {
                var access_token = authenticationResult.AccessToken;
                requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", access_token);
                return(Task.FromResult(0));
            });

            GraphServiceClient graphClient = new GraphServiceClient(authenticationProvider);


            if (authenticationResult.Account == null)
            {
                throw new Exception("authenticationResult.Account == null!");
            }
            mClientByUser[authenticationResult.Account.HomeAccountId.Identifier] = graphClient;

            return(graphClient);
        }
コード例 #2
0
        public static async Task <GraphServiceClient> EnsureClientCreated()
        {
            if (_discoveryContext == null)
            {
                _discoveryContext = await DiscoveryContext.CreateAsync();
            }

            var dcr = await _discoveryContext.DiscoverResourceAsync(GraphResourceId);

            _lastLoggedInUser = dcr.UserId;

            var clientCredential = new ClientCredential(_discoveryContext.AppIdentity.ClientId, _discoveryContext.AppIdentity.ClientSecret);
            var authResult       = await _discoveryContext
                                   .AuthenticationContext
                                   .AcquireTokenByRefreshTokenAsync(new SessionCache().Read("RefreshToken"), clientCredential, GraphResourceId);

            var graphToken             = authResult.AccessToken;
            var authenticationProvider = new DelegateAuthenticationProvider(
                (requestMessage) =>
            {
                requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", graphToken);
                return(Task.FromResult(0));
            });

            return(new GraphServiceClient(authenticationProvider));
        }
コード例 #3
0
        public static async Task Main(string[] args)
        {
            string clientId = "d662ac70-7482-45af-9dc3-c3cde8eeede4";

            string[] scopes = new[] { "User.Read", "Mail.ReadWrite", "Calendars.ReadWrite", "Notes.ReadWrite" };

            //Create the msal application
            IPublicClientApplication publicClientApplication = PublicClientApplicationBuilder
                                                               .Create(clientId).WithRedirectUri("http://localhost:1234")
                                                               .Build();

            var authResult = await publicClientApplication.AcquireTokenInteractive(scopes).ExecuteAsync();

            /* Create a DelegateAuthenticationProvider to use */
            var delegatingAuthProvider = new DelegateAuthenticationProvider((requestMessage) =>
            {
                requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", authResult.AccessToken);
                return(Task.FromResult(0));
            });

            HttpClient httpClient = GraphClientFactory.Create(delegatingAuthProvider);

            //Test Batch Code
            await TestBatch(httpClient);

            await TestFetchUser(httpClient);

            await TestFetchEvents(httpClient);
        }
コード例 #4
0
        public GraphService(Activity activity)
        {
            AuthClientApp = PublicClientApplicationBuilder.Create(clientID)
                            .WithRedirectUri($"msal{clientID}://auth")
                            .Build();

            var authProvider = new DelegateAuthenticationProvider(async(request) =>
            {
                IEnumerable <IAccount> accounts = await AuthClientApp.GetAccountsAsync();
                AuthenticationResult authResult;
                try
                {
                    authResult = await AuthClientApp.AcquireTokenSilent(scopes, accounts.FirstOrDefault())
                                 .ExecuteAsync();
                }
                catch (MsalUiRequiredException)
                {
                    authResult = await AuthClientApp.AcquireTokenInteractive(scopes)
                                 .WithParentActivityOrWindow(activity)
                                 .ExecuteAsync();
                }
                request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", authResult.AccessToken);
            });

            // Use AndroidClientHandler as opposed to HttpClientHandler.
            var innerHandler = new AndroidClientHandler {
                AllowAutoRedirect = false
            };
            var pipeline = GraphClientFactory.CreatePipeline(GraphClientFactory.CreateDefaultHandlers(authProvider), innerHandler);

            GraphClient = new GraphServiceClient(authProvider, new HttpProvider(pipeline, true, new Serializer()));
        }
コード例 #5
0
        /// <summary>
        /// For explanation only
        /// Gibt einen Authentifikation Anbieter zurück der eigens codierte funktion verwendet um ein token abzurufen.
        /// Es wird ein Token für einen Client, kein delegiertes Token abgerufen!
        /// </summary>
        /// <returns></returns>
        private DelegateAuthenticationProvider CreateDelegateAuthenticationProvider()
        {
            var delegateAuthenticationProvider = new DelegateAuthenticationProvider(async(requestMessage) =>
            {
                var app = ConfidentialClientApplicationBuilder
                          .Create(Config.ClientId)
                          .WithTenantId(Config.TenantId)
                          .WithClientSecret(Config.ClientSecret)
                          .Build();

                var scopes = new[] { "https://graph.microsoft.com/.default" };

                // Retrieve an access token for Microsoft Graph (gets a fresh token if needed).
                var authResult = await app
                                 .AcquireTokenForClient(scopes)
                                 .ExecuteAsync();

                var header = new AuthenticationHeaderValue("Bearer", authResult.AccessToken);

                // Add the access token in the Authorization header of the API request.
                requestMessage.Headers.Authorization = header;
            });

            return(delegateAuthenticationProvider);
        }
コード例 #6
0
        public static async Task <GraphServiceClient> GetGraphServiceClient2()
        {
            var authentication = new
            {
                Authority             = "https://graph.microsoft.com/",
                Directory             = WebConfigurationManager.AppSettings["ida:TenantId"],
                Application           = WebConfigurationManager.AppSettings["ida:ClientId"],
                ClientSecret          = WebConfigurationManager.AppSettings["ida:ClientSecret"],
                GraphResourceEndPoint = "v1.0",
                Instance = WebConfigurationManager.AppSettings["ida:AADInstance"],
                Domain   = WebConfigurationManager.AppSettings["ida:Domain"]
            };
            var graphAPIEndpoint = $"{authentication.Authority}{authentication.GraphResourceEndPoint}";
            var newAuth          = $"{authentication.Instance}{authentication.Directory}";
            //var newAuth2 = $"{authentication.Instance}{authentication.Domain}";

            AuthenticationContext authenticationContext = new AuthenticationContext(newAuth);

            Microsoft.IdentityModel.Clients.ActiveDirectory.ClientCredential clientCred
                = new Microsoft.IdentityModel.Clients.ActiveDirectory.ClientCredential(authentication.Application, authentication.ClientSecret);
            Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationResult authenticationResult
                = await authenticationContext.AcquireTokenAsync(authentication.Authority, clientCred);

            var token = authenticationResult.AccessToken;
            var delegateAuthProvider = new DelegateAuthenticationProvider((requestMessage) => {
                requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", token.ToString());
                return(Task.FromResult(0));
            });

            var graphClient = new GraphServiceClient(graphAPIEndpoint, delegateAuthProvider);

            return(graphClient);
        }
コード例 #7
0
        private static async Task <IAuthenticationProvider> GetAuthProvider()
        {
            var app = ConfidentialClientApplicationBuilder.Create(clientId)
                      .WithAuthority(AzureCloudInstance.AzurePublic, tenantId)
                      .WithClientSecret(clientSecret)
                      .Build();

            //Change this to scope of the requested service.
            string[] scopes = new string[] { "https://graph.microsoft.com/.default" };

            AuthenticationResult result = null;

            //try
            //{
            result = await app.AcquireTokenForClient(scopes).ExecuteAsync();

            //AuthenticationContext authenticationContext = new AuthenticationContext(authority);
            //ClientCredential clientCred = new ClientCredential(clientId, clientSecret);

            //result = await app.AcquireTokenForClient(scopes).ExecuteAsync();
            // ADAL includes an in memory cache, so this call will only send a message to the server if the cached token is expired.
            //AuthenticationResult authenticationResult = await authenticationContext.AcquireTokenAsync(graphResource, clientCred);

            //var token = authenticationResult.AccessToken;
            var token = result.AccessToken;

            var delegateAuthProvider = new DelegateAuthenticationProvider((requestMessage) =>
            {
                requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", token.ToString());
                return(Task.FromResult(0));
            });

            return(delegateAuthProvider);
            //}
        }
コード例 #8
0
ファイル: OneDrive2FileStorage.cs プロジェクト: 77rusa/README
        private IGraphServiceClient BuildClient(AuthenticationResult authenticationResult)
        {
            logDebug("buildClient...");


            //DeviceCodeProvider authenticationProvider = new DeviceCodeProvider(_publicClientApp, Scopes);
            var authenticationProvider = new DelegateAuthenticationProvider(
                (requestMessage) =>
            {
                var access_token = authenticationResult.AccessToken;
                requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", access_token);
                return(Task.FromResult(0));
            });

            GraphServiceClientWithState clientWithState = new GraphServiceClientWithState()
            {
                Client = new GraphServiceClient(authenticationProvider),
                RequiresUserInteraction = false,
                TokenExpiryDate         = authenticationResult.ExpiresOn.LocalDateTime
            };



            if (authenticationResult.Account == null)
            {
                throw new Exception("authenticationResult.Account == null!");
            }
            mClientByUser[authenticationResult.Account.HomeAccountId.Identifier] = clientWithState;

            return(clientWithState.Client);
        }
コード例 #9
0
        private static async Task GetUsers()
        {
            var scopes = new[] { "user.read.all" };

            var token = await TokenProvider.GetToken(scopes);

            var delegateAuthProvider = new DelegateAuthenticationProvider((requestMessage) =>
            {
                requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", token);

                return(Task.FromResult(0));
            });

            var graphClient = new GraphServiceClient("https://graph.microsoft.com/v1.0", delegateAuthProvider);

            //Get 10 Users sorted by Name
            var users = await graphClient.Users.Request()
                        .Top(10)
                        .OrderBy("displayName")
                        .Select("id, displayName")
                        .GetAsync();

            Console.WriteLine("First 10 Users in your tenant...");
            foreach (var user in users)
            {
                Console.WriteLine($"    {user.DisplayName}. Id: {user.Id}");
            }
        }
コード例 #10
0
 // GET: UserProfile
 public async Task<ActionResult> Index()
 {
     string tenantID = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;
     string userObjectID = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
     try
     {
         var graphToken = await AuthenticationHelper.GetGraphAccessToken();
         var authenticationProvider = new DelegateAuthenticationProvider(
         (requestMessage) =>
         {
             requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", graphToken);
             return Task.FromResult(0);
         });
         var graphClient = new GraphServiceClient(authenticationProvider);
         var user = await graphClient.Me.Request().GetAsync();
         return View(user);
     }
     catch (AdalException)
     {
         // Return to error page.
         return View("Error");
     }
     // if the above failed, the user needs to explicitly re-authenticate for the app to obtain the required token
     catch (Exception)
     {
         return View("Relogin");
     }
 }
コード例 #11
0
        public async Task SendAsync_E2E_ValidateHasRawResponseBody(string authenticationToken)
        {
            var authenticationProvider = new DelegateAuthenticationProvider(
                (requestMessage) =>
            {
                requestMessage.Headers.Authorization = new AuthenticationHeaderValue(CoreConstants.Headers.Bearer, authenticationToken);
                return(Task.FromResult(0));
            });

            var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, "https://graph.microsoft.com/v1.0/me/fail");
            var httpProvider       = new HttpProvider();

            HttpResponseMessage response = null;

            var exception = (ServiceException)await Record.ExceptionAsync(async() =>
            {
                await authenticationProvider.AuthenticateRequestAsync(httpRequestMessage);
                response = await httpProvider.SendAsync(httpRequestMessage);
            });

            // Assert expected exception
            Assert.Null(response);
            Assert.NotNull(exception);
            Assert.NotNull(exception.Error);
            Assert.Contains("InvalidAuthenticationToken", exception.RawResponseBody);
            Assert.Equal("InvalidAuthenticationToken", exception.Error.Code);

            // Assert not unexpected deserialization exception
            Assert.NotSame(ErrorConstants.Codes.GeneralException, exception.Error.Code);
            Assert.NotSame(ErrorConstants.Messages.UnexpectedExceptionResponse, exception.Error.Message);
        }
コード例 #12
0
        // GET: UserProfile
        public async Task <ActionResult> Index()
        {
            string tenantID     = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;
            string userObjectID = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;

            try
            {
                var graphToken = await AuthenticationHelper.GetGraphAccessToken();

                var authenticationProvider = new DelegateAuthenticationProvider(
                    (requestMessage) =>
                {
                    requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", graphToken);
                    return(Task.FromResult(0));
                });
                var graphClient = new GraphServiceClient(authenticationProvider);
                var user        = await graphClient.Me.Request().GetAsync();

                return(View(user));
            }
            catch (AdalException)
            {
                // Return to error page.
                return(View("Error"));
            }
            // if the above failed, the user needs to explicitly re-authenticate for the app to obtain the required token
            catch (Exception)
            {
                return(View("Relogin"));
            }
        }
コード例 #13
0
        public async Task InitializeAsync()
        {
            // User.Read --> Needed for sign in
            // Mail.Read --> Read actual mails
            var appScopes = new[] { "User.Read", "Mail.Read" };
            var appId     = "bec1f446-9c59-4b92-9647-a3e872bf2bb2";

            var clientApplication = PublicClientApplicationBuilder
                                    .Create(appId)
                                    .WithRedirectUri("http://localhost:1234")
                                    .Build();

            var authenticationResult = await clientApplication
                                       .AcquireTokenInteractive(appScopes)
                                       .ExecuteAsync()
                                       .ConfigureAwait(false);

            var authenticationProvider = new DelegateAuthenticationProvider(message =>
            {
                message.Headers.Authorization =
                    new AuthenticationHeaderValue("bearer", authenticationResult.AccessToken);
                return(Task.FromResult(0));
            });

            _client = new GraphServiceClient(authenticationProvider);
        }
コード例 #14
0
        private async void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            // 欢迎访问我博客 http://lindexi.gitee.io 里面有大量 UWP WPF 博客

            var provider = new DelegateAuthenticationProvider(AuthenticateRequestAsyncDelegate);

            var client = new GraphServiceClient(provider);

            await client.Me.SendMail(new Message()
            {
                Subject = "调用Microsoft Graph发出的邮件",
                Body    = new ItemBody()
                {
                    ContentType = BodyType.Text,
                    Content     = "这是一封调用了Microsoft Graph服务发出的邮件,范例参考 https://github.com/chenxizhang/office365dev"
                },
                ToRecipients = new[]
                {
                    new Recipient()
                    {
                        EmailAddress = new EmailAddress()
                        {
                            Address = "*****@*****.**"
                        }
                    }
                }
            }, SaveToSentItems : true /*保存到发送邮件夹*/).Request().PostAsync();
        }
コード例 #15
0
        public static async Task <UserAAD> CreateUser(AuthenticateResult result, List <Claim> filtered)
        {
            var user = new ApplicationUser
            {
                UserName = filtered.Any(x => x.Type == "email") ? filtered.FirstOrDefault(x => x.Type == "email")?.Value : Guid.NewGuid().ToString(),
                Email    = filtered.FirstOrDefault(x => x.Type == "email")?.Value
            };
            List <Claim> claimAdded = new List <Claim>();

            string access_token = string.Empty;

            if (!string.IsNullOrEmpty(result.Properties.GetTokenValue("access_token")))
            {
                access_token = result.Properties.GetTokenValue("access_token");
                var delegateAuthProvider = new DelegateAuthenticationProvider((requestMessage) =>
                {
                    requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", access_token);
                    return(Task.CompletedTask);
                });

                GraphServiceClient graphClient = new GraphServiceClient(delegateAuthProvider);
                var userMe = await graphClient.Me
                             .Request()
                             .GetAsync();

                if (!string.IsNullOrEmpty(userMe.City))
                {
                    claimAdded.Add(new Claim(AADClaims.City, userMe.City));
                }
                if (!string.IsNullOrEmpty(userMe.CompanyName))
                {
                    claimAdded.Add(new Claim(AADClaims.CompanyName, userMe.CompanyName));
                }
                if (!string.IsNullOrEmpty(userMe.Country))
                {
                    claimAdded.Add(new Claim(AADClaims.Country, userMe.Country));
                }
                if (!string.IsNullOrEmpty(userMe.JobTitle))
                {
                    claimAdded.Add(new Claim(AADClaims.JobTitle, userMe.JobTitle));
                }
                if (userMe.BusinessPhones.Any())
                {
                    claimAdded.Add(new Claim(ClaimTypes.MobilePhone, userMe.BusinessPhones.FirstOrDefault()));
                }
                if (!string.IsNullOrEmpty(userMe.StreetAddress))
                {
                    claimAdded.Add(new Claim(ClaimTypes.StreetAddress, userMe.StreetAddress));
                }
            }

            return(new UserAAD
            {
                User = user,
                Claims = claimAdded
            });
        }
コード例 #16
0
        /// <summary>
        /// Gets an <see cref="IAuthenticationProvider"/> using the provide <see cref="IAuthContext"/>.
        /// </summary>
        /// <param name="authContext">The <see cref="IAuthContext"/> to get an auth provider for.</param>
        /// <returns>A <see cref="IAuthenticationProvider"/> based on provided <see cref="IAuthContext"/>.</returns>
        public static IAuthenticationProvider GetAuthProvider(IAuthContext authContext)
        {
            if (authContext is null)
            {
                throw new AuthenticationException(ErrorConstants.Message.MissingAuthContext);
            }

            IAuthenticationProvider authProvider = null;
            string authorityUrl = GetAuthorityUrl(authContext);

            switch (authContext.AuthType)
            {
            case AuthenticationType.Delegated:
            {
                IPublicClientApplication publicClientApp = PublicClientApplicationBuilder
                                                           .Create(authContext.ClientId)
                                                           .WithTenantId(authContext.TenantId)
                                                           .WithAuthority(authorityUrl)
                                                           .WithClientCapabilities(new[] { "cp1" })
                                                           .Build();

                ConfigureTokenCache(publicClientApp.UserTokenCache, authContext);
                authProvider = new DeviceCodeProvider(publicClientApp, authContext.Scopes, async(result) =>
                    {
                        await Console.Out.WriteLineAsync(result.Message);
                    });
                break;
            }

            case AuthenticationType.AppOnly:
            {
                IConfidentialClientApplication confidentialClientApp = ConfidentialClientApplicationBuilder
                                                                       .Create(authContext.ClientId)
                                                                       .WithTenantId(authContext.TenantId)
                                                                       .WithAuthority(authorityUrl)
                                                                       .WithCertificate(GetCertificate(authContext))
                                                                       .Build();

                ConfigureTokenCache(confidentialClientApp.AppTokenCache, authContext);
                string graphBaseUrl = GraphSession.Instance.Environment?.GraphEndpoint ?? "https://graph.microsoft.com";
                authProvider = new ClientCredentialProvider(confidentialClientApp, $"{graphBaseUrl}/.default");
                break;
            }

            case AuthenticationType.UserProvidedAccessToken:
            {
                authProvider = new DelegateAuthenticationProvider((requestMessage) =>
                    {
                        requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer",
                                                                                             new NetworkCredential(string.Empty, GraphSession.Instance.UserProvidedToken).Password);
                        return(Task.CompletedTask);
                    });
                break;
            }
            }
            return(authProvider);
        }
コード例 #17
0
        private GraphServiceClient CreateGraphServiceClient(string accessToken)
        {
            var authenticationProvider = new DelegateAuthenticationProvider((request) =>
            {
                request.Headers.Authorization = new AuthenticationHeaderValue("bearer", accessToken);
                return(Task.FromResult(0));
            });

            return(new GraphServiceClient(authenticationProvider));
        }
        public GraphClientAuthProvider(ITokenAcquisition token)
        {
            Token = token;
            var accessToken = token.GetAccessTokenForUserAsync(Scopes).GetAwaiter().GetResult();

            AuthProvider = new DelegateAuthenticationProvider(x => {
                x.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
                return(Task.FromResult(0));
            });
        }
コード例 #19
0
 public static async Task<GraphServiceClient> EnsureClientCreated(string authCode)
 {
     var graphToken = await GetAccessTokenByAuthenticationCodeAsync(authCode);
     var authenticationProvider = new DelegateAuthenticationProvider(
         (requestMessage) =>
         {
             requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", graphToken);
             return Task.FromResult(0);
         });
     return new GraphServiceClient(authenticationProvider);
 }
コード例 #20
0
        static void Main(string[] args)
        {
            try
            {
                var UserEmail    = ConfigurationManager.AppSettings["AAD:UserEmail"];
                var UserPassword = ConfigurationManager.AppSettings["AAD:UserPassword"];
                var resource     = ConfigurationManager.AppSettings["AAD.Resource"];


                Console.WriteLine("{0} - Connecting as user:{1}", DateTime.Now, UserEmail);


                var accessToken = AccessTokenProvider.GetAccessToken(resource, UserEmail, UserPassword);

                //Calling Graph Client
                var delegateAuthProvider = new DelegateAuthenticationProvider((requestMessage) =>
                {
                    requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", accessToken.Token);

                    return(Task.FromResult(0));
                });

                var graphClient = new GraphServiceClient(delegateAuthProvider);

                Console.WriteLine("Reading top 20 emails......");

                var mailResults = graphClient.Me.MailFolders.Inbox.Messages.Request()
                                  .OrderBy("receivedDateTime DESC")
                                  .Select(m => new { m.Subject, m.ReceivedDateTime, m.From })
                                  .Top(20)
                                  .GetAsync()
                                  .Result;


                foreach (var msg in mailResults.CurrentPage)
                {
                    Console.WriteLine("Subject: {0}<br/>", msg.Subject);
                }

                Console.WriteLine();
                Console.WriteLine("Done. Press any key to continue....");
            }
            catch (Exception err)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("Error:{0}", err.Message);
                while ((err = err.InnerException) != null)
                {
                    Console.WriteLine(err.Message);
                }
            }

            Console.ReadKey();
        }
コード例 #21
0
        public static GraphServiceClient GetGraphServiceClient(string token)
        {
            var authenticationProvider = new DelegateAuthenticationProvider(
                (requestMessage) =>
                {
                    requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
                    return Task.FromResult(0);
                });

            return new GraphServiceClient(SettingsHelper.GraphResourceUrl, authenticationProvider);
        }
        public async Task AppendAuthenticationHeaderAsync_DelegateNotSet()
        {
            var authenticationProvider = new DelegateAuthenticationProvider(null);

            using (var httpRequestMessage = new HttpRequestMessage())
            {
                await authenticationProvider.AuthenticateRequestAsync(httpRequestMessage);

                Assert.Null(httpRequestMessage.Headers.Authorization);
            }
        }
コード例 #23
0
        private GraphServiceClient GetGraphClient(IEnumerable <string> scopes)
        {
            var auth = new DelegateAuthenticationProvider(
                async(requestMessage) =>
            {
                var token = await this.GetUserAccessTokenAsync(scopes);
                requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", token);
            });

            return(new GraphServiceClient(this.config.GraphBaseUrl.ToString(), auth));
        }
コード例 #24
0
ファイル: GraphClient.cs プロジェクト: mrsunil/bp2
        private IGraphServiceClient GetGraphServiceClient()
        {
            var authenticationProvider = new DelegateAuthenticationProvider(async request =>
            {
                var accessToken = await _tokenProvider.GetBearerTokenAsync();
                request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", accessToken);
            });

            _graphClient = new GraphServiceClient(authenticationProvider);
            return(_graphClient);
        }
コード例 #25
0
        private GraphServiceClient GetGraphServiceClient()
        {
            var authenticationProvider = new DelegateAuthenticationProvider(
                (requestMessage) =>
            {
                requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", AuthenticationHelper.LastAccessToken);
                return(Task.FromResult(0));
            });

            return(new GraphServiceClient(authenticationProvider));
        }
コード例 #26
0
 public static async Task<GraphServiceClient> GetGraphServiceClientAsync()
 {
     var accessToken = await O365UniApp.AuthenticationHelper.GetGraphAccessTokenAsync();
     var authenticationProvider = new DelegateAuthenticationProvider(
         (requestMessage) =>
         {
             requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
             return Task.FromResult(0);
         });
     return new GraphServiceClient(authenticationProvider);
 }
コード例 #27
0
        public static GraphServiceClient GetGraphServiceClient(string token)
        {
            var authenticationProvider = new DelegateAuthenticationProvider(
                (requestMessage) =>
            {
                requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
                return(Task.FromResult(0));
            });

            return(new GraphServiceClient(authenticationProvider));
        }
コード例 #28
0
        private void InitDriveService()
        {
            var provider = new DelegateAuthenticationProvider((requestMessage) =>
            {
                requestMessage
                .Headers
                .Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", oauthClient.AccessToken);
                return(Task.FromResult(0));
            });

            graphServiceClient = new GraphServiceClient(provider);
        }
コード例 #29
0
        public static async Task <GraphServiceClient> GetGraphServiceClientAsync()
        {
            var accessToken = await GetGraphAccessTokenAsync();

            var authenticationProvider = new DelegateAuthenticationProvider(
                (requestMessage) =>
            {
                requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
                return(Task.FromResult(0));
            });

            return(new GraphServiceClient(authenticationProvider));
        }
コード例 #30
0
        private static GraphServiceClient GetClient(string accessToken, IHttpProvider provider = null)
        {
            var delegateAuthProvider = new DelegateAuthenticationProvider((requestMessage) =>
            {
                requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", accessToken);

                return(Task.FromResult(0));
            });

            var graphClient = new GraphServiceClient(delegateAuthProvider, provider ?? HttpProvider);

            return(graphClient);
        }
コード例 #31
0
        public GraphServiceClient CreateClient(AuthenticationResult authResult)
        {
            var authProvider = new DelegateAuthenticationProvider(reqMsg =>
            {
                reqMsg.Headers.Authorization = new AuthenticationHeaderValue("bearer", authResult.AccessToken);
                return(Task.CompletedTask);
            });

            var pipeline     = GraphClientFactory.CreatePipeline(GraphClientFactory.CreateDefaultHandlers(authProvider), HttpMessageHandler);
            var httpProvider = new HttpProvider(pipeline, true, new Serializer());

            return(new GraphServiceClient(authProvider, httpProvider));
        }
コード例 #32
0
        public static async Task <GraphServiceClient> EnsureClientCreated(string authCode)
        {
            var graphToken = await GetAccessTokenByAuthenticationCodeAsync(authCode);

            var authenticationProvider = new DelegateAuthenticationProvider(
                (requestMessage) =>
            {
                requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", graphToken);
                return(Task.FromResult(0));
            });

            return(new GraphServiceClient(authenticationProvider));
        }
コード例 #33
0
		public static async Task<GraphServiceClient> GetGraphServiceAsync(Activity activity)
		{
			var accessToken = await GetAccessTokenAsync(activity, Constants.GraphResourceId);
            var authenticationProvider = new DelegateAuthenticationProvider(
                (requestMessage) =>
                {
                    requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", accessToken);

                    return Task.FromResult(0);
                });

            return new GraphServiceClient(Constants.GraphResourceUrl, authenticationProvider);
		}
コード例 #34
0
        internal static IAuthenticationProvider GetAuthProvider(IAuthContext authContext)
        {
            if (authContext is null)
            {
                throw new AuthenticationException(ErrorConstants.Message.MissingAuthContext);
            }

            IAuthenticationProvider authProvider = null;

            switch (authContext.AuthType)
            {
            case AuthenticationType.Delegated:
            {
                IPublicClientApplication publicClientApp = PublicClientApplicationBuilder
                                                           .Create(authContext.ClientId)
                                                           .WithTenantId(authContext.TenantId)
                                                           .Build();

                ConfigureTokenCache(publicClientApp.UserTokenCache, authContext);
                authProvider = new DeviceCodeProvider(publicClientApp, authContext.Scopes, async(result) => {
                        await Console.Out.WriteLineAsync(result.Message);
                    });
                break;
            }

            case AuthenticationType.AppOnly:
            {
                IConfidentialClientApplication confidentialClientApp = ConfidentialClientApplicationBuilder
                                                                       .Create(authContext.ClientId)
                                                                       .WithTenantId(authContext.TenantId)
                                                                       .WithCertificate(string.IsNullOrEmpty(authContext.CertificateThumbprint) ? GetCertificateByName(authContext.CertificateName) : GetCertificateByThumbprint(authContext.CertificateThumbprint))
                                                                       .Build();

                ConfigureTokenCache(confidentialClientApp.AppTokenCache, authContext);
                authProvider = new ClientCredentialProvider(confidentialClientApp);
                break;
            }

            case AuthenticationType.UserProvidedAccessToken:
            {
                authProvider = new DelegateAuthenticationProvider((requestMessage) => {
                        requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer",
                                                                                             new NetworkCredential(string.Empty, GraphSession.Instance.UserProvidedToken).Password);
                        return(Task.CompletedTask);
                    });
                break;
            }
            }
            return(authProvider);
        }
        public static async Task <GraphServiceClient> GetGraphServiceAsync(Activity activity)
        {
            var accessToken = await GetAccessTokenAsync(activity, Constants.GraphResourceId);

            var authenticationProvider = new DelegateAuthenticationProvider(
                (requestMessage) =>
            {
                requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", accessToken);

                return(Task.FromResult(0));
            });

            return(new GraphServiceClient(Constants.GraphResourceUrl, authenticationProvider));
        }
コード例 #36
0
        public static async Task<GraphServiceClient> EnsureClientCreated()
        {
            if (_discoveryContext == null)
            {
                _discoveryContext = await DiscoveryContext.CreateAsync();
            }

            var dcr = await _discoveryContext.DiscoverResourceAsync(GraphResourceId);

            _lastLoggedInUser = dcr.UserId;

            var clientCredential = new ClientCredential(_discoveryContext.AppIdentity.ClientId, _discoveryContext.AppIdentity.ClientSecret);
            var authResult = await _discoveryContext
                                    .AuthenticationContext
                                    .AcquireTokenByRefreshTokenAsync(new SessionCache().Read("RefreshToken"), clientCredential, GraphResourceId);
            var graphToken = authResult.AccessToken;
            var authenticationProvider = new DelegateAuthenticationProvider(
                (requestMessage) =>
                {
                    requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", graphToken);
                    return Task.FromResult(0);
                });
            return new GraphServiceClient(authenticationProvider);
        }
コード例 #37
0
 private GraphServiceClient GetGraphServiceClient(string token)
 {
     var authenticationProvider = new DelegateAuthenticationProvider(
         (requestMessage) =>
         {
             requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
             return Task.FromResult(0);
         });
     return new GraphServiceClient(authenticationProvider);
 }