Exemple #1
0
        public override async Task <ActionResponse> ExecuteActionAsync(ActionRequest request)
        {
            var azureToken   = request.DataStore.GetJson("AzureTokenAS");
            var subscription = request.DataStore.GetJson("SelectedSubscription", "SubscriptionId");

            JObject graphToken = AzureTokenUtility.GetTokenForResourceFromExistingToken("as", request.Info.WebsiteRootUrl, 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));
        }
        public override async Task <ActionResponse> ExecuteActionAsync(ActionRequest request)
        {
            // Handle Azure token slightly diffrent - depends on client id
            if (request.DataStore.GetValue("MsCrmToken") == null && request.DataStore.GetValue("AzureToken") != null && request.DataStore.GetJson("AzureToken", "expires_on") != null)
            {
                var expiryDateTime = UnixTimeStampToDateTime(request.DataStore.GetJson("AzureToken", "expires_on"));
                if ((expiryDateTime - DateTime.Now).TotalMinutes < 5)
                {
                    var dataStoreItem = request.DataStore.GetDataStoreItem("AzureToken");
                    var meta          = AzureTokenUtility.GetMetaFromOAuthType("");
                    var newToken      = AzureTokenUtility.GetTokenForResourceFromExistingToken("", request.Info.WebsiteRootUrl, dataStoreItem.Value, meta.Resource);
                    UpdateToken(dataStoreItem.Value, newToken);
                }
            }

            // Handle Azure token slightly diffrent - depends on client id - use mscrm client id to refresh the token
            // Checks for both tokens in the CRMSalesManagement case
            if (request.DataStore.GetValue("MsCrmToken") != null && request.DataStore.GetValue("AzureToken") != null && request.DataStore.GetJson("AzureToken", "expires_on") != null)
            {
                var expiryDateTime = UnixTimeStampToDateTime(request.DataStore.GetJson("AzureToken", "expires_on"));
                if ((expiryDateTime - DateTime.Now).TotalMinutes < 5)
                {
                    var dataStoreItem = request.DataStore.GetDataStoreItem("AzureToken");
                    var meta          = AzureTokenUtility.GetMetaFromOAuthType("mscrm");
                    var newToken      = AzureTokenUtility.GetTokenForResourceFromExistingToken("mscrm", request.Info.WebsiteRootUrl, dataStoreItem.Value, Constants.AzureManagementCoreApi);
                    UpdateToken(dataStoreItem.Value, newToken);
                }
            }

            if (request.DataStore.GetValue("AzureTokenKV") != null && request.DataStore.GetJson("AzureTokenKV", "expires_on") != null)
            {
                var expiryDateTime = UnixTimeStampToDateTime(request.DataStore.GetJson("AzureTokenKV", "expires_on"));
                if ((expiryDateTime - DateTime.Now).TotalMinutes < 5)
                {
                    var dataStoreItem = request.DataStore.GetDataStoreItem("AzureTokenKV");
                    var meta          = AzureTokenUtility.GetMetaFromOAuthType("keyvault");
                    var newToken      = AzureTokenUtility.GetTokenForResourceFromExistingToken("keyvault", request.Info.WebsiteRootUrl, dataStoreItem.Value, meta.Resource);
                    UpdateToken(dataStoreItem.Value, newToken);
                }
            }

            // Checks for crmtoken expiry in CrmSalesManagement
            if (request.DataStore.GetValue("MsCrmToken") != null && request.DataStore.GetJson("MsCrmToken", "expires_on") != null)
            {
                var expiryDateTime = UnixTimeStampToDateTime(request.DataStore.GetJson("MsCrmToken", "expires_on"));
                if ((expiryDateTime - DateTime.Now).TotalMinutes < 5)
                {
                    var dataStoreItem = request.DataStore.GetDataStoreItem("MsCrmToken");
                    var meta          = AzureTokenUtility.GetMetaFromOAuthType("mscrm");
                    var newToken      = AzureTokenUtility.GetTokenForResourceFromExistingToken("mscrm", request.Info.WebsiteRootUrl, dataStoreItem.Value, meta.Resource);
                    UpdateToken(dataStoreItem.Value, newToken);
                }
            }

            if (request.DataStore.GetValue("AzureTokenAS") != null && request.DataStore.GetJson("AzureTokenAS", "expires_on") != null)
            {
                var expiryDateTime = UnixTimeStampToDateTime(request.DataStore.GetJson("AzureTokenAS", "expires_on"));
                if ((expiryDateTime - DateTime.Now).TotalMinutes < 5)
                {
                    var dataStoreItem = request.DataStore.GetDataStoreItem("AzureTokenAS");
                    var meta          = AzureTokenUtility.GetMetaFromOAuthType("as");
                    var newToken      = AzureTokenUtility.GetTokenForResourceFromExistingToken("as", request.Info.WebsiteRootUrl, dataStoreItem.Value, meta.Resource);
                    UpdateToken(dataStoreItem.Value, newToken);
                }
            }

            return(new ActionResponse(ActionStatus.Success));
        }