public static async Task Main() { /* Configuration Values */ MyConfig configuration = InitializeConfig(); /* Do the auth stuff first */ IPublicClientApplication publicClientApplication = PublicClientApplicationBuilder .Create(configuration.ClientId).WithRedirectUri("http://localhost:1234") .Build(); InteractiveAuthenticationProvider authenticationProvider = new InteractiveAuthenticationProvider(publicClientApplication, configuration.Scopes); /* Get the client */ GraphServiceClient graphClient = new GraphServiceClient(authenticationProvider); /* Get a valid token in cache */ await AcquireTokenToCache(graphClient); /* Create a HttpQuery for use */ HttpQuery query = new HttpQuery(graphClient); /* Run the four versions */ await Run0(graphClient); await Run1(query, graphClient); await Run2(query, graphClient); Run3(graphClient); }
/// <summary> /// Konstruktor który inicjalizuje podstawowe obiekty dla Graphów /// </summary> /// <param name="ClientApp">Obiekt z bibloteki MSAL, ktory informuje o rodzaju aplikacji oraz metodzie autentykacji</param> /// <param name="Scopes">Parametry które pobierzemy od uzytkownika</param> public MicrosoftAvatarDownloader(IPublicClientApplication ClientApp, string[] Scopes) { InteractiveAuthenticationProvider interactiveAuthenticationProvider = new InteractiveAuthenticationProvider(ClientApp, Scopes); graphClient = new GraphServiceClient(interactiveAuthenticationProvider); graphClient.BaseUrl = "https://graph.microsoft.com/beta"; }
public async Task InteractiveAuthProvider_ShouldGetNewAccessTokenWithNoIAccount() { UserAssertion assertion = new UserAssertion("access_token"); 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 } } } } }); AuthenticationResult newAuthResult = MockAuthResult.GetAuthenticationResult(); _mockClientApplicationBase.Setup((pca) => pca.AcquireTokenAsync(_scopes, It.IsAny <IAccount>(), UIBehavior.SelectAccount, null, null, _commonAuthority, null)) .ReturnsAsync(newAuthResult); InteractiveAuthenticationProvider authProvider = new InteractiveAuthenticationProvider(_mockClientApplicationBase.Object, _scopes); await authProvider.AuthenticateRequestAsync(httpRequestMessage); Assert.IsInstanceOfType(authProvider.ClientApplication, typeof(IPublicClientApplication), "Unexpected client application set."); Assert.IsNotNull(httpRequestMessage.Headers.Authorization, "Unexpected auhtorization header set."); Assert.AreEqual(newAuthResult.AccessToken, httpRequestMessage.Headers.Authorization.Parameter, "Unexpected access token set."); }
// public static async Task Run() // { // var clientId = "7515c9fd-d9d2-4aa5-b960-d5b3c0032502"; // var scopes = new List<string>() { "User.ReadBasic.All" }.ToArray(); // IPublicClientApplication clientApplication = InteractiveAuthenticationProvider.CreateClientApplication(clientId); // InteractiveAuthenticationProvider authProvider = new InteractiveAuthenticationProvider(clientApplication, scopes); // GraphServiceClient graphClient = new GraphServiceClient(authProvider); // //var users = await graphClient.Users // // .Request() // // .Select(e => new { // // e.DisplayName, // // e.GivenName, // // e.PostalCode, // // e.Manager // // }) // // .GetAsync(); // var users = await graphClient.Users //.Request() //.Select(e => new //{ // e.DisplayName, // e.GivenName, // e.PostalCode, // e.Manager //}) //.GetAsync(); // foreach (var user in users) // { // //Console.WriteLine(user.GivenName); // lstString.Add(user.DisplayName); // } // } #endregion public static async Task Run() { var clientId = "Cliebt ID"; var scopes = new List <string>() { "User.ReadBasic.All" }.ToArray(); IPublicClientApplication clientApplication = InteractiveAuthenticationProvider.CreateClientApplication(clientId); InteractiveAuthenticationProvider authProvider = new InteractiveAuthenticationProvider(clientApplication, scopes); GraphServiceClient graphClient = new GraphServiceClient(authProvider); var users = await graphClient.Users .Request() .Select(e => new { e.DisplayName, e.GivenName, e.PostalCode, e.Manager }) .GetAsync(); foreach (var user in users) { //Console.WriteLine(user.GivenName); lstString.Add(user.DisplayName); } }
public static async Task GetAllUsers() { IPublicClientApplication app = PublicClientApplicationBuilder.Create("9914776b-f46e-41a9-a8ee-56af1134e379") // This is a throwaway ClientId .WithTenantId("d5fe491b-5987-4770-a68f-477c204cd1ca") // This is a demo tenant. .Build(); var authProvider = new InteractiveAuthenticationProvider(app, new string[] { "User.Read", "User.Read.All" }); // Get the standard middleware for Graph (Auth, Redirect, Retry, Compression) var handlers = GraphClientFactory.CreateDefaultHandlers(authProvider); // Add a trace handler, and ChaosHandler handlers.Add(new GraphTraceHandler()); handlers.Add(new ChaosHandler()); // Create a customized HttpClient based on these handlers HttpClient client = GraphClientFactory.Create(handlers); // Create a GraphServiceClient based on the HttpClient var gc = new GraphServiceClient(client); // Get all the user Ids var users = await gc.Users.Request().Select(u => u.Id).GetAsync(); // Iterate over that paged list var iterator = PageIterator <User> .CreatePageIterator(gc, users, (u) => { // Get User details gc.Users[u.Id].Request().GetAsync().GetAwaiter().GetResult(); Console.WriteLine(u.Id); return(true); }); await iterator.IterateAsync(); }
static async Task Main(string[] args) { const string _clientID = "c75fa98e-6c43-4f3f-9768-3abb31a85384"; const string _tenantID = "9bbb2b0f-1905-4262-b30b-72f1acff58d0"; //4. Build App var app = PublicClientApplicationBuilder .Create(_clientID) .WithAuthority(AzureCloudInstance.AzurePublic, _tenantID) .WithRedirectUri("Http://localhost:9001") .Build(); //5. Provide Permission to read profile string[] scopes = { "user.read" }; //6. Graph Operation Get the token using Interactive Authentication var provider = new InteractiveAuthenticationProvider(app, scopes); var client = new GraphServiceClient(provider); // Get the Profile Details User me = await client.Me.Request().GetAsync(); Console.WriteLine($"Display Name :\t {me.DisplayName}"); // AuthenticationResult result = await app.AcquireTokenInteractive(scopes).ExecuteAsync(); // Console.WriteLine($"Obtained Token :\t {result.AccessToken}"); }
static void Main(string[] args) { string clientId = "e0cefc2c-1104-4622-81ab-f7bxxx3112"; //e.g. 01e54f9a-81bc-4dee-b15d-e661ae13f382 IPublicClientApplication publicClientApplication = PublicClientApplicationBuilder .Create(clientId) .WithRedirectUri("msale0cefc2c-1104-4622-81ab-f7b421063112://auth") .Build(); string[] scopes = new string[] { "Sites.ReadWrite.All" }; InteractiveAuthenticationProvider authProvider = new InteractiveAuthenticationProvider(publicClientApplication, scopes); GraphServiceClient graphClient = new GraphServiceClient(authProvider); var queryOptions = new List <QueryOption>() { new QueryOption("expand", "fields") }; var items = graphClient.Sites["abc.sharepoint.com,8f9005da-df16-4c30-9b91-4980e1e40d31,af165982-3b91-4d97-a12d-2a47800cc52d"] .Lists["User Information List"].Items .Request(queryOptions) .GetAsync(); Console.WriteLine(items.Result); Console.ReadKey(); }
public void InteractiveAuthProvider_ShouldCreatePublicClientApplicationWithMandatoryParams() { IClientApplicationBase clientApp = InteractiveAuthenticationProvider.CreateClientApplication(_clientId); Assert.IsInstanceOfType(clientApp, typeof(PublicClientApplication), "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."); }
public async Task Authenticate() { InteractiveAuthenticationProvider authProvider = new InteractiveAuthenticationProvider(publicClientApp, new string[] { "user.read" }); graphClient = new GraphServiceClient(authProvider); await LoadMe(); }
public void InteractiveAuthProvider_ShouldCreatePublicClientApplicationForConfiguredCloud() { string testTenant = "infotest"; IClientApplicationBase clientApp = InteractiveAuthenticationProvider.CreateClientApplication(_clientId, null, testTenant, NationalCloud.China); Assert.IsInstanceOfType(clientApp, typeof(PublicClientApplication), "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."); }
public void InteractiveAuthProvider_ShouldConstructAuthProviderWithPublicClientApp() { PublicClientApplication pca = new PublicClientApplication(_clientId, _commonAuthority, new TokenCache()); InteractiveAuthenticationProvider auth = new InteractiveAuthenticationProvider(pca, _scopes); Assert.IsInstanceOfType(auth, typeof(IAuthenticationProvider), "Unexpected auth provider set."); Assert.IsNotNull(auth.ClientApplication, "Client application not initialized."); Assert.AreSame(pca, auth.ClientApplication, "Wrong client application set."); }
private static async Task GetNameFromGraph(IPublicClientApplication app) { var provider = new InteractiveAuthenticationProvider(app, _scopes); var client = new GraphServiceClient(provider); User me = await client.Me.Request().GetAsync(); Console.WriteLine($"Graph: Hello {me.DisplayName}"); }
#pragma warning disable CS1998 // Async method lacks 'await' operators and will run synchronously public async Task TestInteractiveConstructorNoDI_DefaultValues() #pragma warning restore CS1998 // Async method lacks 'await' operators and will run synchronously { var provider = new InteractiveAuthenticationProvider(); Assert.IsNotNull(provider); Assert.IsNotNull(provider.ClientId); Assert.IsNotNull(provider.TenantId); Assert.IsNotNull(provider.RedirectUri); }
public GraphClient() { IPublicClientApplication publicClientApplication = PublicClientApplicationBuilder .Create(clientId) .WithRedirectUri("https://CLIENT ID OR SOMETHING ELSE YOU SET AS REDIRECT URI IN YOUR APP") .Build(); InteractiveAuthenticationProvider authProvider = new InteractiveAuthenticationProvider(publicClientApplication); theGraphClient = new GraphServiceClient(authProvider); }
public void ShouldUseDefaultScopeUrlWhenScopeIsNull() { HttpRequestMessage httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, "http://example.org/foo"); var mock = Mock.Of <IPublicClientApplication>(); InteractiveAuthenticationProvider authProvider = new InteractiveAuthenticationProvider(mock, null); Assert.NotNull(authProvider.Scopes); Assert.True(authProvider.Scopes.Count().Equals(1)); Assert.Equal(AuthConstants.DefaultScopeUrl, authProvider.Scopes.FirstOrDefault()); }
public MainWindow() { InitializeComponent(); var app = PublicClientApplicationBuilder.Create(ClientId) .WithAuthority(AzureCloudInstance.AzurePublic, Tenant) .Build(); var authProvider = new InteractiveAuthenticationProvider(app); GraphClient = new GraphServiceClient(authProvider); }
/** Logs the user into their Microsoft Live account using Microsoft Graphs API. * To increase the number of permissions add to scopes array. Right now our graphs * client has user email access and read/write permission to users onedrive. */ public static async void Login() { var clientId = "1912fef8-e092-4702-8012-cb3e535138a8"; // microsoft graphs api ID. var app = PublicClientApplicationBuilder.Create(clientId) .WithRedirectUri("http://localhost") .Build(); string[] scopes = new string[] { // add more scopes here if you want more access to users data using graphs api. "https://graph.microsoft.com/user.read", "https://graph.microsoft.com/email", "https://graph.microsoft.com/Files.ReadWrite.AppFolder" }; var result = await app.AcquireTokenInteractive(scopes) .ExecuteAsync(); InteractiveAuthenticationProvider authProvider = new InteractiveAuthenticationProvider(app, scopes); graphClient = new GraphServiceClient(authProvider); var user = await graphClient.Me.Request().GetAsync(); email = user.Mail; DatabaseCommunicator.email = user.Mail; if (Program.connected_to_database) { if (!DatabaseCommunicator.CheckRegistration(email)) { // show registration box here. RegisterForm register = new RegisterForm(email); register.StartPosition = FormStartPosition.CenterScreen; register.Show(); } else { // User is already registered so we don't show registration. // get all the ticked whitelist categories. If it is first time user then we show messagebox asking to select categories. LoadCSESettings(); LoadPrivacySettings(); Program.LoadWhitelist(); LoadCategories(); } } else { // App isn't connected to database so we don't need to check if user is registered or not. LoadCSESettings(); LoadPrivacySettings(); Program.LoadWhitelist(); LoadCategories(); } }
private static InteractiveAuthenticationProvider PrepareInteractiveAuthenticationProvider() { var configuration = TestCommon.GetConfigurationSettings(); var clientId = configuration.GetValue <string>($"{TestGlobals.CredentialsConfigurationBasePath}:{interactiveConfigurationPath}:ClientId"); var tenantId = configuration.GetValue <string>($"{TestGlobals.CredentialsConfigurationBasePath}:{interactiveConfigurationPath}:TenantId"); var redirectUri = configuration.GetValue <Uri>($"{TestGlobals.CredentialsConfigurationBasePath}:{interactiveConfigurationPath}:Interactive:RedirectUri"); var provider = new InteractiveAuthenticationProvider( clientId, tenantId, redirectUri); return(provider); }
public Connector() { // Create Client Application and Authentication Provider _clientApp = InteractiveAuthenticationProvider.CreateClientApplication( _clientId, FileBasedTokenStorageProvider.Instance); _clientApp.RedirectUri = "https://login.microsoftonline.com/common/oauth2/nativeclient"; var authProvider = new InteractiveAuthenticationProvider(_clientApp, _scopes); // Create GraphServiceClient with middleware pipeline setup _graph = new GraphServiceClient(authProvider); }
public Connector() { // Create Client Application and Authentication Provider _clientApp = InteractiveAuthenticationProvider.CreateClientApplication( _clientId, new FileBasedTokenStorageProvider()); _clientApp.RedirectUri = "urn:ietf:wg:oauth:2.0:oob:myappname"; var authProvider = new InteractiveAuthenticationProvider(_clientApp, _scopes); // Create GraphServiceClient with middleware pipeline setup _graph = new GraphServiceClient(authProvider); }
static async Task Main(string[] args) { string clientId = AppSettings.LoadAppSettings().ClientId; string tenantId = AppSettings.LoadAppSettings().TenantId; var publicClientApp = PublicClientApplicationBuilder.Create(clientId) .WithRedirectUri("http://localhost") .WithAuthority(AzureCloudInstance.AzurePublic, tenantId) .Build(); var authProvider = new InteractiveAuthenticationProvider(publicClientApp); var _graphServiceClient = new GraphServiceClient(authProvider); var users = new Users(_graphServiceClient); await users.addUsers(); }
static void Main(string[] args) { string[] scopes = { "https://graph.microsoft.com/.default" }; IPublicClientApplication publicClientApplication = PublicClientApplicationBuilder .Create("cbc3***-ac27-4532-802d-303998a6e712") .Build(); InteractiveAuthenticationProvider authenticationProvider = new InteractiveAuthenticationProvider(publicClientApplication, scopes); GraphServiceClient graphClient = new GraphServiceClient(authenticationProvider); User me = graphClient.Me.Request() .GetAsync().Result; Console.Write(me.DisplayName); }
public static async Task CreateGraphRepository(TestContext _) { if (!RunTests) { Assert.Inconclusive("Tests not run because I assume this is in contiguous integration. Set RunTests to true if this is not the case."); } var publicClientApp = PublicClientApplicationBuilder.Create(ClientId) .WithRedirectUri("http://localhost") .WithAuthority(AzureCloudInstance.AzurePublic, Tenant) .Build(); var authProvider = new InteractiveAuthenticationProvider(publicClientApp); _graphServiceClient = new GraphServiceClient(authProvider); _groupRepo = new GraphGroupRepository(_graphServiceClient, new MockLogger()); await DeleteOldObjects("microsoft.graph.group"); await DeleteOldObjects("microsoft.graph.user"); // not the most efficient, but writing all the batching logic to add a bunch of users is a pain // we don't delete the users after, so this only has to be done once anyways. var users = await _graphServiceClient.Users.Request().Filter("startswith(MailNickname, 'testuser')").GetAsync(); HandleExistingUsers(users.CurrentPage); while (users.NextPageRequest != null) { users = await users.NextPageRequest.GetAsync(); HandleExistingUsers(users.CurrentPage); } try { for (int i = 0; i < _testUsers.Length; i++) { if (_testUsers[i] == null) { await AddNewUser(i); } } } catch (ServiceException ex) { Assert.Fail("Failed creating user. This happens sometimes. Please run the tests again and it'll pick up where it left off. Exception: {0}", ex); } }
private static async Task <Stream> GetFileFromOneDriveAsync() { IPublicClientApplication publicClientApplication = PublicClientApplicationBuilder .Create("5cd44a93-b9bd-48cf-b99b-772cd08aa0e0") .WithRedirectUri("http://localhost") .Build(); var authProvider = new InteractiveAuthenticationProvider(publicClientApplication, new[] { "Files.read" }); GraphServiceClient graphClient = new GraphServiceClient(authProvider); var stream = await graphClient.Me.Drive.Items["9694446503212449!333"].Content .Request() .GetAsync(); return(stream); }
private static async Task <Stream> GetFile() { IPublicClientApplication publicClientApplication = PublicClientApplicationBuilder .Create("2vs23b94-s8gj-4eff-f9fn-bdfvd34aw0xw") .WithRedirectUri("http://localhost") .Build(); var authentificationProvider = new InteractiveAuthenticationProvider(publicClientApplication, new[] { "Files.read" }); GraphServiceClient graphClient = new GraphServiceClient(authentificationProvider); var stream = await graphClient.Me.Drive.Items["385737!87775463263}"].Content .Request() .GetAsync(); return(stream); }
#pragma warning disable CS1998 // Async method lacks 'await' operators and will run synchronously public async Task TestInteractiveConstructorNoDI_NullRedirectUri() #pragma warning restore CS1998 // Async method lacks 'await' operators and will run synchronously { var configuration = TestCommon.GetConfigurationSettings(); var clientId = configuration.GetValue <string>($"{TestGlobals.CredentialsConfigurationBasePath}:{interactiveConfigurationPath}:ClientId"); var tenantId = configuration.GetValue <string>($"{TestGlobals.CredentialsConfigurationBasePath}:{interactiveConfigurationPath}:TenantId"); var provider = new InteractiveAuthenticationProvider( clientId, tenantId, redirectUri: null); Assert.IsNotNull(provider); Assert.IsNotNull(provider.ClientId); Assert.IsNotNull(provider.TenantId); Assert.IsNotNull(provider.RedirectUri); }
/// <summary> /// Easily creates a <see cref="MsalProvider"/> from a ClientId. /// </summary> /// <example> /// <code> /// ProviderManager.Instance.GlobalProvider = await QuickCreate.CreateMsalProviderAsync("MyClientId"); /// </code> /// </example> /// <param name="clientid">Registered ClientId</param> /// <param name="redirectUri">RedirectUri for auth response.</param> /// <param name="scopes">List of Scopes to initially request.</param> /// <returns>New <see cref="MsalProvider"/> reference.</returns> public static async Task <MsalProvider> CreateMsalProviderAsync(string clientid, string redirectUri = "https://login.microsoftonline.com/common/oauth2/nativeclient", string[] scopes = null) { var client = PublicClientApplicationBuilder.Create(clientid) .WithAuthority(AzureCloudInstance.AzurePublic, AadAuthorityAudience.AzureAdAndPersonalMicrosoftAccount) .WithRedirectUri(redirectUri) .WithClientName(ProviderManager.ClientName) .WithClientVersion(Assembly.GetExecutingAssembly().GetName().Version.ToString()) .Build(); if (scopes == null) { scopes = new string[] { string.Empty }; } var provider = new InteractiveAuthenticationProvider(client, scopes); return(await MsalProvider.CreateAsync(client, provider)); }
public static async Task Main(string[] args) { var app = PublicClientApplicationBuilder .Create(_clientId) .WithAuthority(AzureCloudInstance.AzurePublic, _tenantId) .WithRedirectUri("http://localhost") .Build(); // AuthenticationResult result = await app.AcquireTokenInteractive(scopes).ExecuteAsync(); // Console.WriteLine($"Token:\t{result.AccessToken}"); string[] scopes = { "user.read" }; var provider = new InteractiveAuthenticationProvider(app, scopes); var client = new GraphServiceClient(provider); User me = await client.Me.Request().GetAsync(); Console.WriteLine($"Display Name:\t{me.DisplayName} and Age Group:\t{me.AgeGroup}"); }
public void ShouldConstructAuthProviderWithPublicClientApp() { string clientId = "00000000-0000-0000-0000-000000000000"; string authority = "https://login.microsoftonline.com/organizations/"; IEnumerable <string> scopes = new List <string> { "User.ReadBasic.All" }; IPublicClientApplication publicClientApplication = PublicClientApplicationBuilder .Create(clientId) .WithAuthority(authority) .Build(); InteractiveAuthenticationProvider auth = new InteractiveAuthenticationProvider(publicClientApplication, scopes); Assert.IsAssignableFrom <IAuthenticationProvider>(auth); Assert.NotNull(auth.ClientApplication); Assert.Equal(publicClientApplication, auth.ClientApplication); }
public GraphSdkClient() { /* * Refer https://docs.microsoft.com/en-us/graph/sdks/create-client?tabs=CS for more information on Microsoft Graph client. */ var scopes = new List <string>() { CommonConstants.GraphResource + "/.default" }; // creating client for admin { var publicClientApplicationBuilder = PublicClientApplicationBuilder .Create(CommonConstants.ClientId) .WithRedirectUri("http://localhost") .Build(); var authProvider = new InteractiveAuthenticationProvider(publicClientApplicationBuilder, scopes); // GraphServiceClient, by design, will create one HttpClient per client. // To avoid this, we have to provide our own HttpProvider, that uses a static HttpClient. this.graphAdminClient = new GraphServiceClient(authProvider, new HttpProvider()); // Make a request to /print/services so the we can cache the UserToken in the HttpProvider class. this.GetPrintServices(graphAdminClient, scopes).Wait(); } // creating client for app permission { string scope = CommonConstants.GraphResource + "/.default"; var confidentialClientApplication = ConfidentialClientApplicationBuilder .Create(CommonConstants.ClientId) .WithTenantId(CommonConstants.TenantId) .WithClientSecret(CommonConstants.ClientSecret) .Build(); var clientCredentialAuthProvider = new ClientCredentialProvider(confidentialClientApplication, scope); this.graphAppClient = new GraphServiceClient(clientCredentialAuthProvider, new HttpProvider()); } }