Esempio n. 1
0
        public async Task <string> GetEmailFrom34ID(string input34id)
        {
            string email = string.Empty;

            var credential = new DefaultAzureCredential();
            var token      = credential.GetToken(
                new Azure.Core.TokenRequestContext(new[] { "https://graph.microsoft.com/.default" }));
            var accessToken        = token.Token;
            var graphServiceClient = new GraphServiceClient(
                new DelegateAuthenticationProvider((requestMessage) =>
            {
                requestMessage
                .Headers
                .Authorization = new AuthenticationHeaderValue("bearer", accessToken);
                return(Task.CompletedTask);
            }));

            // Retrieve a user by userPrincipalName
            var myuser = await graphServiceClient
                         .Users[input34id + "@hca.corpad.net"]
                         .Request()
                         .GetAsync();

            if (myuser != null)
            {
                email = myuser.Mail;
            }
            return(email);
        }
Esempio n. 2
0
 public static IHostBuilder CreateHostBuilder(string[] args)
 {
     if (IsProduction && false)
     {
         return(Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
         {
             webBuilder.UseStartup <Startup>();
         }).ConfigureAppConfiguration((context, config) => {
             var builtConfig = config.Build();
             var valtName = builtConfig["VaultName"];
             var keyVaultClient = new KeyVaultClient(async(authority, resource, scope) =>
             {
                 var credential = new DefaultAzureCredential(false);
                 var token = credential.GetToken(
                     new Azure.Core.TokenRequestContext(
                         new[] { "https://vault.azure.net/.default" }));
                 return token.Token;
             });
             config.AddAzureKeyVault(valtName, keyVaultClient, new DefaultKeyVaultSecretManager());
         }));
     }
     else
     {
         return(Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
         {
             webBuilder.UseStartup <Startup>();
         }));
     }
 }
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            var rc = new TokenRequestContext(new string[] { "https://graph.microsoft.com/.default" });

            AzureEventSourceListener.CreateConsoleLogger();
            services.AddControllersWithViews();
            services.AddRazorPages();

            // Configure the credential options
            var options = new DefaultAzureCredentialOptions
            {
                ExcludeVisualStudioCodeCredential = true,
                ExcludeVisualStudioCredential     = true,
                Diagnostics = { IsLoggingEnabled = true }
            };

            // Create a DefaultAzureCredential
            var cred = new DefaultAzureCredential(options);

            // Initialize a BlobContainerClient with the credential.
            services.AddSingleton(new BlobContainerClient(new Uri(Configuration["BlobUri"]), cred));

            // Initialize a Graph client with the credential.
            GraphServiceClient graphServiceClient = new GraphServiceClient(
                new DelegateAuthenticationProvider((requestMessage) =>
            {
                requestMessage
                .Headers
                .Authorization = new AuthenticationHeaderValue("Bearer", cred.GetToken(rc).Token);

                return(Task.CompletedTask);
            }));

            services.AddSingleton(graphServiceClient);
        }
Esempio n. 4
0
        public static string GetToken()
        {
            return(AuthUtil.GetTokenFromConsole());

https:      //yourazurecoach.com/2020/08/13/managed-identity-simplified-with-the-new-azure-net-sdks/
            var options = new DefaultAzureCredentialOptions
            {
                ExcludeEnvironmentCredential        = false,
                ExcludeManagedIdentityCredential    = false,
                ExcludeSharedTokenCacheCredential   = false,
                ExcludeVisualStudioCredential       = true,
                ExcludeVisualStudioCodeCredential   = true,
                ExcludeAzureCliCredential           = false,
                ExcludeInteractiveBrowserCredential = false
            };
            var credential = new DefaultAzureCredential(options);
            //var credential = new ChainedTokenCredential(new AzureCliCredential(), new ManagedIdentityCredential());
            var token = credential.GetToken(
                new Azure.Core.TokenRequestContext(
                    new[] { "https://graph.microsoft.com/.default" }));

            var accessToken = token.Token;

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

            //        return Task.CompletedTask;
            //    }));

            return(accessToken);
        }
Esempio n. 5
0
        public static void Run([TimerTrigger("%CLEANUP_SCHEDULE%")] TimerInfo myTimer, ILogger log)
        {
            DefaultCredential       = new DefaultAzureCredential();
            DefaultToken            = DefaultCredential.GetToken(new TokenRequestContext(new[] { "https://management.azure.com/.default" })).Token;
            DefaultTokenCredentials = new TokenCredentials(DefaultToken);
            DefaultAzureCredentials = new AzureCredentials(DefaultTokenCredentials, DefaultTokenCredentials, null, AzureEnvironment.AzureGlobalCloud);
            var azure         = Microsoft.Azure.Management.Fluent.Azure.Configure().Authenticate(DefaultAzureCredentials).WithDefaultSubscription();
            var subscriptions = azure.Subscriptions.List();
            var tasks         = new List <Task>();

            foreach (var subscription in subscriptions)
            {
                tasks.Add(Task.Run(() => ProcessSubscription(subscription, log)));
            }
            try
            {
                Task.WaitAll(tasks.ToArray());
            }
            catch (AggregateException ae)
            {
                foreach (var e in ae.InnerExceptions)
                {
                    log.LogError(e.Message);
                }
            }
        }
Esempio n. 6
0
        public IEnumerable <string> Get()
        {
            using (SqlConnection connection = new SqlConnection(Configuration.GetConnectionString("SqlConnectionString")))
            {
                var credential = new DefaultAzureCredential();
                var token      = credential
                                 .GetToken(new Azure.Core.TokenRequestContext(
                                               new[] { "https://database.windows.net/.default" }));
                connection.AccessToken = token.Token;
                connection.Open();

                SqlCommand createCommand = new SqlCommand("" +
                                                          "IF NOT EXISTS(SELECT [name] FROM sys.tables WHERE [name] = 'TestTable') " +
                                                          "BEGIN " +
                                                          "CREATE TABLE [dbo].[TestTable]([Id][int] IDENTITY(1, 1) NOT NULL,[Message][nvarchar](250) NOT NULL) ON[PRIMARY] " +
                                                          "INSERT INTO [dbo].[TestTable]([Message])VALUES('This is a test') " +
                                                          "INSERT INTO [dbo].[TestTable]([Message])VALUES('This is the second test') " +
                                                          "END", connection);
                createCommand.ExecuteNonQuery();

                List <string> messages = new List <string>();
                SqlCommand    command  = new SqlCommand("SELECT * FROM [dbo].[TestTable]", connection);
                using (SqlDataReader reader = command.ExecuteReader())
                    while (reader.Read())
                    {
                        messages.Add(reader["Message"].ToString());
                    }
                return(messages);
            }
        }
        public DbConnection GetConnection()
        {
            var sqlConnection = new SqlConnection(_connectionString);
            var credential    = new DefaultAzureCredential();
            var accessToken   = credential.GetToken(new TokenRequestContext(_authenticationTokenScopes)).Token;

            sqlConnection.AccessToken = accessToken;

            return(sqlConnection);
        }
Esempio n. 8
0
        public QuoteContext(DbContextOptions options) : base(options)
        {
            var conn = (Microsoft.Data.SqlClient.SqlConnection)Database.GetDbConnection();
            var opt  = new DefaultAzureCredentialOptions()
            {
                ExcludeSharedTokenCacheCredential = true
            };
            var credential = new DefaultAzureCredential(opt);
            var token      = credential
                             .GetToken(new Azure.Core.TokenRequestContext(
                                           new[] { "https://database.windows.net/.default" }));

            conn.AccessToken = token.Token;
        }
Esempio n. 9
0
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            if (configuration != null)
            {
                var connection          = new SqlConnection(configuration.GetConnectionString("DefaultConnection"));
                var tokenRequestContext = new TokenRequestContext(new[] { "https://database.windows.net//.default" });

                if (azureSqlAuthTokenService != null && configuration.GetValue <bool>("UseMSI"))
                {
                    connection.AccessToken = azureSqlAuthTokenService.GetToken(tokenRequestContext, default).Token;
                }

                optionsBuilder.UseSqlServer(connection);
            }
        }
Esempio n. 10
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllersWithViews();
            //services.AddDbContext<MyDatabaseContext>(options =>
            //        options.UseSqlite("Data Source=localdatabase.db"));
            var connString = Configuration.GetConnectionString("MyDbConnection");
            var sqlConn    = new System.Data.SqlClient.SqlConnection(connString);
            var credential = new DefaultAzureCredential();
            var token      = credential.GetToken(new Azure.Core.TokenRequestContext(new[] { "https://database.windows.net/.default" }));

            sqlConn.AccessToken = token.Token;

            services.AddDbContext <MyDatabaseContext>(options =>
                                                      options.UseSqlServer(sqlConn));
        }
        protected override async Task <string> GenerateSecret(ISecret secret, ILogger log)
        {
            log.LogInformation($"Resource Name: {secret.ResourceName}");
            log.LogInformation($"Expires In (days): {secret.ExpiresInDays}");

            // Create the Microsoft Graph service client with a DefaultAzureCredential class, which gets an access token by using the available Managed Identity.
            var credential = new DefaultAzureCredential(includeInteractiveCredentials: true);
            var token      = credential.GetToken(
                new TokenRequestContext(
                    new[] { "https://graph.microsoft.com/.default" }));

            var accessToken = token.Token;

            var graphServiceClient = new GraphServiceClient(
                new DelegateAuthenticationProvider((requestMessage) =>
            {
                requestMessage
                .Headers
                .Authorization = new AuthenticationHeaderValue("bearer", accessToken);
                return(Task.CompletedTask);
            }));

            var passwordCredential = new PasswordCredential
            {
                DisplayName = SecretDisplayName,
                EndDateTime = DateTimeOffset.UtcNow.AddDays(int.Parse(secret.ExpiresInDays)),
            };
            Application application = await graphServiceClient.Applications[secret.ResourceName].Request().GetAsync();

            try
            {
                foreach (PasswordCredential password in application.PasswordCredentials.Where(t => t.EndDateTime < DateTimeOffset.UtcNow && t.DisplayName == SecretDisplayName).ToList())
                {
                    log.LogInformation($"Deleting Expired Key Secret on {secret.ResourceName}: {password.KeyId}");
                    await graphServiceClient.Applications[secret.ResourceName].RemovePassword(password.KeyId ?? Guid.Empty).Request().PostAsync();
                }
            }
            catch
            {
                log.LogWarning("Error deleting expired Key Secrets");
            }

            var servicePrincipalKey = await graphServiceClient.Applications[secret.ResourceName].AddPassword(passwordCredential).Request().PostAsync();

            return(servicePrincipalKey.SecretText);
        }
        public async Task OnGetAsync()
        {
            // Create the Graph service client with a DefaultAzureCredential which gets an access token using the available Managed Identity
            var credential = new DefaultAzureCredential();
            var token      = credential.GetToken(
                new Azure.Core.TokenRequestContext(
                    new[] { "https://graph.microsoft.com/.default" }));

            var accessToken        = token.Token;
            var graphServiceClient = new GraphServiceClient(
                new DelegateAuthenticationProvider((requestMessage) =>
            {
                requestMessage
                .Headers
                .Authorization = new AuthenticationHeaderValue("bearer", accessToken);

                return(Task.CompletedTask);
            }));

            List <MSGraphUser> msGraphUsers = new List <MSGraphUser>();

            try
            {
                var users = await graphServiceClient.Users.Request().GetAsync();

                foreach (var u in users)
                {
                    MSGraphUser user = new MSGraphUser();
                    user.userPrincipalName = u.UserPrincipalName;
                    user.displayName       = u.DisplayName;
                    user.mail     = u.Mail;
                    user.jobTitle = u.JobTitle;

                    msGraphUsers.Add(user);
                }
            }
            catch (Exception ex)
            {
                string msg = ex.Message;
            }

            Users = msGraphUsers;
        }
Esempio n. 13
0
        public async Task OnGet()
        {
            var credential = new DefaultAzureCredential();
            var token      = credential.GetToken(
                new Azure.Core.TokenRequestContext(
                    new[] { "https://graph.microsoft.com/.default" }));

            var accessToken        = token.Token;
            var graphServiceClient = new GraphServiceClient(
                new DelegateAuthenticationProvider((requestMessage) =>
            {
                requestMessage.Headers
                .Authorization = new AuthenticationHeaderValue("bearer", accessToken);

                return(Task.CompletedTask);
            }));

            try
            {
                var users = await graphServiceClient.Users.Request().GetAsync();
            }
        }
Esempio n. 14
0
        // The current example is set up to utilize a system assigned managed identity.
        // If you would like to use a user assigned managed identity, then go ahead and
        // uncomment this line, and initialize DefaultAzureCredential utilizing
        // this value which is the Id of the user assigned managed identity
        //const string UserAssignedManagedIdentityId = "USER-ASSIGNED-MANAGED-IDENTITY-ID";

        static async Task Main(string[] args)
        {
            // Initialize a DefaultAzureCredential which is a part of the
            // Azure.Identity package which provides an authentication flow
            // for more information: https://docs.microsoft.com/en-us/dotnet/api/azure.identity.defaultazurecredential?view=azure-dotnet
            DefaultAzureCredential credential = new DefaultAzureCredential();

            // If utilizing a user assigned managed identity, then uncomment the
            // second line and comment out the first line
            //var credential = new DefaultAzureCredential(new DefaultAzureCredentialOptions { ManagedIdentityClientId = UserAssignedManagedIdentityId });


            // Create token request context with scope set to .default
            TokenRequestContext tokenRequestContext = new TokenRequestContext(new[] { "https://graph.microsoft.com/.default" });


            // Get token which will sequentially call the included credentials in the order
            // EnvironmentCredential, ManagedIdentityCredential, SharedTokenCacheCredential,
            // and InteractiveBrowserCredential returning the first successfully obtained AccessToken
            AccessToken token       = credential.GetToken(tokenRequestContext);
            string      accessToken = token.Token;


            // Initialize the auth provider with the access token acquired
            DelegateAuthenticationProvider authProvider = new DelegateAuthenticationProvider((requestMessage) =>
            {
                requestMessage
                .Headers
                .Authorization = new AuthenticationHeaderValue("bearer", accessToken);
                return(Task.CompletedTask);
            });


            // Initialize graph client with the auth provider
            GraphServiceClient graphServiceClient = new GraphServiceClient(authProvider);


            // Get CollectionPage of applications
            var applicationList = new List <Application>();
            IGraphServiceApplicationsCollectionPage applications = await graphServiceClient.Applications.Request().GetAsync();

            applicationList.AddRange(applications.CurrentPage);


            // Cycle through all pages to get all applications
            while (applications.NextPageRequest != null)
            {
                applications = await applications.NextPageRequest.GetAsync();

                applicationList.AddRange(applications.CurrentPage);
            }


            // Print out applications to the console
            // When deployed as a trigger webjob, by default
            // these will be written out to the webjob run log
            foreach (var app in applicationList)
            {
                Console.WriteLine("Application: " + app.DisplayName);
            }
        }