public GraphApiReader(
            IOptions <GraphServiceCredentials> graphServiceConfiguration,
            IOptions <NotificationConfiguration> notificationConfiguration)
        {
            if (graphServiceConfiguration == null)
            {
                throw new ArgumentNullException(nameof(graphServiceConfiguration));
            }
            if (notificationConfiguration == null)
            {
                throw new ArgumentNullException(nameof(notificationConfiguration));
            }

            var confidentialClientApplication = ConfidentialClientApplicationBuilder
                                                .Create(graphServiceConfiguration.Value.AppId)
                                                .WithTenantId(graphServiceConfiguration.Value.TenantId)
                                                .WithClientSecret(graphServiceConfiguration.Value.ClientSecret)
                                                .Build();
            var authProvider = new ClientCredentialProvider(confidentialClientApplication);

            _graphServiceClient = new GraphServiceClient(authProvider);

            _expiringSecretsSelector = new Func <PasswordCredential, bool>(c =>
                                                                           c.EndDateTime <= DateTime.Now.AddDays(notificationConfiguration.Value.ExpirationThresholdInDays));

            _expiringCertificatesSelector = new Func <KeyCredential, bool>(c =>
                                                                           c.EndDateTime <= DateTime.Now.AddDays(notificationConfiguration.Value.ExpirationThresholdInDays));
        }
Example #2
0
        public async Task AuthenticateAsync()
        {
            try
            {
                // portal details
                var confidentialClientApplication = ConfidentialClientApplicationBuilder
                                                    .Create("clientid")            // from azure portal
                                                    .WithTenantId("tenantid")      // from azure portal
                                                    .WithClientSecret("secretkey") // from azure portal
                                                    .Build();

                var authProvider = new ClientCredentialProvider(confidentialClientApplication);
                var graphClient  = new GraphServiceClient(authProvider);

                var invitation = new Invitation
                {
                    InvitedUserDisplayName  = "Invitee Name",
                    InvitedUserEmailAddress = "Invitee email",
                    InviteRedirectUrl       = "https://myapp.com",
                    SendInvitationMessage   = true,
                    InvitedUserMessageInfo  = new InvitedUserMessageInfo {
                        CustomizedMessageBody = "Message"
                    }
                };

                var x = await graphClient.Invitations.Request().AddAsync(invitation);

                Console.WriteLine("Id: " + x.Id);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
        internal static GraphConnectionContext GetConnectionContext(KeyedCollection <string, ConfigParameter> configParameters)
        {
            logger.Info($"Setting up connection to {configParameters[ConfigParameterNames.TenantDomain].Value}");

            System.Net.ServicePointManager.DefaultConnectionLimit = MicrosoftTeamsMAConfigSection.Configuration.ConnectionLimit;
            GlobalSettings.ExportThreadCount = MicrosoftTeamsMAConfigSection.Configuration.ExportThreads;

            IConfidentialClientApplication confidentialClientApplication = ConfidentialClientApplicationBuilder
                                                                           .Create(configParameters[ConfigParameterNames.ClientId].Value)
                                                                           .WithTenantId(configParameters[ConfigParameterNames.TenantDomain].Value)
                                                                           .WithClientSecret(configParameters[ConfigParameterNames.Secret].SecureValue.ConvertToUnsecureString())
                                                                           .Build();

            ClientCredentialProvider authProvider = new ClientCredentialProvider(confidentialClientApplication);

            JsonConvert.DefaultSettings = () => new JsonSerializerSettings
            {
                NullValueHandling = NullValueHandling.Ignore
            };

            var client     = new GraphServiceClient(authProvider);
            var betaClient = new Beta.GraphServiceClient(authProvider);

            return(new GraphConnectionContext()
            {
                Client = client,
                BetaClient = betaClient,
                UserFilter = new UserFilter(client, configParameters)
            });
        }
        public IGraphServiceClient Initialize()
        {
            if (_configuration == null)
            {
                throw new ArgumentNullException($"{_configuration} cannot be null.");
            }

            GraphServiceClient graphClient;

            try
            {
                // Initiate client application
                var confidentialClientApplication = ConfidentialClientApplicationBuilder
                                                    .Create(_configuration.ClientId)
                                                    .WithTenantId(_configuration.TenantId)
                                                    .WithClientSecret(_configuration.ClientSecret)
                                                    .Build();

                // Create the auth provider
                var authProvider = new ClientCredentialProvider(confidentialClientApplication);

                // Create Graph Service Client
                graphClient = new GraphServiceClient(authProvider);
            }
            catch (ServiceException ex)
            {
                //throw new GraphApiClientException(
                //    HttpStatusCode.BadRequest,
                //    $"Could not create a Graph Service Client: {ex.Message}");
                throw ex;
            }

            // Return
            return(graphClient);
        }
        static async Task Main(string[] args)
        {
            string clientId     = "<clientId>";
            string tenantId     = "<tenantId>";
            string clientSecret = "<clientSecret>";

            // Build a client application.​
            var clientApplication = PublicClientApplicationBuilder.Create(clientId);

            clientApplication = clientApplication.WithTenantId(tenantId);

            // Create an authentication provider by username password.​
            IConfidentialClientApplication confidentialClientApplication = ConfidentialClientApplicationBuilder
                                                                           .Create(clientId)
                                                                           .WithTenantId(tenantId)
                                                                           .WithClientSecret(clientSecret)
                                                                           .Build();
            ClientCredentialProvider authProvider = new ClientCredentialProvider(confidentialClientApplication);

            // Create a new instance of GraphServiceClient with the authentication provider.​
            GraphServiceClient graphClient = new GraphServiceClient(authProvider​);

            // Makes a request to https://graph.microsoft.com/v1.0/me​
            var users = await graphClient.Users.Request().GetAsync();

            foreach (var user in users)
            {
                Console.WriteLine($"{user.DisplayName}");
            }
        }
Example #6
0
        static async Task Main(string[] args)
        {
            string clientID     = ConfigurationManager.AppSettings["AppID"].ToString();
            string clientSecret = ConfigurationManager.AppSettings["Secret"].ToString(); // Put the Client Secret from above here.

            sqlConnectionString = ConfigurationManager.AppSettings["ConnectionString"].ToString();
            storageString       = ConfigurationManager.AppSettings["StorageString"].ToString();
            storageacc          = CloudStorageAccount.Parse(storageString);

            Uri microsoftLogin = new Uri("https://login.microsoftonline.com/");
            //string tenantID = "M365EDU736909.onmicrosoft.com"; // Put the Azure AD Tenant ID from above here.
            string tenantID = ConfigurationManager.AppSettings["Domain"].ToString(); // Put the Azure AD Tenant ID from above here.
            // Build a client application.
            IConfidentialClientApplication confidentialClientApplication = ConfidentialClientApplicationBuilder
                                                                           .Create(clientID)
                                                                           .WithTenantId(tenantID)
                                                                           .WithClientSecret(clientSecret)
                                                                           .Build();

            ClientCredentialProvider authProvider = new ClientCredentialProvider(confidentialClientApplication);

            // Create a new instance of GraphServiceClient with the authentication provider.
            graphClient = new GraphServiceClient(authProvider);

            //Pull Information for the selected templates from their source teamid
            dbConnect = new SqlConnection(sqlConnectionString);
            dbConnect.Open();

            await ExportTeamChannelsAndFiles();

            dbConnect.Close();
        }
Example #7
0
        //https://github.com/microsoftgraph/msgraph-sdk-dotnet-auth

        public O365Client()
        {
            IConfidentialClientApplication clientApplication      = ClientCredentialProvider.CreateClientApplication(_clientId, new ClientCredential(_clientSecret), null, _tenantId);
            ClientCredentialProvider       authenticationProvider = new ClientCredentialProvider(clientApplication);

            _graphServiceClient = new GraphServiceClient(authenticationProvider);
        }
        public async Task <OAuthUserModel> GetIdByEmail(string EmailOrObjectId)
        {
            OAuthUserModel model = new OAuthUserModel();

            try
            {
                var confidentialClient = ConfidentialClientApplicationBuilder
                                         .Create(_clientId)
                                         .WithTenantId(_tenantId)
                                         .WithClientSecret(_clientSecret)
                                         .Build();
                ClientCredentialProvider authProvider = new ClientCredentialProvider(confidentialClient);
                GraphServiceClient       graphClient  = new GraphServiceClient(authProvider);
                var user = await graphClient.Users[EmailOrObjectId].Request().GetAsync();

                model.User           = user;
                model.AuthProvider   = authProvider;
                model.GraphService   = graphClient;
                model.Status.Code    = 200;
                model.Status.Message = "OK";

                return(model);
            }
            catch (Exception e)
            {
                model.Status.Code    = 406;
                model.Status.Message = e.Message;
                return(model);
            }
        }
        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"];
        }
Example #10
0
        public override void Configure(IFunctionsHostBuilder builder)
        {
            IConfigurationBuilder configBuilder = new ConfigurationBuilder();

            configBuilder = ForgeAlternativeConfigurationExtensions.AddForgeAlternativeEnvironmentVariables(configBuilder);
            configBuilder.Build();

            IConfiguration configuration = configBuilder.Build(); // builder.GetContext().Configuration;

            builder.Services.AddDesignAutomation(configuration);
            builder.Services.AddSingleton <Autodesk.Forge.TwoLeggedApi>(new TwoLeggedApi());

            // Initialize the client credential auth provider
            IConfidentialClientApplication confidentialClientApplication = ConfidentialClientApplicationBuilder
                                                                           .Create(Environment.GetEnvironmentVariable("AppId"))
                                                                           .WithTenantId(Environment.GetEnvironmentVariable("TenantId"))
                                                                           .WithClientSecret(Environment.GetEnvironmentVariable("ClientSecret"))
                                                                           .Build();
            ClientCredentialProvider authProvider       = new ClientCredentialProvider(confidentialClientApplication);
            GraphServiceClient       graphServiceClient = new GraphServiceClient(authProvider);

            // Set up the Microsoft Graph service client with client credentials
            builder.Services.AddSingleton <GraphServiceClient>(graphServiceClient);

            builder.Services.AddSingleton <Utilities>(new Utilities(graphServiceClient));
        }
Example #11
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            var graphOptions = new MSGraphOptions();

            Configuration.Bind("MSGraph", graphOptions);

            services.AddSingleton(graphOptions);

            IConfidentialClientApplication confidentialClientApplication = ConfidentialClientApplicationBuilder
                                                                           .Create(graphOptions.GraphClientId)
                                                                           .WithTenantId(graphOptions.TenantID)
                                                                           .WithClientSecret(graphOptions.GraphClientSecret)
                                                                           .Build();

            var mSGraphauthProvider = new ClientCredentialProvider(confidentialClientApplication, "https://graph.microsoft.com/.default");

            services.AddSingleton(mSGraphauthProvider);

            services.AddHttpClient <IMSGraphServiceClientAdaptor, MSGraphServiceClientAdaptor>(PolicyNames.GraphHttpClient)
            .AddPolicyHandler(HttpPolicies.GetRetryPolicy());

            services.AddSingleton <IMSGraphServiceClientAdaptor, MSGraphServiceClientAdaptor>();

            services.AddControllers();
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="AzureActiveDirectoryRepository"/> class.
        /// </summary>
        /// <param name="loggerFactory">Logger factory for creating logger</param>
        /// <param name="configuration">Configuration for this Azure Active Directory repository</param>
        public AzureActiveDirectoryRepository(ILoggerFactory loggerFactory, AzureActiveDirectoryConfiguration configuration)
            : base(loggerFactory)
        {
            this.Logger.LogTrace("Beginning construction of Azure Active Directory Repository");

            // Sanity check input arguments
            configuration = Ensure.IsNotNull(() => configuration);
            configuration.Validate();

            // Copy over domain from configuration
            this.domain = Ensure.IsNotNullOrWhitespace(() => configuration.Domain);

            // Build Graph Service Client
            var confidentialClientApplication = ConfidentialClientApplicationBuilder
                                                .Create(configuration.AppId)
                                                .WithTenantId(configuration.TenantId)
                                                .WithClientSecret(configuration.ClientSecret)
                                                .Build();

            var authProvider = new ClientCredentialProvider(confidentialClientApplication);

            this.graphServiceClient = new GraphServiceClient(authProvider);

            this.Logger.LogTrace("Completed construction of Azure Active Directory Repository");
        }
Example #13
0
        public async Task ImportContactsFromAzure2Db()
        {
            //Build a client application.
            var confidentialClientApplication = ConfidentialClientApplicationBuilder
                                                .Create("b94d1d3d-3f7d-4f83-bb4a-751f46b72d8e")
                                                .WithTenantId("2e18f15a-865a-4f40-bc98-c9fb24d156af")
                                                .WithClientSecret("RW-qrUhAk5_Fqh45~_s95xaC_7E2iJAYY2")
                                                .Build();
            var authProvider = new ClientCredentialProvider(confidentialClientApplication);
            // Create a new instance of GraphServiceClient with the authentication provider.
            var graphClient   = new GraphServiceClient(authProvider);
            var contactsAzure = await graphClient.Users.Request().GetAsync();

            var contactsDB = db.Contacts.ToList();

            foreach (var conA in contactsAzure)
            {
                var newUser = contactsDB.All(conD => conA.Id != conD.Guid);

                if (newUser)
                {
                    db.Contacts.Add((ContactModel)conA);
                }
            }
            db.SaveChanges();
        }
Example #14
0
        static void Main(string[] args)
        {
            string clientId     = "e0cexxxxx1063112"; //e.g. 01e54f9a-81bc-4dee-b15d-e661ae13f382
            string clientSecret = @"1kQxxxxxxxm05-qZ";
            string tenantID     = "8a400xxxx872cfeef";

            IConfidentialClientApplication confidentialClientApplication = ConfidentialClientApplicationBuilder
                                                                           .Create(clientId)
                                                                           .WithTenantId(tenantID)
                                                                           .WithClientSecret(clientSecret)
                                                                           .Build();

            ClientCredentialProvider authProvider = new ClientCredentialProvider(confidentialClientApplication);
            GraphServiceClient       graphClient  = new GraphServiceClient(authProvider);


            var totalitems = new List <Microsoft.Graph.ListItem>();


            var items = graphClient
                        .Sites["xxxx.sharepoint.com,5ae4xxxxx20ad27b850b,352d1542-3xxx41552082"]
                        .Lists["40418cxxxxe9f0129"].Items
                        .Request()
                        .GetAsync().Result;

            totalitems.AddRange(items.CurrentPage);
            while (items.NextPageRequest != null)
            {
                items = items.NextPageRequest.GetAsync().Result;
                totalitems.AddRange(items.CurrentPage);
            }

            Console.WriteLine(totalitems);
            Console.ReadKey();
        }
Example #15
0
        static async System.Threading.Tasks.Task Main(string[] args)
        {
            IConfidentialClientApplication confidentialClientApplication = ConfidentialClientApplicationBuilder
                                                                           .Create("clientId")
                                                                           .WithTenantId("tenantId")
                                                                           .WithClientSecret("clientSecret")
                                                                           .Build();

            ClientCredentialProvider authProvider = new ClientCredentialProvider(confidentialClientApplication);
            GraphServiceClient       graphClient  = new GraphServiceClient(authProvider);

            var result = await graphClient.Users
                         .Request()
                         .Select(e => new
            {
                e.DisplayName,
                e.Id,
                e.Identities
            })
                         .GetAsync();

            foreach (var user in result.CurrentPage)
            {
                Console.WriteLine(JsonConvert.SerializeObject(user));
            }
            Console.ReadLine();  // add this line or use "Ctrl + F5" to run the code
        }
Example #16
0
        private static void CreateAuthorizationProvider(IConfigurationRoot appInformation)
        {
            var clientId     = appInformation["applicationId"];
            var tenantId     = appInformation["tenantId"];
            var clientSecret = appInformation["applicationSecret"];
            var redirectUri  = appInformation["redirectUri"];

            IConfidentialClientApplication confidentialClientApplication = ConfidentialClientApplicationBuilder
                                                                           .Create(clientId)
                                                                           .WithAuthority(authorityUri: $"https://login.microsoftonline.com/{tenantId}/v2.0")
                                                                           .WithClientSecret(clientSecret)
                                                                           .WithRedirectUri(redirectUri)
                                                                           .Build();

            ClientCredentialProvider authenticationProvider = new ClientCredentialProvider(confidentialClientApplication);

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

            _graphServiceClient =
                new GraphServiceClient(new DelegateAuthenticationProvider(async(requestMessage) => {
                var authResult = await confidentialClientApplication
                                 .AcquireTokenForClient(scopes)
                                 .ExecuteAsync();
                requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", authResult.AccessToken);
            })
                                       );
        }
        public GraphData(IConfiguration config)
        {
            _teamsId = config["teamsId"];

            _applicationId         = config["GraphSettings:applicationId"];
            _tenantId              = config["GraphSettings:tenantId"];
            _secret                = config["GraphSettings:secret"];
            _anonymousUserId       = config["AnonymousUser:Id"];
            _anonymousUserPassword = config["AnonymousUser:Password"];
            _channelId             = config["GraphSettings:channelId"];
            _subscriptionUrl       = config["GraphSettings:subscriptionUrl"];

            IConfidentialClientApplication confidentialClientApplication = ConfidentialClientApplicationBuilder
                                                                           .Create(_applicationId)
                                                                           .WithTenantId(_tenantId)
                                                                           .WithClientSecret(_secret)
                                                                           .Build();

            ClientCredentialProvider authProvide = new ClientCredentialProvider(confidentialClientApplication);

            _client = new GraphServiceClient(authProvide);

            _credential = new Microsoft.IdentityModel.Clients.ActiveDirectory.ClientCredential(_applicationId, _secret);

            _authContext = new AuthenticationContext($"https://login.microsoftonline.com/{_tenantId}/");

            _httpClient = new HttpClient();
        }
 public MSGraphServiceClientAdaptor(ClientCredentialProvider authProvider, IHttpClientFactory httpClientFactory)
 {
     _graphServiceClient = new GraphServiceClient(httpClientFactory.CreateClient(PolicyNames.GraphHttpClient))
     {
         AuthenticationProvider = authProvider
     };
 }
Example #19
0
        static void Main(string[] args)
        {
            string clientId     = "your client id ";
            string clientSecret = "your client secret";
            string tenantID     = "your azure ad tanant/ directory id";

            IConfidentialClientApplication confidentialClientApplication = ConfidentialClientApplicationBuilder
                                                                           .Create(clientId)
                                                                           .WithTenantId(tenantID)
                                                                           .WithClientSecret(clientSecret)
                                                                           .Build();

            ClientCredentialProvider authProvider = new ClientCredentialProvider(confidentialClientApplication);

            GraphServiceClient graphClient = new GraphServiceClient(authProvider);

            var invitation = new Invitation
            {
                InvitedUserEmailAddress = "*****@*****.**",
                InviteRedirectUrl       = "https://yourapplication.com"
            };

            graphClient.Invitations
            .Request()
            .AddAsync(invitation).GetAwaiter().GetResult();

            Console.ReadLine();
        }
        public async Task <HttpResponseMessage> Post()
        {
            // The post body should contain a JSON representation of the AADGroup object
            HttpResponseMessage response = new HttpResponseMessage();
            string   content             = Request.Content.ReadAsStringAsync().Result;
            AADGroup model = null;

            try
            {
                // Convert the JSON payload to an AADGroup
                model = JsonConvert.DeserializeObject <AADGroup>(content);
            }
            catch (Exception ex)
            {
                response.StatusCode = HttpStatusCode.InternalServerError;
                response.Content    = new StringContent(ex.Message);
            }

            if (model != null)
            {
                // Authenticate to the Microsoft Graph and create a graph client
                string           clientId         = ConfigurationManager.AppSettings["ClientId"];
                string           clientSecret     = ConfigurationManager.AppSettings["ClientSecret"];
                string           tenant           = ConfigurationManager.AppSettings["Tenant"];
                ClientCredential clientCredential = new ClientCredential(clientSecret);
                IConfidentialClientApplication clientApplication = ClientCredentialProvider.CreateClientApplication(clientId, clientCredential, null, tenant);
                ClientCredentialProvider       authProvider      = new ClientCredentialProvider(clientApplication);
                GraphServiceClient             graphClient       = new GraphServiceClient(authProvider);

                var group = new Group
                {
                    Description     = model.Description,
                    DisplayName     = model.DisplayName,
                    MailEnabled     = model.MailEnabled,
                    MailNickname    = model.MailNickname,
                    SecurityEnabled = model.SecurityEnabled
                };

                try
                {
                    // Add the group to Azure AD
                    var newGroup = await graphClient.Groups
                                   .Request()
                                   .AddAsync(group);

                    // Capture the object ID of the newly created group
                    model.Id            = newGroup.Id;
                    response.StatusCode = HttpStatusCode.OK;
                    response.Content    = new StringContent(JsonConvert.SerializeObject(model), Encoding.UTF8, "application/json");
                }
                catch (Exception ex)
                {
                    response.StatusCode = HttpStatusCode.InternalServerError;
                    response.Content    = new StringContent(ex.Message);
                }
            }

            return(response);
        }
Example #21
0
        public void ClientCredentialProvider_ShouldCreateConfidentialClientApplicationWithMandatoryParams()
        {
            IClientApplicationBase clientApp = ClientCredentialProvider.CreateClientApplication(_clientId, _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.");
        }
Example #22
0
        public void ClientCredentialProvider_ShouldConstructAuthProviderWithConfidentialClientApp()
        {
            ConfidentialClientApplication cca  = new ConfidentialClientApplication(_clientId, _redirectUri, _clientCredential, new TokenCache(), null);
            ClientCredentialProvider      auth = new ClientCredentialProvider(cca);

            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.");
        }
Example #23
0
        public void ClientCredentialProvider_ShouldCreateConfidentialClientApplicationForConfiguredCloud()
        {
            string tenant = "infotest";
            IClientApplicationBase clientApp = ClientCredentialProvider.CreateClientApplication(_clientId, _clientCredential, null, tenant, 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], tenant), clientApp.Authority, "Wrong authority set.");
        }
Example #24
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);
        }
Example #25
0
        static async Task RetrieveClass(string ClassCode)
        {
            string clientID     = ConfigurationManager.AppSettings["AppID"].ToString();
            string clientSecret = ConfigurationManager.AppSettings["Secret"].ToString(); // Put the Client Secret from above here.


            Uri microsoftLogin = new Uri("https://login.microsoftonline.com/");
            //string tenantID = "M365EDU736909.onmicrosoft.com"; // Put the Azure AD Tenant ID from above here.
            string tenantID = ConfigurationManager.AppSettings["Domain"].ToString(); // Put the Azure AD Tenant ID from above here.
            // Build a client application.
            IConfidentialClientApplication confidentialClientApplication = ConfidentialClientApplicationBuilder
                                                                           .Create(clientID)
                                                                           .WithTenantId(tenantID)
                                                                           .WithClientSecret(clientSecret)
                                                                           .Build();

            ClientCredentialProvider authProvider = new ClientCredentialProvider(confidentialClientApplication);

            // Create a new instance of GraphServiceClient with the authentication provider.
            try
            {
                graphClient = new GraphServiceClient(authProvider);
                myLog.Log("Information", "", "Connection to graph successful");
            }
            catch (Exception)
            {
                myLog.Log("Error", "", "Connection to graph unsuccessful");
                System.Windows.Forms.Application.Exit();
            }

            IEducationRootClassesCollectionPage classes = graphClient.Education.Classes.Request().GetAsync().Result;

            while (classes.Count > 0)
            {
                foreach (var myClass in classes.CurrentPage)
                {
                    if (ClassCode == myClass.ExternalId)
                    {
                        teamID = myClass.Id;
                        return;
                    }
                }

                if (classes.NextPageRequest != null)
                {
                    classes = await classes.NextPageRequest.GetAsync();
                }
                else
                {
                    break;
                }
            }

            return;
        }
        public async Task Execute(AuthMessageSenderOptions authOptions, string subject, string message, string email)
        {
            Console.WriteLine(JsonSerializer.Serialize(authOptions));

            var confidentialClientApplication = ConfidentialClientApplicationBuilder
                                                .Create(authOptions.ClientID)
                                                .WithTenantId(authOptions.TenantID)
                                                .WithClientSecret(authOptions.ClientSecret)
                                                .Build();

            var authProvider = new ClientCredentialProvider(confidentialClientApplication);

            var graphClient = new GraphServiceClient(authProvider);

            var messageClass = new Message
            {
                Subject = subject,
                Body    = new ItemBody
                {
                    ContentType = BodyType.Html,
                    Content     = message
                },
                Sender = new Recipient
                {
                    EmailAddress = new EmailAddress
                    {
                        Address = authOptions.Sender
                    }
                },
                From = new Recipient
                {
                    EmailAddress = new EmailAddress
                    {
                        Address = authOptions.From
                    }
                },
                ToRecipients = new Recipient[]
                {
                    new Recipient
                    {
                        EmailAddress = new EmailAddress
                        {
                            Address = email
                        }
                    }
                }
            };

            await graphClient
            .Users[authOptions.Sender]
            .SendMail(messageClass)
            .Request()
            .PostAsync();
        }
        public GraphServiceClient Create()
        {
            var confidentialClientApplication = ConfidentialClientApplicationBuilder.Create(_azureAppSettings.ClientId)
                                                .WithClientSecret(_azureAppSettings.ClientSecret)
                                                .WithTenantId(_azureAppSettings.Tenant)
                                                .Build();

            var authProvider = new ClientCredentialProvider(confidentialClientApplication);

            return(new GraphServiceClient(authProvider));
        }
Example #28
0
        private void initializeB2C()
        {
            this.confidentialClientApplication = ConfidentialClientApplicationBuilder
                                                 .Create(this.appId)
                                                 .WithTenantId(this.tenantId)
                                                 .WithClientSecret(this.clientSecret)
                                                 .Build();
            this.authProvider = new ClientCredentialProvider(confidentialClientApplication);

            this.graphClient = new GraphServiceClient(authProvider);
        }
Example #29
0
        private static GraphServiceClient GetGraphClient()
        {
            IConfidentialClientApplication confidentialClientApplication = ConfidentialClientApplicationBuilder
                                                                           .Create(ClientId)
                                                                           .WithTenantId(TenantId)
                                                                           .WithClientSecret(ClientSecret)
                                                                           .Build();
            ClientCredentialProvider authProvider = new ClientCredentialProvider(confidentialClientApplication);

            return(new GraphServiceClient(authProvider));
        }
Example #30
0
        static async Task PrepTeamForImport()
        {
            string clientID     = ConfigurationManager.AppSettings["AppID"].ToString();
            string clientSecret = ConfigurationManager.AppSettings["Secret"].ToString(); // Put the Client Secret from above here.


            Uri microsoftLogin = new Uri("https://login.microsoftonline.com/");
            //string tenantID = "M365EDU736909.onmicrosoft.com"; // Put the Azure AD Tenant ID from above here.
            string tenantID = ConfigurationManager.AppSettings["Domain"].ToString(); // Put the Azure AD Tenant ID from above here.
            // Build a client application.
            IConfidentialClientApplication confidentialClientApplication = ConfidentialClientApplicationBuilder
                                                                           .Create(clientID)
                                                                           .WithTenantId(tenantID)
                                                                           .WithClientSecret(clientSecret)
                                                                           .Build();

            ClientCredentialProvider authProvider = new ClientCredentialProvider(confidentialClientApplication);

            // Create a new instance of GraphServiceClient with the authentication provider.
            try
            {
                graphClient = new GraphServiceClient(authProvider);
                myLog.Log("Information", "", "Connection to graph successful");
            }
            catch (Exception)
            {
                myLog.Log("Error", "", "Connection to graph unsuccessful");
                System.Windows.Forms.Application.Exit();
            }


            var item = await graphClient.Groups[teamID].Drive.Request().GetAsync();

            SPOURL = item.WebUrl.Split('/')[0] + "//" + item.WebUrl.Split('/')[2] + "/" + item.WebUrl.Split('/')[3] + "/";
            site   = item.WebUrl.Split('/')[4];

            System.Data.SqlClient.SqlCommand sqlCommand = new System.Data.SqlClient.SqlCommand();
            sqlCommand.Connection = dbConnect;

            sqlCommand.CommandText = "SELECT [channel] FROM [dbo].[TemplateChannels]  where templateid = @templateid;";
            sqlCommand.Parameters.Add("@templateid", System.Data.SqlDbType.BigInt);
            sqlCommand.Parameters["@templateid"].Value = templateID;

            SqlDataReader reader = sqlCommand.ExecuteReader();

            while (reader.Read())
            {
                if (reader["channel"].ToString() != "General")
                {
                    await CreateChannel(reader["channel"].ToString());
                }
            }
        }