/// <summary>
 /// Acquires an IUserIdentity from Azure Active Directory using the argument authorizationCode.
 /// </summary>
 /// <param name="authorizationCode">An authorization code provided by Azure Active Directory used to retrieve an IUserIdentity</param>
 /// <returns>Returns an IUserIdentity representing a successfully authenticated Azure Active Directory user who has privileges for this configured application</returns>
 public static IUserIdentity GetAuthenticatedUserIDentity(string authorizationCode)
 {
     var authenticationContext = new Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext(string.Format("https://login.windows.net/{0}", AAD.TENANT_ID));
     var clientCredential      = new Microsoft.IdentityModel.Clients.ActiveDirectory.ClientCredential(AAD.CLIENT_ID, AAD.CLIENT_KEY);
     var authenticationResult  = authenticationContext.AcquireTokenByAuthorizationCode(authorizationCode, new Uri(AAD.REPLY_URL), clientCredential);
     return new UserIdentity(authenticationResult.UserInfo);
 }
예제 #2
0
    public static async Task <string> SendGraphGetRequest(AuthenticationResult authResult, string api, string query, string tenant, string adminClientId, string adminClientSecret)
    {
        var authContext = new Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext("https://login.microsoftonline.com/" + tenant);
        var credential  = new Microsoft.IdentityModel.Clients.ActiveDirectory.ClientCredential(adminClientId, adminClientSecret);

        // Here you ask for a token using the web app's clientId as the scope, since the web app and service share the same clientId.
        // AcquireTokenSilentAsync will return a token from the token cache, and throw an exception if it cannot do so.
        //var authContext = new AuthenticationContext(authority, new NaiveSessionCache(userObjectId));

        //// We don't care which policy is used to access the TaskService, so let's use the most recent policy
        //var mostRecentPolicy = authTicket.Identity.FindFirst(AcrClaimType).Value;
        //var result = await authContext.AcquireTokenSilentAsync(new string[] { clientId }, credential, UserIdentifier.AnyUser, mostRecentPolicy);

        //// First, use ADAL to acquire a token using the app's identity (the credential)
        //// The first parameter is the resource we want an access_token for; in this case, the Graph API.
        var result = authContext.AcquireToken("https://graph.windows.net", credential);

        // For B2C user managment, be sure to use the beta Graph API version.
        var http = new HttpClient();
        var url  = "https://graph.windows.net/" + tenant + api + "?" + "api-version=beta";

        if (!string.IsNullOrEmpty(query))
        {
            url += "&" + query;
        }

        //Console.ForegroundColor = ConsoleColor.Cyan;
        //Console.WriteLine("GET " + url);
        //Console.WriteLine("Authorization: Bearer " + result.AccessToken.Substring(0, 80) + "...");
        //Console.WriteLine("");

        // Append the access token for the Graph API to the Authorization header of the request, using the Bearer scheme.
        var request = new HttpRequestMessage(HttpMethod.Get, url);

        //request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", authResult.Token);
        request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);
        var response = await http.SendAsync(request);

        if (!response.IsSuccessStatusCode)
        {
            string error = await response.Content.ReadAsStringAsync();

            object formatted = JsonConvert.DeserializeObject(error);
            throw new WebException("Error Calling the Graph API: \n" + JsonConvert.SerializeObject(formatted, Formatting.Indented));
        }

        //Console.ForegroundColor = ConsoleColor.Green;
        //Console.WriteLine((int)response.StatusCode + ": " + response.ReasonPhrase);
        //Console.WriteLine("");

        return(await response.Content.ReadAsStringAsync());
    }
        private async Task <string> GetAppTokenAsync()
        {
            // *****ADAL code
            Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationResult tokenResult = null;
            string userObjectID = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;

            Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext authContext =
                new Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext(authority, false);
            Microsoft.IdentityModel.Clients.ActiveDirectory.ClientCredential credential =
                new Microsoft.IdentityModel.Clients.ActiveDirectory.ClientCredential(clientId, appKey);
            tokenResult = await authContext.AcquireTokenAsync(resAzureGraphAPI, credential);

            return(tokenResult.AccessToken);
        }
예제 #4
0
        static void InitializeAzureKeyVaultProvider()
        {
            //TODO: Determine the exact name of environment variable created by ARM template. change the following two lines accordingly.
            string clientId = System.Environment.GetEnvironmentVariable("applicationADID");
            //System.Configuration.ConfigurationManager.AppSettings["AuthClientId"];
            string clientSecret = System.Environment.GetEnvironmentVariable("applicationADSecret");

            //System.Configuration.ConfigurationManager.AppSettings["applicationADSecret"];
            //Change the above lines to get the ID and Secret set correctly.

            _clientCredential = new Microsoft.IdentityModel.Clients.ActiveDirectory.ClientCredential(clientId, clientSecret);

            Microsoft.SqlServer.Management.AlwaysEncrypted.AzureKeyVaultProvider.SqlColumnEncryptionAzureKeyVaultProvider azureKeyVaultProvider =
                new Microsoft.SqlServer.Management.AlwaysEncrypted.AzureKeyVaultProvider.SqlColumnEncryptionAzureKeyVaultProvider(GetToken);

            System.Collections.Generic.Dictionary <string, System.Data.SqlClient.SqlColumnEncryptionKeyStoreProvider> providers =
                new System.Collections.Generic.Dictionary <string, System.Data.SqlClient.SqlColumnEncryptionKeyStoreProvider>();

            providers.Add(Microsoft.SqlServer.Management.AlwaysEncrypted.AzureKeyVaultProvider.SqlColumnEncryptionAzureKeyVaultProvider.ProviderName, azureKeyVaultProvider);
            System.Data.SqlClient.SqlConnection.RegisterColumnEncryptionKeyStoreProviders(providers);
        }
예제 #5
0
        /// <summary>
        /// get the bearer token for adding to authorization header
        /// </summary>
        /// <returns></returns>
        private async static Task <string> GetBearerToken()
        {
            try
            {
                string authContextURL        = "https://login.windows.net/" + tenantId;
                var    authenticationContext = new Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext(authContextURL);
                var    cred   = new Microsoft.IdentityModel.Clients.ActiveDirectory.ClientCredential(clientId, clientKey);
                var    result = await authenticationContext.AcquireTokenAsync("https://management.azure.com/", cred);

                if (result == null)
                {
                    throw new InvalidOperationException("Failed to obtain the JWT token");
                }
                string token = result.AccessToken;
                return(token);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
예제 #6
0
        private static async Task OnAuthorizationCodeReceived(AuthorizationCodeReceivedNotification notification)
        {
            // The user's objectId is extracted from the claims provided in the id_token, and used to cache tokens in ADAL
            // The authority is constructed by appending your B2C directory's name to "https://login.microsoftonline.com/"
            // The client credential is where you provide your application secret, and is used to authenticate the application to Azure AD
            var userObjectId = notification.AuthenticationTicket.Identity.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;

            var audience = notification.AuthenticationTicket.Identity.FindFirst("aud").Value;

            if (audience == Auth.Config.ExternalUsersClientId)
            {
                var authority  = string.Format(CultureInfo.InvariantCulture, Auth.Config.AadInstance, Auth.Config.ExternalUsersTenant, string.Empty, string.Empty);
                var credential = new ClientCredential(Auth.Config.ExternalUsersClientId, Auth.Config.ExternalUsersClientSecret);

                // We don't care which policy is used to access the TaskService, so let's use the most recent policy
                var mostRecentPolicy = notification.AuthenticationTicket.Identity.FindFirst(Auth.Config.AcrClaimType).Value;

                // The Authentication Context is ADAL's primary class, which represents your connection to your B2C directory
                // ADAL uses an in-memory token cache by default.  In this case, we've extended the default cache to use a simple per-user session cache
                var authContext = new AuthenticationContext(authority, new NaiveSessionCache(userObjectId));

                // Here you ask for a token using the web app's clientId as the scope, since the web app and service share the same clientId.
                // The token will be stored in the ADAL token cache, for use in our controllers
                await authContext.AcquireTokenByAuthorizationCodeAsync(notification.Code, new Uri(Auth.Config.RedirectUri), credential,
                                                                       new[] { Auth.Config.ExternalUsersClientId }, mostRecentPolicy);
            }
            else
            {
                var authority  = string.Format(CultureInfo.InvariantCulture, Auth.Config.AadInstance, Auth.Config.InternalUsersTenant, string.Empty, string.Empty);
                var credential = new Microsoft.IdentityModel.Clients.ActiveDirectory.ClientCredential(Auth.Config.InternalUsersClientId, Auth.Config.InternalUsersClientSecret);

                // The Authentication Context is ADAL's primary class, which represents your connection to your B2C directory
                // ADAL uses an in-memory token cache by default.  In this case, we've extended the default cache to use a simple per-user session cache
                var authContext = new Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext(authority);

                // Here you ask for a token using the web app's clientId as the scope, since the web app and service share the same clientId.
                // The token will be stored in the ADAL token cache, for use in our controllers
                await authContext.AcquireTokenByAuthorizationCodeAsync(notification.Code, new Uri(Auth.Config.RedirectUri), credential);
            }
        }
예제 #7
0
        public static async Task testAsync()
        {
            Microsoft.IdentityModel.Clients.ActiveDirectory.ClientCredential cred = new Microsoft.IdentityModel.Clients.ActiveDirectory.ClientCredential(PBIConfig.ClientId, PBIConfig.ClientSecret);
            Microsoft.IdentityModel.Clients.ActiveDirectory.UserIdentifier   user = new Microsoft.IdentityModel.Clients.ActiveDirectory.UserIdentifier("43e514c7-cc35-4226-93a3-eb83a2852ad5", Microsoft.IdentityModel.Clients.ActiveDirectory.UserIdentifierType.OptionalDisplayableId);

            var res = await TokenService.AuthContext.AcquireTokenSilentAsync(PBIConfig.ResourceUrl, cred, user);

            string token = "AQABAAAAAACEfexXxjamQb3OeGQ4Gugv71VOKGNVXNJGkcjBwMuqpryMOp69ZfOaiQ4be_oP3tt2JIQ4U0p5lJpCgdbV5V9eeNseQzaQMxqlPogHyD-FJuH2BCfWEOorBav1Z6Zh6qV7vGYxQmte6oNh-lqV8N1H3cFFqVBbYwQsPsA3RevZ3HJ8phgxf_mRBlx6OsWR-8_LeP8QgDcVUXEbdw93ZCA6v5wX0v8J5Z8yp5YIgvdrPA2LQlSfmhM5u5Vedauue-m0YvtxgZpXwAfyX2NHLP3QRP_5_D224Tv_Au7kOETRbMRBKmrCCQzBbjRC-g3FCWuWyAIYbTJFoqmEcndPGiEWAjny6VYD2lsZTRBbSXAeA0Kqa1loQ8A4QnTAECJBMY0IWppVGzDCvgAO_kT_qwYRqP9fR9YVCeTsF9d4rFMq4Nil-8bc7GDfKcJpa0Z52DxYrIsIYiM9WSuX1Xf0vVpgpY7QFn-YDbuLrlf--bp9wJJ_BHmguHhzWxw6b5rYyqL0IaVlk-1SrmvPy4IoUgslyrF6azQaKLb4EIvkimXC_kmiRVOcFii7wyefO0pikNq3JllpmDQ-FvoqTehNZVvlF4d3dYmISYhzS1xk8ghklb3Br0RrhLj88Yyf47SNFli3YD79nFIxs8v3fybdyxqhp54gCqJN0kf2jkmitX8gR1KH5nwG1pdFDRt9Z3nidIYgAA";
            string url   = "https://api.powerbi.com/v1.0/myorg/admin/groups";

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

            request.ContentType = "application/json";
            request.MediaType   = "application/json";
            request.Accept      = "application/json";

            request.ContentLength = 0;
            request.Method        = "GET";
            request.Headers.Add("Authorization", String.Format("Bearer {0}", token));

            HttpWebResponse response        = (HttpWebResponse)request.GetResponse();
            string          responseContent = (new StreamReader(response.GetResponseStream())).ReadToEnd();
        }
예제 #8
0
	public static async Task<string> SendGraphGetRequest(AuthenticationResult authResult, string api, string query, string tenant, string adminClientId, string adminClientSecret)
	{
		var authContext = new Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext("https://login.microsoftonline.com/" + tenant);
		var credential = new Microsoft.IdentityModel.Clients.ActiveDirectory.ClientCredential(adminClientId, adminClientSecret);

		// Here you ask for a token using the web app's clientId as the scope, since the web app and service share the same clientId.
		// AcquireTokenSilentAsync will return a token from the token cache, and throw an exception if it cannot do so.
		//var authContext = new AuthenticationContext(authority, new NaiveSessionCache(userObjectId));

		//// We don't care which policy is used to access the TaskService, so let's use the most recent policy
		//var mostRecentPolicy = authTicket.Identity.FindFirst(AcrClaimType).Value;
		//var result = await authContext.AcquireTokenSilentAsync(new string[] { clientId }, credential, UserIdentifier.AnyUser, mostRecentPolicy);

		//// First, use ADAL to acquire a token using the app's identity (the credential)
		//// The first parameter is the resource we want an access_token for; in this case, the Graph API.
		var result = authContext.AcquireToken("https://graph.windows.net", credential);

		// For B2C user managment, be sure to use the beta Graph API version.
		var http = new HttpClient();
		var url = "https://graph.windows.net/" + tenant + api + "?" + "api-version=beta";
		if (!string.IsNullOrEmpty(query))
		{
			url += "&" + query;
		}

		//Console.ForegroundColor = ConsoleColor.Cyan;
		//Console.WriteLine("GET " + url);
		//Console.WriteLine("Authorization: Bearer " + result.AccessToken.Substring(0, 80) + "...");
		//Console.WriteLine("");

		// Append the access token for the Graph API to the Authorization header of the request, using the Bearer scheme.
		var request = new HttpRequestMessage(HttpMethod.Get, url);
		//request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", authResult.Token);
		request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);
		var response = await http.SendAsync(request);

		if (!response.IsSuccessStatusCode)
		{
			string error = await response.Content.ReadAsStringAsync();
			object formatted = JsonConvert.DeserializeObject(error);
			throw new WebException("Error Calling the Graph API: \n" + JsonConvert.SerializeObject(formatted, Formatting.Indented));
		}

		//Console.ForegroundColor = ConsoleColor.Green;
		//Console.WriteLine((int)response.StatusCode + ": " + response.ReasonPhrase);
		//Console.WriteLine("");

		return await response.Content.ReadAsStringAsync();
	}