コード例 #1
0
        internal static JwtSecurityToken GetCachedIdToken(string userName)
        {
            AuthenticationContext authContext = new AuthenticationContext(ConfigurationManager.AppSettings["AuthorityURI"], new ADALTokenCache());
            UserIdentifier        userId      = new UserIdentifier(userName, UserIdentifierType.RequiredDisplayableId);
            AuthenticationResult  authResult;
            string           resource;
            JwtSecurityToken jwtToken;

            if (IsInteractiveAuth())
            {
                ClientCredential clientCredential = new ClientCredential(
                    ConfigurationManager.AppSettings["ClientID"],
                    ConfigurationManager.AppSettings["ClientSecret"]);

                resource   = TokenUtilities.GraphResourceId;
                authResult = authContext.AcquireTokenSilent(resource, clientCredential, userId);
            }
            else
            {
                string clientId = ConfigurationManager.AppSettings["APIClientId"];
                resource = ConfigurationManager.AppSettings["ClientId"];

                authResult = authContext.AcquireTokenSilent(resource, clientId, userId);
            }

            jwtToken = new JwtSecurityToken(authResult.IdToken);
            return(jwtToken);
        }
コード例 #2
0
        public static AuthenticationResult GetToken(string serviceName)
        {
            var ctx = new AuthenticationContext(IdentitySettings.IssuerAddress, new NativeTokenCache());

            var resource        = Resource(serviceName);
            var appClientId     = RuntimeFactory.Current.Context.GetServiceConfiguration().GetConfigParameter("OauthClientId");
            var appClientSecret = RuntimeFactory.Current.Context.GetServiceConfiguration().GetSecureConfigParameter("OauthClientSecret");

            try
            {
                AuthenticationResult token;
                var userToken        = GetUserToken();
                var userId           = GetUserObjectId();
                var clientCredential = new ClientCredential(appClientId, appClientSecret);
                if (userToken.ContainsCharacters())
                {
                    try
                    {
                        token = ctx.AcquireToken(resource, clientCredential, new UserAssertion(userToken, "urn:ietf:params:oauth:grant-type:jwt-bearer", RuntimeFactory.Current.GetCurrentClaimsIdentity().Name));
                    }
                    catch (Exception)
                    {
                        token = ctx.AcquireTokenSilent(resource, clientCredential, GetUserAssertion());
                    }
                }
                else if (userId.ContainsCharacters())
                {
                    token = ctx.AcquireTokenSilent(resource, clientCredential, GetUserAssertion());
                }
                else
                {
                    if (ConfigurationManagerHelper.GetValueOnKey("stardust.promptUserFOrCredentials", false))
                    {
                        token = ctx.AcquireToken(resource, appClientId, new Uri("http://" + Utilities.GetEnvironment() + "ters.dnvgl.com"), PromptBehavior.Auto);
                    }
                    else
                    {
                        token = ctx.AcquireToken(resource, clientCredential);
                    }
                }
                return(token);
            }
            catch (AdalSilentTokenAcquisitionException adalex)
            {
                if (adalex.ErrorCode == AdalError.FailedToAcquireTokenSilently)
                {
                    HttpContext.Current.GetOwinContext().Authentication.SignOut();
                    HttpContext.Current.GetOwinContext().Authentication.Challenge();
                    throw;
                }
                throw;
            }
            catch (System.Exception ex)
            {
                ex.Log();
                throw;
            }
        }
コード例 #3
0
        /// <summary>
        /// Get the token for authenticating requests to Azure Resource Manager in customer tenant.
        /// </summary>
        /// <param name="appId">appid that is registered for this application in Azure Active Directory (AAD)</param>
        /// <param name="key">This is the key for this application in Azure Active Directory</param>
        /// <param name="customerTenantId">cid of the customer</param>
        /// <returns>Azure Auth Token in the context of the customer tenant.</returns>
        private static AuthenticationResult GetAzureAuthTokenForCustomerTenant(string appId, string credentialName, string customerTenantId)
        {
            AuthenticationResult authResult = null;
            string resource = "https://management.core.windows.net/";

            var authenticationContext = new AuthenticationContext("https://login.windows.net/" + customerTenantId);

            try
            {
                authResult = authenticationContext.AcquireTokenSilent(resource: resource, clientId: appId);
            }
            catch (AdalException aex)
            {
                if (aex.ErrorCode == "failed_to_acquire_token_silently")
                {
                    UserCredential uc = CredentialManager.GetCredential(credentialName);
                    authResult = authenticationContext.AcquireToken(resource: resource, clientId: appId, userCredential: uc);
                }
            }
            catch (Exception ex)
            {
                throw;
            }

            return(authResult);
        }
コード例 #4
0
ファイル: HomeController.cs プロジェクト: bryan1201/GitRespo
        /// <summary>
        /// Use AuthenticationContext to get an access token
        /// </summary>
        /// <returns></returns>
        private string AccessToken()
        {
            if (token == String.Empty)
            {
                //string userName = "******";
                //string password = "******";
                string userName = ConfigurationManager.AppSettings["PowerBIUsername"];
                string password = ConfigurationManager.AppSettings["PowerBIPassword"];

                // Create an instance of TokenCache to cache the access token
                TokenCache TC = new TokenCache();

                // Create an instance of AuthenticationContext to acquire an Azure access token
                authContext = new AuthenticationContext(authority, TC);

                // Call AcquireToken to get an Azure token from Azure Active Directory token issuance endpoint
                // token = authContext.AcquireToken(resourceUri, clientID, new Uri(redirectUri), PromptBehavior.RefreshSession).AccessToken;
                token = authContext.AcquireToken(resourceUri, clientID, new UserCredential(userName, password)).AccessToken;
            }
            else
            {
                // Get the token in the cache
                token = authContext.AcquireTokenSilent(resourceUri, clientID).AccessToken;
            }

            return(token);
        }
コード例 #5
0
        // GET: Contacts
        public async Task <ActionResult> Index()
        {
            List <MyContact> myContacts = new List <MyContact>();

            var signInUserId = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;
            var userObjectId = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
            var tenantId     = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;

            AuthenticationContext authContext = new AuthenticationContext(string.Format("{0}/{1}", SettingsHelper.AuthorizationUri, tenantId), new ADALTokenCache(signInUserId));

            try
            {
                DiscoveryClient discClient = new DiscoveryClient(SettingsHelper.DiscoveryServiceEndpointUri,
                                                                 () =>
                {
                    var authResult = authContext.AcquireTokenSilent(SettingsHelper.DiscoveryServiceResourceId, new ClientCredential(SettingsHelper.ClientId, SettingsHelper.AppKey), new UserIdentifier(userObjectId, UserIdentifierType.UniqueId));

                    return(authResult.AccessToken);
                });

                var dcr = await discClient.DiscoverCapabilityAsync("Contacts");

                ViewBag.ResourceId = dcr.ServiceResourceId;

                OutlookServicesClient exClient = new OutlookServicesClient(dcr.ServiceEndpointUri,
                                                                           async() =>
                {
                    var authResult = await authContext.AcquireTokenSilentAsync(dcr.ServiceResourceId, new ClientCredential(SettingsHelper.ClientId, SettingsHelper.AppKey), new UserIdentifier(userObjectId, UserIdentifierType.UniqueId));

                    return(authResult.AccessToken);
                });

                var contactsResult = await exClient.Me.Contacts.ExecuteAsync();

                do
                {
                    var contacts = contactsResult.CurrentPage;
                    foreach (var contact in contacts)
                    {
                        myContacts.Add(new MyContact {
                            Name = contact.DisplayName
                        });
                    }

                    contactsResult = await contactsResult.GetNextPageAsync();
                } while (contactsResult != null);
            }
            catch (AdalException exception)
            {
                //handle token acquisition failure
                if (exception.ErrorCode == AdalError.FailedToAcquireTokenSilently)
                {
                    authContext.TokenCache.Clear();

                    ViewBag.ErrorMessage = "AuthorizationRequired";
                }
            }

            return(View(myContacts));
        }
コード例 #6
0
        public static string GetUsage(string subscriptionId, string organizationId)
        {
            string signedInUserUniqueName = ClaimsPrincipal.Current.FindFirst(ClaimTypes.Name).Value.Split('#')[ClaimsPrincipal.Current.FindFirst(ClaimTypes.Name).Value.Split('#').Length - 1];
            string UsageResponse          = "";

            try
            {
                // Aquire Access Token to call Azure Resource Manager
                ClientCredential credential = new ClientCredential(ConfigurationManager.AppSettings["ida:ClientID"],
                                                                   ConfigurationManager.AppSettings["ida:Password"]);
                // initialize AuthenticationContext with the token cache of the currently signed in user, as kept in the app's EF DB
                AuthenticationContext authContext = new AuthenticationContext(
                    string.Format(ConfigurationManager.AppSettings["ida:Authority"], organizationId), new ADALTokenCache(signedInUserUniqueName));
                AuthenticationResult result = authContext.AcquireTokenSilent(ConfigurationManager.AppSettings["ida:AzureResourceManagerIdentifier"], credential,
                                                                             new UserIdentifier(signedInUserUniqueName, UserIdentifierType.RequiredDisplayableId));
                //Making a call to the Azure Usage API for a set time frame with the input AzureSubID
                string requesturl = String.Format("https://management.azure.com/subscriptions/{0}/providers/Microsoft.Commerce/UsageAggregates?api-version=2015-06-01-preview&reportedstartTime=2015-05-15+00%3a00%3a00Z&reportedEndTime=2015-05-16+00%3a00%3a00Z", subscriptionId);

                //Crafting the HTTP call
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requesturl);
                request.Headers.Add(HttpRequestHeader.Authorization, "Bearer " + result.AccessToken);
                request.ContentType = "application/json";
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Console.WriteLine(response.StatusDescription);
                Stream receiveStream = response.GetResponseStream();

                // Pipes the stream to a higher level stream reader with the required encoding format.
                StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8);
                UsageResponse = readStream.ReadToEnd();
            }
            catch { }

            return(UsageResponse);
        }
        public static void GrantRoleToServicePrincipalOnSubscription(string objectId, string subscriptionId, string organizationId)
        {
            string signedInUserUniqueName = ClaimsPrincipal.Current.FindFirst(ClaimTypes.Name).Value.Split('#')[ClaimsPrincipal.Current.FindFirst(ClaimTypes.Name).Value.Split('#').Length - 1];

            try
            {
                // Aquire Access Token to call Azure Resource Manager
                ClientCredential credential = new ClientCredential(ConfigurationManager.AppSettings["ida:ClientID"],
                                                                   ConfigurationManager.AppSettings["ida:Password"]);
                // initialize AuthenticationContext with the token cache of the currently signed in user, as kept in the app's EF DB
                AuthenticationContext authContext = new AuthenticationContext(
                    string.Format(ConfigurationManager.AppSettings["ida:Authority"], organizationId), new ADALTokenCache(signedInUserUniqueName));
                AuthenticationResult result = authContext.AcquireTokenSilent(ConfigurationManager.AppSettings["ida:AzureResourceManagerIdentifier"], credential,
                                                                             new UserIdentifier(signedInUserUniqueName, UserIdentifierType.RequiredDisplayableId));


                // Create role assignment for application on the subscription
                string roleAssignmentId = Guid.NewGuid().ToString();
                string roleDefinitionId = GetRoleId(ConfigurationManager.AppSettings["ida:RequiredARMRoleOnSubscription"], subscriptionId, organizationId);

                string requestUrl = string.Format("{0}/subscriptions/{1}/providers/microsoft.authorization/roleassignments/{2}?api-version={3}",
                                                  ConfigurationManager.AppSettings["ida:AzureResourceManagerUrl"], subscriptionId, roleAssignmentId,
                                                  ConfigurationManager.AppSettings["ida:ARMAuthorizationRoleAssignmentsAPIVersion"]);

                HttpClient         client  = new HttpClient();
                HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Put, requestUrl);
                request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);
                StringContent content = new StringContent("{\"properties\": {\"roleDefinitionId\":\"" + roleDefinitionId + "\",\"principalId\":\"" + objectId + "\"}}");
                content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                request.Content             = content;
                HttpResponseMessage response = client.SendAsync(request).Result;
            }
            catch { }
        }
コード例 #8
0
        private static HttpClient GetAuthenticatedHttpClient(AuthType authType)
        {
            var authoritySegment   = ClaimsPrincipal.Current.TenantId();
            var resourceIdentifier = Config.AzureResourceManagerIdentifier;

            string           signedInUserUniqueName = ClaimsPrincipal.Current.FindFirst(ClaimTypes.Name).Value.Split('#').Last();
            ClientCredential credential             = new ClientCredential(Config.ClientId, Config.Password);

            AuthenticationContext authContext = new AuthenticationContext(
                string.Format(Config.Authority, authoritySegment), new AdalTokenCache(signedInUserUniqueName));

            AuthenticationResult result = (authType == AuthType.App ?
                                           authContext.AcquireToken(resourceIdentifier, credential) :
                                           authContext.AcquireTokenSilent(resourceIdentifier, credential,
                                                                          new UserIdentifier(signedInUserUniqueName, UserIdentifierType.RequiredDisplayableId)));

            HttpClient httpClient = new HttpClient();

            httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);
            httpClient.DefaultRequestHeaders.Add(HttpRequestHeader.Accept.ToString(), "application/json");
            httpClient.DefaultRequestHeaders.Add(HttpRequestHeader.ContentType.ToString(), "application/json");
            httpClient.DefaultRequestHeaders.Add(Utils.MSClientRequestHeader, Config.AscAppId);

            return(httpClient);
        }
コード例 #9
0
        /// <summary>
        /// Authenticate.
        /// </summary>
        void Authenticate()
        {
                        #if !PCL
            if (RootConfiguration == null)
            {
                RootConfiguration = (PowerBIConfiguration)ConfigurationManager.GetSection(typeof(PowerBIConfiguration).Name);
            }
                        #endif

            if (AuthenticationContext == null)
            {
                var tokenCache = new TokenCache();
                AuthenticationContext = new AuthenticationContext(Configuration.Authority, tokenCache);
            }

            //For PCL we need to use the ADAL 3.O alpha. Because this version isn't a release we use compilation
            //condition to not use it in the classic version (PCL version of the PowerBI.Api.Client is also a Pre-Release)
            //We use synchronous call (We be change in the next version of the library)
                        #if !PCL
            var authResult = string.IsNullOrEmpty(AccessToken)
                                ? AuthenticationContext.AcquireToken(Configuration.Resource, Configuration.Client, new UserCredential(Configuration.User, Configuration.Password))
                                : AuthenticationContext.AcquireTokenSilent(Configuration.Resource, Configuration.Client);

            AccessToken = authResult.AccessToken;
                        #else
            var task = string.IsNullOrEmpty(AccessToken)
                                ? AuthenticationContext.AcquireTokenAsync(Configuration.Resource, Configuration.Client, new UserCredential(Configuration.User, Configuration.Password))
                                : AuthenticationContext.AcquireTokenSilentAsync(Configuration.Resource, Configuration.Client);
            Task.WaitAll(task);
            AccessToken = task.Result.AccessToken;
                        #endif
        }
コード例 #10
0
        // GET: UserProfile
        public ActionResult Index()
        {
            string clientId        = ConfigurationManager.AppSettings["ida:ClientID"];
            string appKey          = ConfigurationManager.AppSettings["ida:Password"];
            string graphResourceID = "https://graph.windows.net";
            string signedInUserID  = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;
            string tenantID        = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;
            string userObjectID    = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;

            try
            {
                // get a token for the Graph without triggering any user interaction (from the cache, via multi-resource refresh token, etc)
                ClientCredential clientcred = new ClientCredential(clientId, appKey);
                // initialize AuthenticationContext with the token cache of the currently signed in user, as kept in the app's EF DB
                AuthenticationContext authContext = new AuthenticationContext(string.Format("https://login.windows.net/{0}", tenantID), new EFADALTokenCache(signedInUserID));
                AuthenticationResult  result      = authContext.AcquireTokenSilent(graphResourceID, clientcred, new UserIdentifier(userObjectID, UserIdentifierType.UniqueId));

                // use the token for querying the graph
                GraphSettings graphSettings = new GraphSettings();
                graphSettings.ApiVersion      = "2013-11-08";
                graphSettings.GraphDomainName = "graph.windows.net";
                Guid            ClientRequestId = Guid.NewGuid();
                GraphConnection graphConnection = new GraphConnection(result.AccessToken, ClientRequestId, graphSettings);
                User            user            = graphConnection.Get <User>(userObjectID);

                return(View(user));
            }
            // if the above failed, the user needs to explicitly re-authenticate for the app to obtain the required token
            catch (Exception ee)
            {
                ViewBag.ErrorMessage = "AuthorizationRequired";
                return(View());
            }
        }
コード例 #11
0
        string GetAccessToken()
        {
            string clientId       = ConfigurationManager.AppSettings["ida:ClientID"];
            string appKey         = ConfigurationManager.AppSettings["ida:Password"];
            string signedInUserID = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;
            string userObjectID   = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;

            try
            {
                // get a token for the Graph without triggering any user interaction (from the cache, via multi-resource refresh token, etc)
                ClientCredential clientcred = new ClientCredential(clientId, appKey);
                // initialize AuthenticationContext with the token cache of the currently signed in user, as kept in the app's EF DB
                AuthenticationContext authContext = new AuthenticationContext(string.Format("https://login.windows.net/{0}",
                                                                                            TenantId), new EFADALTokenCache(signedInUserID));
                AuthenticationResult result = authContext.AcquireTokenSilent("https://management.core.windows.net/",
                                                                             clientcred, new UserIdentifier(userObjectID, UserIdentifierType.UniqueId));

                return(result.AccessToken);
            }
            // if the above failed, the user needs to explicitly re-authenticate for the app to obtain the required token
            catch (Exception ee)
            {
                return(null);
            }
        }
コード例 #12
0
        private string AccessToken()
        {
            bool fireAgain = false;

            try
            {
                if (token == String.Empty)
                {
                    // Create an instance of TokenCache to cache the access token
                    TokenCache TC = new TokenCache();
                    // Create an instance of AuthenticationContext to acquire an Azure access token
                    authContext = new AuthenticationContext(this.OAuth2AuthorityUri, TC);
                    // Call AcquireToken to get an Azure token from Azure Active Directory token issuance endpoint
                    //token = authContext.AcquireToken(resourceUri, clientID, new Uri(redirectUri)).AccessToken.ToString();

                    UserCredential user = new UserCredential(this.UserName, this.Password);
                    token = authContext.AcquireToken(this.ResourceUri, this.ClientID, user).AccessToken.ToString();
                    ComponentMetaData.FireInformation(0, ComponentMetaData.Name, "Toked Acquired", "", 0, ref fireAgain);
                }
                else
                {
                    // Get the token in the cache
                    token = authContext.AcquireTokenSilent(this.ResourceUri, this.ClientID).AccessToken;
                    ComponentMetaData.FireInformation(0, ComponentMetaData.Name, "Refresh Token Acquired", "", 0, ref fireAgain);
                }

                return(token);
            }
            catch (Exception e)
            {
                ComponentMetaData.FireInformation(0, ComponentMetaData.Name, "Token Error:" + e.Message, "", 0, ref fireAgain);
                return("");
            }
        }
コード例 #13
0
        private static string serviceBaseAddress = "https://localhost:44300/"; // base url of the web api

        // GET: Location
        public async Task <ActionResult> Index()
        {
            AuthenticationResult result       = null;
            string userObjectID               = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
            AuthenticationContext authContext = new AuthenticationContext(authority, new WebSessionCache(userObjectID));
            ClientCredential      credential  = new ClientCredential(clientId, appKey);

            result = authContext.AcquireTokenSilent(serviceResourceID, credential, new UserIdentifier(userObjectID, UserIdentifierType.UniqueId));

            HttpClient         client  = new HttpClient();
            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, serviceBaseAddress + "api/location?cityName=dc");

            request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);
            HttpResponseMessage response = await client.SendAsync(request);

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

                ViewBag.Results = r;
                return(View("Index"));
            }
            else
            {
                string r = await response.Content.ReadAsStringAsync();

                if (response.StatusCode == System.Net.HttpStatusCode.Unauthorized)
                {
                    authContext.TokenCache.Clear();
                }
                ViewBag.ErrorMessage = "AuthorizationRequired";
                return(View("Index"));
            }
        }
コード例 #14
0
        public static string AcquireToken(string userObjectId)
        {
            ClientCredential      cred        = new ClientCredential(ConfigHelper.ClientId, ConfigHelper.AppKey);
            AuthenticationContext authContext = new AuthenticationContext(ConfigHelper.Authority, new TokenDbCache(userObjectId));
            AuthenticationResult  result      = authContext.AcquireTokenSilent(ConfigHelper.GraphResourceId, cred, new UserIdentifier(userObjectId, UserIdentifierType.UniqueId));

            return(result.AccessToken);
        }
コード例 #15
0
ファイル: GraphUtil.cs プロジェクト: SpikesBE/OfficeDevPnP
        /// <summary>
        /// During access management, the user searches for users and groups in the directory and grants them access.
        /// If the given search string matches exactly one user or group in the directory, this method returns its objectId.
        /// </summary>
        /// <param name="searchString">The search string entered by the user to lookup a user or group in the directory.</param>
        /// <returns>The objectID of the matching user or group.</returns>
        public static string LookupObjectIdOfAADUserOrGroup(string searchString, ClaimsIdentity Identity)
        {
            string userOrGroupObjectId = null;
            string tenantId            = Identity.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;
            string signedInUserID      = Identity.FindFirst(System.IdentityModel.Claims.ClaimTypes.NameIdentifier).Value;
            string userObjectID        = Identity.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;

            ClientCredential      credential  = new ClientCredential(SettingsHelper.ClientId, SettingsHelper.ClientSecret);
            AuthenticationContext authContext = new AuthenticationContext(SettingsHelper.AzureADAuthority, new EfAdalTokenCache(signedInUserID));
            AuthenticationResult  result      = authContext.AcquireTokenSilent(
                SettingsHelper.AzureAdGraphResourceId, credential, new UserIdentifier(userObjectID, UserIdentifierType.UniqueId));

            HttpClient client = new HttpClient();

            string userQueryUrl = string.Format("{0}/{1}/users?api-version={2}&$filter=startswith(displayName,'{3}') or startswith(userPrincipalName,'{3}')",
                                                SettingsHelper.AzureAdGraphResourceId, tenantId,
                                                SettingsHelper.GraphAPIVersion, searchString);

            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, userQueryUrl);

            request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);
            HttpResponseMessage response = client.SendAsync(request).Result;

            if (response.IsSuccessStatusCode)
            {
                var    responseContent = response.Content;
                string responseString  = responseContent.ReadAsStringAsync().Result;
                var    users           = (System.Web.Helpers.Json.Decode(responseString)).value;
                if (users.Length == 1)
                {
                    userOrGroupObjectId = users[0].objectId;
                }
            }

            if (userOrGroupObjectId == null)
            {
                string groupQueryUrl = string.Format("{0}/{1}/groups?api-version={2}&$filter=startswith(displayName,'{3}')",
                                                     SettingsHelper.AzureAdGraphResourceId, tenantId,
                                                     SettingsHelper.GraphAPIVersion, searchString);

                request = new HttpRequestMessage(HttpMethod.Get, groupQueryUrl);
                request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);
                response = client.SendAsync(request).Result;

                if (response.IsSuccessStatusCode)
                {
                    var    responseContent = response.Content;
                    string responseString  = responseContent.ReadAsStringAsync().Result;
                    var    groups          = (System.Web.Helpers.Json.Decode(responseString)).value;
                    if (groups.Length == 1)
                    {
                        userOrGroupObjectId = groups[0].objectId;
                    }
                }
            }

            return(userOrGroupObjectId);
        }
コード例 #16
0
        public static void RevokeRoleFromServicePrincipalOnSubscription(string objectId, string subscriptionId, string organizationId)
        {
            string signedInUserUniqueName = ClaimsPrincipal.Current.FindFirst(ClaimTypes.Name).Value.Split('#')[ClaimsPrincipal.Current.FindFirst(ClaimTypes.Name).Value.Split('#').Length - 1];

            try
            {
                // Aquire Access Token to call Azure Resource Manager
                ClientCredential credential = new ClientCredential(
                    ConfigurationManager.AppSettings["ida:ClientID"],
                    ConfigurationManager.AppSettings["ida:Password"]);

                // initialize AuthenticationContext with the token cache of the currently signed in user, as kept in the app's EF DB
                AuthenticationContext authContext = new AuthenticationContext(
                    string.Format(ConfigurationManager.AppSettings["ida:Authority"], organizationId),
                    new ADALTokenCache(signedInUserUniqueName));

                AuthenticationResult result = authContext.AcquireTokenSilent(
                    ConfigurationManager.AppSettings["ida:AzureResourceManagerIdentifier"],
                    credential,
                    new UserIdentifier(signedInUserUniqueName, UserIdentifierType.RequiredDisplayableId));


                // Get rolesAssignments to application on the subscription
                string requestUrl = string.Format("{0}/subscriptions/{1}/providers/microsoft.authorization/roleassignments?api-version={2}&$filter=principalId eq '{3}'",
                                                  ConfigurationManager.AppSettings["ida:AzureResourceManagerUrl"], subscriptionId,
                                                  ConfigurationManager.AppSettings["ida:ARMAuthorizationRoleAssignmentsAPIVersion"], objectId);

                // Make the GET request
                HttpClient         client  = new HttpClient();
                HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, requestUrl);
                request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);
                HttpResponseMessage response = client.SendAsync(request).Result;

                // Endpoint returns JSON with an array of role assignments
                // properties                                  id                                          type                                        name
                // ----------                                  --                                          ----                                        ----
                // @{roleDefinitionId=/subscriptions/e91d47... /subscriptions/e91d4...1-a796-2...          Microsoft.Authorization/roleAssignments     9db2cd....b1b8

                if (response.IsSuccessStatusCode)
                {
                    string responseContent       = response.Content.ReadAsStringAsync().Result;
                    var    roleAssignmentsResult = (Json.Decode(responseContent)).value;

                    //remove all role assignments
                    foreach (var roleAssignment in roleAssignmentsResult)
                    {
                        requestUrl = string.Format("{0}{1}?api-version={2}",
                                                   ConfigurationManager.AppSettings["ida:AzureResourceManagerUrl"], roleAssignment.id,
                                                   ConfigurationManager.AppSettings["ida:ARMAuthorizationRoleAssignmentsAPIVersion"]);

                        request = new HttpRequestMessage(HttpMethod.Delete, requestUrl);
                        request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);
                        response = client.SendAsync(request).Result;
                    }
                }
            }
            catch { }
        }
コード例 #17
0
        public static string AcquireToken(string userObjectId)
        {
            ClientCredential      cred        = new ClientCredential(ConfigHelper.ClientId, ConfigHelper.AppKey);
            string                tenantId    = ClaimsPrincipal.Current.FindFirst(Globals.TenantIdClaimType).Value;
            AuthenticationContext authContext = new AuthenticationContext(String.Format(CultureInfo.InvariantCulture, ConfigHelper.AadInstance, tenantId), new TokenDbCache(userObjectId));
            AuthenticationResult  result      = authContext.AcquireTokenSilent(ConfigHelper.GraphResourceId, cred, new UserIdentifier(userObjectId, UserIdentifierType.UniqueId));

            return(result.AccessToken);
        }
コード例 #18
0
        public ActionResult Create([Bind(Include = "DisplayName,Description,MailNickName,SecurityEnabled")] Group group)
        {
            //Get the access token as we need it to make a call to the Graph API
            AuthenticationResult result = null;

            try
            {
                // Get the access token from the cache
                string userObjectID = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
                AuthenticationContext authContext = new AuthenticationContext(Startup.Authority,
                                                                              new NaiveSessionCache(userObjectID));
                ClientCredential credential = new ClientCredential(clientId, appKey);
                result = authContext.AcquireTokenSilent(graphResourceId, credential,
                                                        new UserIdentifier(userObjectID, UserIdentifierType.UniqueId));
            }
            catch (Exception e)
            {
                if (Request.QueryString["reauth"] == "True")
                {
                    //
                    // Send an OpenID Connect sign-in request to get a new set of tokens.
                    // If the user still has a valid session with Azure AD, they will not be prompted for their credentials.
                    // The OpenID Connect middleware will return to this controller after the sign-in response has been handled.
                    //
                    HttpContext.GetOwinContext().Authentication.Challenge(OpenIdConnectAuthenticationDefaults.AuthenticationType);
                }

                //
                // The user needs to re-authorize.  Show them a message to that effect.
                //
                ViewBag.ErrorMessage = "AuthorizationRequired";
                return(View());
            }

            try
            {
                // Setup Graph API connection and add Group
                Guid          ClientRequestId = Guid.NewGuid();
                GraphSettings graphSettings   = new GraphSettings();
                graphSettings.ApiVersion = GraphConfiguration.GraphApiVersion;
                if (result != null)
                {
                    GraphConnection graphConnection = new GraphConnection(result.AccessToken, ClientRequestId,
                                                                          graphSettings);
                    group.MailEnabled = false;
                    graphConnection.Add(group);
                    return(RedirectToAction("Index"));
                }
            }
            catch (Exception exception)
            {
                ModelState.AddModelError("", exception.Message);
                return(View());
            }
            ViewBag.ErrorMessage = "AuthorizationRequired";
            return(View());
        }
コード例 #19
0
        public static string GetRoleId(string roleName, string subscriptionId, string organizationId)
        {
            string roleId = null;

            string signedInUserUniqueName = ClaimsPrincipal.Current.FindFirst(ClaimTypes.Name).Value.Split('#')[ClaimsPrincipal.Current.FindFirst(ClaimTypes.Name).Value.Split('#').Length - 1];

            try
            {
                // Aquire Access Token to call Azure Resource Manager
                X509Certificate2 keyCredential = new X509Certificate2(HttpContext.Current.Server.MapPath
                                                                          (ConfigurationManager.AppSettings["KeyCredentialPath"]), "", X509KeyStorageFlags.MachineKeySet);
                ClientAssertionCertificate clientAssertion = new ClientAssertionCertificate(ConfigurationManager.AppSettings["ClientId"], keyCredential);

                // initialize AuthenticationContext with the token cache of the currently signed in user, as kept in the app's EF DB
                AuthenticationContext authContext = new AuthenticationContext(
                    string.Format(ConfigurationManager.AppSettings["Authority"], organizationId), new ADALTokenCache(signedInUserUniqueName));
                AuthenticationResult result = authContext.AcquireTokenSilent(ConfigurationManager.AppSettings["AzureResourceManagerIdentifier"], clientAssertion,
                                                                             new UserIdentifier(signedInUserUniqueName, UserIdentifierType.RequiredDisplayableId));

                // Get subscriptions to which the user has some kind of access
                string requestUrl = string.Format("{0}/subscriptions/{1}/providers/Microsoft.Authorization/roleDefinitions?api-version={2}",
                                                  ConfigurationManager.AppSettings["AzureResourceManagerUrl"], subscriptionId,
                                                  ConfigurationManager.AppSettings["ARMAuthorizationRoleDefinitionsAPIVersion"]);

                // Make the GET request
                HttpClient         client  = new HttpClient();
                HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, requestUrl);
                request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);
                HttpResponseMessage response = client.SendAsync(request).Result;

                // Endpoint returns JSON with an array of roleDefinition Objects
                // properties                                  id                                          type                                        name
                // ----------                                  --                                          ----                                        ----
                // @{roleName=Contributor; type=BuiltInRole... /subscriptions/e91d47c4-76f3-4271-a796-2... Microsoft.Authorization/roleDefinitions     b24988ac-6180-42a0-ab88-20f7382dd24c
                // @{roleName=Owner; type=BuiltInRole; desc... /subscriptions/e91d47c4-76f3-4271-a796-2... Microsoft.Authorization/roleDefinitions     8e3af657-a8ff-443c-a75c-2fe8c4bcb635
                // @{roleName=Reader; type=BuiltInRole; des... /subscriptions/e91d47c4-76f3-4271-a796-2... Microsoft.Authorization/roleDefinitions     acdd72a7-3385-48ef-bd42-f606fba81ae7
                // ...

                if (response.IsSuccessStatusCode)
                {
                    string responseContent       = response.Content.ReadAsStringAsync().Result;
                    var    roleDefinitionsResult = (Json.Decode(responseContent)).value;

                    foreach (var roleDefinition in roleDefinitionsResult)
                    {
                        if ((roleDefinition.properties.roleName as string).Equals(roleName, StringComparison.CurrentCultureIgnoreCase))
                        {
                            roleId = roleDefinition.id;
                            break;
                        }
                    }
                }
            }
            catch { }

            return(roleId);
        }
コード例 #20
0
        public static List <Subscription> GetUserSubscriptions(string organizationId)
        {
            List <Subscription> subscriptions = null;

            string signedInUserUniqueName = ClaimsPrincipal.Current.FindFirst(ClaimTypes.Name).Value.Split('#')[ClaimsPrincipal.Current.FindFirst(ClaimTypes.Name).Value.Split('#').Length - 1];

            try
            {
                // Aquire Access Token to call Azure Resource Manager
                X509Certificate2 keyCredential = new X509Certificate2(HttpContext.Current.Server.MapPath
                                                                          (ConfigurationManager.AppSettings["KeyCredentialPath"]), "", X509KeyStorageFlags.MachineKeySet);
                ClientAssertionCertificate clientAssertion = new ClientAssertionCertificate(ConfigurationManager.AppSettings["ClientId"], keyCredential);

                // initialize AuthenticationContext with the token cache of the currently signed in user, as kept in the app's EF DB
                AuthenticationContext authContext = new AuthenticationContext(
                    string.Format(ConfigurationManager.AppSettings["Authority"], organizationId), new ADALTokenCache(signedInUserUniqueName));
                AuthenticationResult result = authContext.AcquireTokenSilent(ConfigurationManager.AppSettings["AzureResourceManagerIdentifier"], clientAssertion,
                                                                             new UserIdentifier(signedInUserUniqueName, UserIdentifierType.RequiredDisplayableId));

                subscriptions = new List <Subscription>();

                // Get subscriptions to which the user has some kind of access
                string requestUrl = string.Format("{0}/subscriptions?api-version={1}", ConfigurationManager.AppSettings["AzureResourceManagerUrl"],
                                                  ConfigurationManager.AppSettings["AzureResourceManagerAPIVersion"]);

                // Make the GET request
                HttpClient         client  = new HttpClient();
                HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, requestUrl);
                request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);
                HttpResponseMessage response = client.SendAsync(request).Result;

                // Endpoint returns JSON with an array of Subscription Objects
                // id                                                  subscriptionId                       displayName state
                // --                                                  --------------                       ----------- -----
                // /subscriptions/c276fc76-9cd4-44c9-99a7-4fd71546436e c276fc76-9cd4-44c9-99a7-4fd71546436e Production  Enabled
                // /subscriptions/e91d47c4-76f3-4271-a796-21b4ecfe3624 e91d47c4-76f3-4271-a796-21b4ecfe3624 Development Enabled

                if (response.IsSuccessStatusCode)
                {
                    string responseContent     = response.Content.ReadAsStringAsync().Result;
                    var    subscriptionsResult = (Json.Decode(responseContent)).value;

                    foreach (var subscription in subscriptionsResult)
                    {
                        subscriptions.Add(new Subscription()
                        {
                            Id          = subscription.subscriptionId,
                            DisplayName = subscription.displayName,
                        });
                    }
                }
            }
            catch { }

            return(subscriptions);
        }
コード例 #21
0
        public static AuthenticationResult GetAuthenticationResult(string resoureceId)
        {
            string userObjectID = ClaimsPrincipal.Current.FindFirst(AzureADConfiguration.ObjectIdClaimType).Value;
            AuthenticationContext authContext = new AuthenticationContext(aadConfig.Authority);
            ClientCredential      credential  = new ClientCredential(aadConfig.ClientId, aadConfig.AppKey);

            var result = authContext.AcquireTokenSilent(resoureceId, credential, new UserIdentifier(userObjectID, UserIdentifierType.UniqueId));

            return(result);
        }
コード例 #22
0
        private string getTokenForGraph(string tenantID, string signedInUserID, string userObjectID, string clientId, string appKey, string graphResourceID)
        {
            // get a token for the Graph without triggering any user interaction (from the cache, via multi-resource refresh token, etc)
            ClientCredential clientcred = new ClientCredential(clientId, appKey);
            // initialize AuthenticationContext with the token cache of the currently signed in user, as kept in the app's EF DB
            AuthenticationContext authContext = new AuthenticationContext(string.Format("https://login.windows.net/{0}", tenantID), new EFADALTokenCache(signedInUserID));
            AuthenticationResult  result      = authContext.AcquireTokenSilent(graphResourceID, clientcred, new UserIdentifier(userObjectID, UserIdentifierType.UniqueId));

            return(result.AccessToken);
        }
コード例 #23
0
        /// <summary>
        /// Gets a list of <see cref="User"/> objects that are members of a give <see cref="Role"/>.
        /// </summary>
        /// <param name="objectId">Unique identifier of the <see cref="Role"/>.</param>
        /// <returns>A view with the list of <see cref="User"/> objects.</returns>
        public ActionResult GetMembers(string objectId)
        {
            //Get the access token as we need it to make a call to the Graph API
            AuthenticationResult result = null;
            IList <User>         users  = new List <User>();

            try
            {
                // Get the access token from the cache
                string userObjectID = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
                AuthenticationContext authContext = new AuthenticationContext(Startup.Authority,
                                                                              new NaiveSessionCache(userObjectID));
                ClientCredential credential = new ClientCredential(clientId, appKey);
                result = authContext.AcquireTokenSilent(graphResourceId, credential,
                                                        new UserIdentifier(userObjectID, UserIdentifierType.UniqueId));

                // Setup Graph API connection and get a list of roles
                Guid          ClientRequestId = Guid.NewGuid();
                GraphSettings graphSettings   = new GraphSettings();
                graphSettings.ApiVersion = GraphConfiguration.GraphApiVersion;
                GraphConnection graphConnection = new GraphConnection(result.AccessToken, ClientRequestId, graphSettings);

                Role role = graphConnection.Get <Role>(objectId);
                IList <GraphObject> members = graphConnection.GetAllDirectLinks(role, LinkProperty.Members);

                // Filter for users
                foreach (GraphObject obj in members)
                {
                    if (obj is User)
                    {
                        users.Add((User)obj);
                    }
                }
            }
            catch (Exception e)
            {
                if (Request.QueryString["reauth"] == "True")
                {
                    //
                    // Send an OpenID Connect sign-in request to get a new set of tokens.
                    // If the user still has a valid session with Azure AD, they will not be prompted for their credentials.
                    // The OpenID Connect middleware will return to this controller after the sign-in response has been handled.
                    //
                    HttpContext.GetOwinContext().Authentication.Challenge(OpenIdConnectAuthenticationDefaults.AuthenticationType);
                }

                //
                // The user needs to re-authorize.  Show them a message to that effect.
                //
                ViewBag.ErrorMessage = "AuthorizationRequired";
                return(View());
            }

            return(View(users));
        }
コード例 #24
0
        /// <summary>
        /// This helper method returns and OAuth Access Token for the current user
        /// </summary>
        /// <param name="resourceId">The resourceId for which we are requesting the token</param>
        /// <returns>The OAuth Access Token value</returns>
        public static String GetAccessTokenForCurrentUser(String resourceId = null)
        {
            String accessToken = null;

            if (String.IsNullOrEmpty(resourceId))
            {
                resourceId = O365ProjectsAppSettings.MicrosoftGraphResourceId;
            }

            try
            {
                ClientCredential credential = new ClientCredential(
                    O365ProjectsAppSettings.ClientId,
                    O365ProjectsAppSettings.ClientSecret);

                String signedInUserID = System.Security.Claims.ClaimsPrincipal.Current.FindFirst(
                    ClaimTypes.NameIdentifier).Value;
                String tenantId = System.Security.Claims.ClaimsPrincipal.Current.FindFirst(
                    "http://schemas.microsoft.com/identity/claims/tenantid").Value;

                AuthenticationContext authContext = new AuthenticationContext(
                    O365ProjectsAppSettings.AADInstance + tenantId,
                    new SessionADALCache(signedInUserID));

                AuthenticationResult result = authContext.AcquireTokenSilent(
                    resourceId,
                    credential,
                    UserIdentifier.AnyUser);

                if (result != null)
                {
                    accessToken = result.AccessToken;
                }
            }
            catch (AdalException ex)
            {
                if (ex.ErrorCode == "failed_to_acquire_token_silently")
                {
                    // Refresh the access token from scratch
                    HttpContext.Current.GetOwinContext().Authentication.Challenge(
                        new AuthenticationProperties
                    {
                        RedirectUri = HttpContext.Current.Request.Url.ToString(),
                    },
                        OpenIdConnectAuthenticationDefaults.AuthenticationType);
                }
                else
                {
                    // Rethrow the exception
                    throw ex;
                }
            }

            return(accessToken);
        }
        /// <summary>
        /// Creates a view to for adding a key credential to an existing <see cref="Application"/> in Graph.
        /// </summary>
        /// <param name="objectId">Unique identifier of the <see cref="Application"/>.</param>
        /// <returns>A view with details to add a key to the <see cref="Application"/>.</returns>
        public ActionResult AddKey(string objectId)
        {
            //Get the access token as we need it to make a call to the Graph API
            AuthenticationResult result = null;
            Application          app    = null;

            try
            {
                // Get the access token from the cache
                string userObjectID = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
                AuthenticationContext authContext = new AuthenticationContext(Startup.Authority,
                                                                              new NaiveSessionCache(userObjectID));
                ClientCredential credential = new ClientCredential(clientId, appKey);
                result = authContext.AcquireTokenSilent(graphResourceId, credential,
                                                        new UserIdentifier(userObjectID, UserIdentifierType.UniqueId));

                //Setup Graph API connection and get a list of groups
                Guid          ClientRequestId = Guid.NewGuid();
                GraphSettings graphSettings   = new GraphSettings();
                graphSettings.ApiVersion = GraphConfiguration.GraphApiVersion;
                GraphConnection graphConnection = new GraphConnection(result.AccessToken, ClientRequestId, graphSettings);

                app = graphConnection.Get <Application>(objectId);
            }
            catch (Exception e)
            {
                if (Request.QueryString["reauth"] == "True")
                {
                    //
                    // Send an OpenID Connect sign-in request to get a new set of tokens.
                    // If the user still has a valid session with Azure AD, they will not be prompted for their credentials.
                    // The OpenID Connect middleware will return to this controller after the sign-in response has been handled.
                    //
                    HttpContext.GetOwinContext().Authentication.Challenge(OpenIdConnectAuthenticationDefaults.AuthenticationType);
                }

                //
                // The user needs to re-authorize.  Show them a message to that effect.
                //
                ViewBag.ErrorMessage = "AuthorizationRequired";
                return(View());
            }
            KeyCredential key = new KeyCredential();

            key.KeyId = System.Guid.NewGuid();
            key.Type  = "Symmetric";
            key.Usage = "Verify";
            String keyValue = "VSoJ0xLgSyQv60M+mJCtJOMM6yflDz5pLnAVNzGT6do=";

            byte[] keyBytes = System.Text.Encoding.ASCII.GetBytes(keyValue);
            key.Value = keyBytes;
            app.KeyCredentials.Add(key);

            return(View(app));
        }
コード例 #26
0
        internal static void MsaTest()
        {
            AadSts sts = new AadSts();

            string liveIdtoken = StsLoginFlow.TryGetSamlToken("https://login.live.com", sts.MsaUserName, sts.MsaPassword, "urn:federation:MicrosoftOnline");
            var    context     = new AuthenticationContext(sts.Authority, sts.ValidateAuthority);

            try
            {
                var result = context.AcquireToken(sts.ValidResource, sts.ValidClientId, new UserAssertion(liveIdtoken, "urn:ietf:params:oauth:grant-type:saml1_1-bearer"));
                VerifySuccessResult(result);

                var result2 = context.AcquireTokenSilent(sts.ValidResource2, sts.ValidClientId, new UserIdentifier(sts.MsaUserName, UserIdentifierType.OptionalDisplayableId));
                VerifySuccessResult(result2);
                Verify.IsNotNull(result2.RefreshToken);
                Verify.IsTrue(result2.IsMultipleResourceRefreshToken);

                AuthenticationContextProxy.Delay(2000);   // 2 seconds delay

                var result3 = context.AcquireTokenSilent(sts.ValidResource, sts.ValidClientId, new UserIdentifier(sts.MsaUserName, UserIdentifierType.OptionalDisplayableId));
                VerifySuccessResult(result3);
                Verify.IsTrue(AreDateTimeOffsetsEqual(result.ExpiresOn, result3.ExpiresOn));
            }
            catch (Exception ex)
            {
                Verify.Fail("Unexpected exception: " + ex);
            }

            try
            {
                context.TokenCache.Clear();
                var result = context.AcquireToken(sts.ValidResource, sts.ValidClientId, new UserAssertion("x", "urn:ietf:params:oauth:grant-type:saml1_1-bearer"));
                Verify.Fail("Exception expected");
                VerifySuccessResult(result);
            }
            catch (AdalServiceException ex)
            {
                Verify.AreEqual(ex.ErrorCode, "invalid_grant");
                Verify.AreEqual(ex.StatusCode, 400);
                Verify.IsTrue(ex.ServiceErrorCodes.Contains("50008"));
            }
        }
コード例 #27
0
        public static string GetOrganizationDisplayName(string organizationId)
        {
            string displayName = null;

            string signedInUserUniqueName = ClaimsPrincipal.Current.FindFirst(ClaimTypes.Name).Value.Split('#')[ClaimsPrincipal.Current.FindFirst(ClaimTypes.Name).Value.Split('#').Length - 1];

            try
            {
                // Aquire Access Token to call Azure AD Graph API
                ClientCredential credential = new ClientCredential(ConfigurationManager.AppSettings["ida:ClientID"],
                                                                   ConfigurationManager.AppSettings["ida:Password"]);
                // initialize AuthenticationContext with the token cache of the currently signed in user, as kept in the app's EF DB
                AuthenticationContext authContext = new AuthenticationContext(
                    string.Format(ConfigurationManager.AppSettings["ida:Authority"], organizationId), new ADALTokenCache(signedInUserUniqueName));

                AuthenticationResult result = authContext.AcquireTokenSilent(ConfigurationManager.AppSettings["ida:GraphAPIIdentifier"], credential,
                                                                             new UserIdentifier(signedInUserUniqueName, UserIdentifierType.RequiredDisplayableId));

                // Get a list of Organizations of which the user is a member
                string requestUrl = string.Format("{0}{1}/tenantDetails?api-version={2}", ConfigurationManager.AppSettings["ida:GraphAPIIdentifier"],
                                                  organizationId, ConfigurationManager.AppSettings["ida:GraphAPIVersion"]);

                // Make the GET request
                HttpClient         client  = new HttpClient();
                HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, requestUrl);
                request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);
                HttpResponseMessage response = client.SendAsync(request).Result;

                // Endpoint returns JSON with an array of Tenant Objects
                if (response.IsSuccessStatusCode)
                {
                    string responseContent = response.Content.ReadAsStringAsync().Result;
                    var    organizationPropertiesResult = (Json.Decode(responseContent)).value;
                    if (organizationPropertiesResult != null && organizationPropertiesResult.Length > 0)
                    {
                        displayName = organizationPropertiesResult[0].displayName;
                        if (organizationPropertiesResult[0].verifiedDomains != null)
                        {
                            foreach (var verifiedDomain in organizationPropertiesResult[0].verifiedDomains)
                            {
                                if (verifiedDomain["default"])
                                {
                                    displayName += " (" + verifiedDomain.name + ")";
                                }
                            }
                        }
                    }
                }
            }
            catch { }

            return(displayName);
        }
コード例 #28
0
        /// <summary>
        /// Method to get display name of organization based on Organization id and AAD object Id.
        /// </summary>
        /// <param name="organizationId">Organization Id.</param>
        /// <param name="objectId">AAD Object Id.</param>
        /// <returns>Display Name of the organization.</returns>
        public static string LookupDisplayNameOfAADObject(string organizationId, string objectId)
        {
            string objectDisplayName = null;

            string signedInUserUniqueName =
                ClaimsPrincipal.Current.FindFirst(ClaimTypes.Name).Value.Split('#')[ClaimsPrincipal.Current.FindFirst(ClaimTypes.Name).Value.Split('#').Length - 1];

            // Acquire Access Token to call Azure AD Graph API
            ClientCredential credential = new ClientCredential(
                ConfigurationManager.AppSettings["ida:ClientID"],
                ConfigurationManager.AppSettings["ida:Password"]);

            // Initialize AuthenticationContext with the token cache of the currently signed in user, as kept in the app's EF DB
            AuthenticationContext authContext = new AuthenticationContext(
                string.Format(
                    CultureInfo.InvariantCulture,
                    ConfigurationManager.AppSettings["ida:Authority"],
                    organizationId));

            AuthenticationResult result =
                authContext.AcquireTokenSilent(
                    ConfigurationManager.AppSettings["ida:GraphAPIIdentifier"],
                    credential,
                    new UserIdentifier(
                        signedInUserUniqueName,
                        UserIdentifierType.RequiredDisplayableId));

            string doQueryUrl = string.Format(
                CultureInfo.InvariantCulture,
                "{0}{1}/directoryObjects/{2}?api-version={3}",
                ConfigurationManager.AppSettings["ida:GraphAPIIdentifier"],
                organizationId,
                objectId,
                ConfigurationManager.AppSettings["ida:GraphAPIVersion"]);

            HttpResponseMessage response = GetRequestResponse(result, doQueryUrl);

            if (response.IsSuccessStatusCode)
            {
                var    responseContent = response.Content;
                string responseString  = responseContent.ReadAsStringAsync().Result;
                var    directoryObject = System.Web.Helpers.Json.Decode(responseString);
                if (directoryObject != null)
                {
                    objectDisplayName = string.Format(
                        "{0} ({1})",
                        directoryObject.displayName,
                        directoryObject.objectType);
                }
            }

            return(objectDisplayName);
        }
コード例 #29
0
        /// <summary>
        /// Gets a list of <see cref="Contact"/> objects from Graph.
        /// </summary>
        /// <returns>A view with the list of <see cref="Contact"/> objects.</returns>
        public ActionResult Index()
        {
            //Get the access token as we need it to make a call to the Graph API
            AuthenticationResult result      = null;
            List <Contact>       contactList = new List <Contact>();

            try
            {
                // Get the access token from the cache
                string userObjectID = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
                AuthenticationContext authContext = new AuthenticationContext(Startup.Authority,
                                                                              new NaiveSessionCache(userObjectID));
                ClientCredential credential = new ClientCredential(clientId, appKey);
                result = authContext.AcquireTokenSilent(graphResourceId, credential,
                                                        new UserIdentifier(userObjectID, UserIdentifierType.UniqueId));

                // Setup Graph API connection and get a list of users
                Guid          ClientRequestId = Guid.NewGuid();
                GraphSettings graphSettings   = new GraphSettings();
                graphSettings.ApiVersion = GraphConfiguration.GraphApiVersion;
                GraphConnection graphConnection = new GraphConnection(result.AccessToken, ClientRequestId, graphSettings);

                // Get all results into a list
                PagedResults <Contact> pagedResults = graphConnection.List <Contact>(null, new FilterGenerator());
                contactList.AddRange(pagedResults.Results);
                while (!pagedResults.IsLastPage)
                {
                    pagedResults = graphConnection.List <Contact>(pagedResults.PageToken, new FilterGenerator());
                    contactList.AddRange(pagedResults.Results);
                }
            }
            catch (Exception e)
            {
                if (Request.QueryString["reauth"] == "True")
                {
                    //
                    // Send an OpenID Connect sign-in request to get a new set of tokens.
                    // If the user still has a valid session with Azure AD, they will not be prompted for their credentials.
                    // The OpenID Connect middleware will return to this controller after the sign-in response has been handled.
                    //
                    HttpContext.GetOwinContext().Authentication.Challenge(OpenIdConnectAuthenticationDefaults.AuthenticationType);
                }

                //
                // The user needs to re-authorize.  Show them a message to that effect.
                //
                ViewBag.ErrorMessage = "AuthorizationRequired";
                return(View());
            }

            return(View(contactList));
        }
コード例 #30
0
ファイル: GraphUtil.cs プロジェクト: jezlloyd/VipSwapper
        /// <summary>
        /// In the case of Groups claim overage, we must query the GraphAPI to obtain the group membership.
        /// Here we use the GraphAPI Client Library to do so.
        /// </summary>
        /// <param name="claimsIdentity">The <see cref="ClaimsIdenity" /> object that represents the
        /// claims-based identity of the currently signed in user and contains thier claims.</param>
        /// <returns>A list of ObjectIDs representing the groups that the user is member of.</returns>
        private static async Task <List <string> > GetGroupsFromGraphAPI(ClaimsIdentity claimsIdentity)
        {
            List <string> groupObjectIds = new List <string>();

            string tenantId       = claimsIdentity.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;
            string signedInUserID = claimsIdentity.FindFirst(System.IdentityModel.Claims.ClaimTypes.NameIdentifier).Value;
            string userObjectID   = claimsIdentity.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;

            // Aquire Access Token to call Graph
            ClientCredential credential = new ClientCredential(ConfigurationManager.AppSettings["ida:ClientID"],
                                                               ConfigurationManager.AppSettings["ida:Password"]);
            // initialize AuthenticationContext with the token cache of the currently signed in user, as kept in the app's EF DB
            AuthenticationContext authContext = new AuthenticationContext(
                string.Format(ConfigurationManager.AppSettings["ida:Authority"], tenantId), new ADALTokenCache(signedInUserID));
            AuthenticationResult result = authContext.AcquireTokenSilent(
                ConfigurationManager.AppSettings["ida:GraphAPIIdentifier"], credential, new UserIdentifier(userObjectID, UserIdentifierType.UniqueId));

            // Get the GraphAPI Group Endpoint for the specific user from the _claim_sources claim in token
            string groupsClaimSourceIndex = (Json.Decode(claimsIdentity.FindFirst("_claim_names").Value)).groups;
            var    groupClaimsSource      = (Json.Decode(claimsIdentity.FindFirst("_claim_sources").Value))[groupsClaimSourceIndex];
            string requestUrl             = groupClaimsSource.endpoint + "?api-version=" + ConfigurationManager.AppSettings["ida:GraphAPIVersion"];

            // Prepare and Make the POST request
            HttpClient         client  = new HttpClient();
            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, requestUrl);

            request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);
            StringContent content = new StringContent("{\"securityEnabledOnly\": \"false\"}");

            content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
            request.Content             = content;
            HttpResponseMessage response = await client.SendAsync(request);

            // Endpoint returns JSON with an array of Group ObjectIDs
            if (response.IsSuccessStatusCode)
            {
                string responseContent = await response.Content.ReadAsStringAsync();

                var groupsResult = (Json.Decode(responseContent)).value;

                foreach (string groupObjectID in groupsResult)
                {
                    groupObjectIds.Add(groupObjectID);
                }
            }
            else
            {
                throw new WebException();
            }

            return(groupObjectIds);
        }
コード例 #31
0
        /// <summary>
        /// Get the token for authenticating requests to Azure Resource Manager in customer tenant.
        /// </summary>
        /// <param name="appId">appid that is registered for this application in Azure Active Directory (AAD)</param>
        /// <param name="key">This is the key for this application in Azure Active Directory</param>
        /// <param name="customerTenantId">cid of the customer</param>
        /// <returns>Azure Auth Token in the context of the customer tenant.</returns>
        private static AuthenticationResult GetAzureAuthTokenForCustomerTenant(string appId, string credentialName, string customerTenantId)
        {
            AuthenticationResult authResult = null;
            string resource = "https://management.core.windows.net/";

            var authenticationContext = new AuthenticationContext("https://login.windows.net/" + customerTenantId);
            try
            {
                authResult = authenticationContext.AcquireTokenSilent(resource: resource, clientId: appId);
            }
            catch (AdalException aex)
            {
                if (aex.ErrorCode == "failed_to_acquire_token_silently")
                {
                    UserCredential uc = CredentialManager.GetCredential(credentialName);
                    authResult = authenticationContext.AcquireToken(resource: resource, clientId: appId, userCredential: uc);
                }
            }
            catch (Exception ex)
            {
                throw;
            }

            return authResult;
        }