Exemplo n.º 1
0
        public override async Task <ActionResponse> ExecuteActionAsync(ActionRequest request)
        {
            var azureToken   = request.DataStore.GetJson("AzureToken");
            var subscription = request.DataStore.GetJson("SelectedSubscription", "SubscriptionId");

            JObject graphToken = AzureTokenUtility.GetTokenForResource(request, azureToken, "https://graph.windows.net");

            var tenantId = AzureUtility.GetTenantFromToken(request.DataStore.GetJson("AzureToken"));

            // Generate new key for ClientSecret
            string key          = GetNewKey();
            string graphUriBase = "https://graph.windows.net/{0}/applications";

            string graphApi = string.Format(graphUriBase, tenantId);

            AzureHttpClient client  = new AzureHttpClient(graphToken["access_token"].ToString(), subscription);
            dynamic         payload = new ExpandoObject();

            payload.displayName             = "solutiontemplate";
            payload.availableToOtherTenants = false;
            payload.homepage          = "www.test.com";
            payload.identifierUris    = new string[1];
            payload.identifierUris[0] = "https://test.com/" + RandomGenerator.GetRandomLowerCaseCharacters(10);

            payload.passwordCredentials              = new ExpandoObject[1];
            payload.passwordCredentials[0]           = new ExpandoObject();
            payload.passwordCredentials[0].startDate = DateTime.UtcNow.ToString("o");
            payload.passwordCredentials[0].endDate   = DateTime.UtcNow.AddYears(3).ToString("o");
            payload.passwordCredentials[0].keyId     = Guid.NewGuid();
            payload.passwordCredentials[0].value     = key;

            string body = JsonUtility.GetJsonStringFromObject(payload);

            var response = await client.ExecuteGenericRequestWithHeaderAsync(HttpMethod.Post, graphApi + "?api-version=1.6", body);

            string responseBody = await response.Content.ReadAsStringAsync();

            JObject responseBodyObj = JsonUtility.GetJObjectFromJsonString(responseBody);

            if (response.IsSuccessStatusCode)
            {
                string appId = responseBodyObj["appId"].ToString();
                string obbId = responseBodyObj["objectId"].ToString();

                responseBodyObj.Add("SPNAppId", appId);
                responseBodyObj.Add("SPNKey", key);
                responseBodyObj.Add("SPNUser", "app:" + appId + "@" + tenantId);
                responseBodyObj.Add("SPNTenantId", tenantId);

                // Delete the SPN if required
                //string graphUriBaseWithApplication = "https://graph.windows.net/{0}/applications/{1}";
                //string graphApiWithApp = string.Format(graphUriBaseWithApplication, tenantId, obbId);
                //response = await client.ExecuteGenericRequestWithHeaderAsync(HttpMethod.Delete, graphApiWithApp + "?api-version=1.6", body);

                return(new ActionResponse(ActionStatus.Success, responseBodyObj, true));
            }

            return(new ActionResponse(ActionStatus.Failure, responseBody, null, null, "Unable to create a Service Principal"));
        }
        public override async Task <ActionResponse> ExecuteActionAsync(ActionRequest request)
        {
            string  code      = request.DataStore.GetValue("code");
            string  aadTenant = request.DataStore.GetValue("AADTenant");
            string  oauthType = (request.DataStore.GetValue("oauthType") ?? string.Empty).ToLowerInvariant();
            JObject token     = new JObject();

            token = oauthType == "mscrm" ? AzureTokenUtility.GetTokenForResourceFromCode(Constants.AzureManagementCoreApi, Constants.MsCrmClientId, aadTenant, request.Info.WebsiteRootUrl, code) :
                    AzureTokenUtility.GetTokenForResourceFromCode(oauthType, aadTenant, request.Info.WebsiteRootUrl, code);

            if (token.SelectToken("error") != null)
            {
                return(new ActionResponse(ActionStatus.Failure, token, null, DefaultErrorCodes.DefaultLoginFailed, token.SelectToken("error_description")?.ToString()));
            }

            var emailAddress = AzureUtility.GetEmailFromToken(token);

            if (emailAddress.Contains('#'))
            {
                emailAddress = emailAddress.Split('#')?[1];
            }
            request.DataStore.AddToDataStore("EmailAddress", emailAddress);

            switch (oauthType)
            {
            case "keyvault":
                request.DataStore.AddToDataStore("AzureTokenKV", token);
                break;

            case "as":
                request.DataStore.AddToDataStore("AzureTokenAS", token);
                break;

            case "mscrm":
                JObject crmToken = AzureTokenUtility.GetTokenForResourceFromExistingToken(oauthType, request.Info.WebsiteRootUrl, token, Constants.MsCrmResource);
                request.DataStore.AddToDataStore("MsCrmToken", crmToken);
                request.DataStore.AddToDataStore("AzureToken", token);
                break;

            case "powerbi":
                request.DataStore.AddToDataStore("PBIToken", token);
                request.DataStore.AddToDataStore("DirectoryName", emailAddress.Split('@').Last());
                request.DataStore.AddToDataStore("PowerBITenantId", AzureUtility.GetTenantFromToken(token));
                break;

            default:
                request.DataStore.AddToDataStore("AzureToken", token);
                var tenantId      = AzureUtility.GetTenantFromToken(token);
                var directoryName = emailAddress.Split('@').Last();
                request.DataStore.AddToDataStore("DirectoryName", directoryName);
                request.DataStore.AddToDataStore("PowerBITenantId", tenantId);
                break;
            }

            return(new ActionResponse(ActionStatus.Success, token, true));
        }
Exemplo n.º 3
0
        public override async Task <ActionResponse> ExecuteActionAsync(ActionRequest request)
        {
            List <string> axInstances = new List <string>();
            var           tenantId    = AzureUtility.GetTenantFromToken(request.DataStore.GetJson("AzureToken"));
            string        axToken     = request.DataStore.GetJson("AxToken", "access_token");

            var jwtToken     = new JwtSecurityToken(axToken);
            var userObjectId = jwtToken.Claims.First(e => e.Type == "oid")?.Value;

            if (string.IsNullOrEmpty(userObjectId))
            {
                return(new ActionResponse(ActionStatus.Failure, "User Object Id cannot be null. "));
            }

            if (string.IsNullOrEmpty(tenantId))
            {
                return(new ActionResponse(ActionStatus.Failure, "Tenant Id cannot be null. "));
            }

            if (string.IsNullOrEmpty(axToken))
            {
                return(new ActionResponse(ActionStatus.Failure, "No Dynamics 365 token available."));
            }

            var ctx   = new AuthenticationContext(string.Format(Constants.AxLocatorLoginAuthority, tenantId));
            var token = await ctx.AcquireTokenAsync(Constants.AxErpResource, new ClientCredential(Constants.AxLocatorClientId, Constants.AxLocatorSecret));

            HttpResponseMessage response;

            using (HttpClient client = new HttpClient())
            {
                client.BaseAddress = new Uri(Constants.AxLocatorBaseUrl);

                client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token.AccessToken);
                client.DefaultRequestHeaders.Add("x-ms-discovery-client-principal-id", userObjectId);
                client.DefaultRequestHeaders.Add("x-ms-discovery-client-tenant-id", tenantId);

                response = client.GetAsync($"/tenantapi/BusinessAppDiscoveryResults(guid'{tenantId}')").Result;
            }

            var content = JsonUtility.GetJsonObjectFromJsonString(await response.Content.ReadAsStringAsync());
            var apps    = content["value"]?[0]?["Apps"];

            if (apps != null)
            {
                foreach (var element in apps)
                {
                    axInstances.Add(element["AppOpenUri"].ToString());
                }

                return(new ActionResponse(ActionStatus.Success, JsonUtility.Serialize(axInstances)));
            }

            return(new ActionResponse(ActionStatus.Success));
        }
Exemplo n.º 4
0
        public static JObject GetTokenForResourceFromExistingToken(string oauthType, string redirect, JToken tokenWithRefresh, string resource)
        {
            JObject tokenObj;

            using (HttpClient httpClient = new HttpClient())
            {
                string tenantId     = AzureUtility.GetTenantFromToken(tokenWithRefresh);
                string refreshToken = AzureUtility.GetRefreshToken(tokenWithRefresh);
                string tokenUrl     = string.Format(Constants.AzureTokenUri, tenantId);

                var           tokenMeta = GetMetaFromOAuthType(oauthType);
                string        token     = AzureTokenUtility.GetTokenBodyFromRefreshToken(refreshToken, resource, redirect, tokenMeta.ClientId);
                StringContent content   = new StringContent(token);
                content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
                string response2 = httpClient.PostAsync(new Uri(tokenUrl), content).Result.Content.AsString();
                tokenObj = JsonUtility.GetJsonObjectFromJsonString(response2);
            }

            return(tokenObj);
        }
Exemplo n.º 5
0
        public static JObject GetTokenForResource(ActionRequest request, JToken azureToken, string resource)
        {
            JObject tokenObj;

            using (HttpClient httpClient = new HttpClient())
            {
                string tenantId     = AzureUtility.GetTenantFromToken(azureToken);
                string refreshToken = AzureUtility.GetRefreshToken(azureToken);
                string tokenUrl     = string.Format(Constants.AzureTokenUri, tenantId);

                string        clientId = GetAzureToken.GetClientIdFromRequest(request);
                string        token    = GetAzureToken.GetTokenUri2(refreshToken, resource, request.Info.WebsiteRootUrl, clientId);
                StringContent content  = new StringContent(token);
                content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
                string response2 = httpClient.PostAsync(new Uri(tokenUrl), content).Result.Content.AsString();
                tokenObj = JsonUtility.GetJsonObjectFromJsonString(response2);
            }

            return(tokenObj);
        }