Example #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));
        }
        public override async Task <ActionResponse> ExecuteActionAsync(ActionRequest request)
        {
            var    tenant   = request.DataStore.GetFirstValue("SPNTenantId");
            var    clientId = request.DataStore.GetFirstValue("SPNAppId");
            string authBase = string.Format(Constants.AzureAuthUri, tenant);
            string authUri  = AzureTokenUtility.GetAuthUriForServicePrincipal(clientId, authBase, request.Info.WebsiteRootUrl + Constants.WebsiteRedirectPath);

            // hack to allow the SPN to be propagated in AD
            await Task.Delay(50000);

            return(new ActionResponse(ActionStatus.Success, JsonUtility.GetJObjectFromStringValue(authUri.ToString())));
        }
Example #4
0
        public static JObject GetTokenForResourceFromCode(AzureTokenRequestMeta meta, string tenantId, string redirect, string code)
        {
            JObject tokenObj;

            using (HttpClient httpClient = new HttpClient())
            {
                string        tokenUrl = string.Format(Constants.AzureTokenUri, tenantId);
                string        token    = AzureTokenUtility.GetTokenBodyFromCode(code, meta.Resource, redirect, meta.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);
        }
Example #5
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);
        }
Example #6
0
        public override async Task <ActionResponse> ExecuteActionAsync(ActionRequest request)
        {
            var    aadTenant = request.DataStore.GetValue("AADTenant");
            string authBase  = string.Format(Constants.AzureAuthUri, aadTenant);

            string oauthType = (request.DataStore.GetValue("oauthType") ?? string.Empty).ToLowerInvariant();

            switch (oauthType)
            {
            case "keyvault":
                var registrationResponse = RegisterKeyVault(request);
                if (!registrationResponse.IsSuccess)
                {
                    return(registrationResponse);
                }
                break;
            }

            string authUri = AzureTokenUtility.GetAzureAuthUri(oauthType, request.Info.WebsiteRootUrl + Constants.WebsiteRedirectPath, authBase);

            return(new ActionResponse(ActionStatus.Success, JsonUtility.GetJObjectFromStringValue(authUri.ToString())));
        }
        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));
        }
Example #8
0
        public static JObject GetTokenForResourceFromCode(string oauthType, string tenantId, string redirect, string code)
        {
            var meta = AzureTokenUtility.GetMetaFromOAuthType(oauthType);

            return(GetTokenForResourceFromCode(meta, tenantId, redirect, code));
        }