Beispiel #1
0
        private async Task <SubscriptionInfo[]> GetSubscriptions(TokenCacheInfo cacheInfo)
        {
            using (var client = new HttpClient())
            {
                client.DefaultRequestHeaders.Add("Authorization", cacheInfo.CreateAuthorizationHeader());
                client.DefaultRequestHeaders.Add("User-Agent", Constants.UserAgent.Value);

                var azureEnvironment = this.AzureEnvironments;
                var url = string.Format("{0}/subscriptions?api-version={1}", Constants.CSMUrls[(int)azureEnvironment], Constants.CSMApiVersion);
                using (var response = await client.GetAsync(url))
                {
                    if (response.IsSuccessStatusCode)
                    {
                        var result = await response.Content.ReadAsAsync <ResultOf <SubscriptionInfo> >();

                        return(result.value);
                    }

                    var content = await response.Content.ReadAsStringAsync();

                    if (content.StartsWith("{"))
                    {
                        var error = (JObject)JObject.Parse(content)["error"];
                        if (error != null)
                        {
                            throw new InvalidOperationException(String.Format("GetSubscriptions {0}, {1}", response.StatusCode, error.Value <string>("message")));
                        }
                    }

                    throw new InvalidOperationException(String.Format("GetSubscriptions {0}, {1}", response.StatusCode, await response.Content.ReadAsStringAsync()));
                }
            }
        }
Beispiel #2
0
        private async Task <TenantDetails> GetTenantDetail(TokenCacheInfo cacheInfo, string tenantId)
        {
            if (Constants.InfrastructureTenantIds.Contains(tenantId))
            {
                return(new TenantDetails
                {
                    objectId = tenantId,
                    displayName = "Infrastructure",
                    verifiedDomains = new[]
                    {
                        new VerifiedDomain
                        {
                            name = "live.com",
                            @default = true
                        }
                    }
                });
            }

            using (var client = new HttpClient())
            {
                client.DefaultRequestHeaders.Add("Authorization", cacheInfo.CreateAuthorizationHeader());
                client.DefaultRequestHeaders.Add("User-Agent", Constants.UserAgent.Value);

                var azureEnvironment = this.AzureEnvironments;
                var url = string.Format("{0}/{1}/tenantDetails?api-version={2}", Constants.AADGraphUrls[(int)azureEnvironment], tenantId, Constants.AADGraphApiVersion);
                using (var response = await client.GetAsync(url))
                {
                    if (response.IsSuccessStatusCode)
                    {
                        var result = await response.Content.ReadAsAsync <ResultOf <TenantDetails> >();

                        return(result.value[0]);
                    }

                    var content = await response.Content.ReadAsStringAsync();

                    if (content.StartsWith("{"))
                    {
                        var error = (JObject)JObject.Parse(content)["odata.error"];
                        if (error != null)
                        {
                            throw new InvalidOperationException(String.Format("GetTenantDetail {0}, {1}", response.StatusCode, error["message"].Value <string>("value")));
                        }
                    }

                    throw new InvalidOperationException(String.Format("GetTenantDetail {0}, {1}", response.StatusCode, await response.Content.ReadAsStringAsync()));
                }
            }
        }
Beispiel #3
0
        public static async Task <JObject> HttpGet(Uri uri, TokenCacheInfo cacheInfo)
        {
            using (var client = new HttpClient())
            {
                client.DefaultRequestHeaders.Add("Authorization", cacheInfo.CreateAuthorizationHeader());
                client.DefaultRequestHeaders.Add("User-Agent", Constants.UserAgent.Value);
                client.DefaultRequestHeaders.Add("Accept", Constants.JsonContentType);

                if (Utils.IsRdfe(uri))
                {
                    client.DefaultRequestHeaders.Add("x-ms-version", "2013-10-01");
                }

                if (Utils.IsCSM(uri))
                {
                    var stamp = GetDefaultStamp();
                    if (!String.IsNullOrEmpty(stamp))
                    {
                        client.DefaultRequestHeaders.Add("x-geoproxy-stamp", stamp);
                    }

                    var stampCert = GetDefaultStampCert();
                    if (!String.IsNullOrEmpty(stampCert))
                    {
                        client.DefaultRequestHeaders.Add("x-geoproxy-stampcert", stampCert);
                    }
                }

                var requestId = Guid.NewGuid().ToString();
                client.DefaultRequestHeaders.Add("x-ms-request-id", requestId);
                client.DefaultRequestHeaders.Add("x-ms-client-request-id", requestId);
                client.DefaultRequestHeaders.Add("x-ms-correlation-request-id", requestId);

                using (var response = await client.GetAsync(uri))
                {
                    var content = await response.Content.ReadAsStringAsync();

                    if (!response.IsSuccessStatusCode)
                    {
                        Trace.WriteLine("Status:  " + response.StatusCode);
                        Trace.WriteLine("Content: " + content);
                    }

                    response.EnsureSuccessStatusCode();
                    return(JObject.Parse(content));
                }
            }
        }
Beispiel #4
0
        static async Task <int> HttpInvoke(Uri uri, TokenCacheInfo cacheInfo, string verb, bool verbose, HttpContent content)
        {
            using (var client = new HttpClient(new HttpLoggingHandler(new HttpClientHandler(), verbose)))
            {
                client.DefaultRequestHeaders.Add("Authorization", cacheInfo.CreateAuthorizationHeader());
                client.DefaultRequestHeaders.Add("User-Agent", Constants.UserAgent.Value);
                client.DefaultRequestHeaders.Add("Accept", Constants.JsonContentType);

                if (IsRdfe(uri))
                {
                    client.DefaultRequestHeaders.Add("x-ms-version", "2013-10-01");
                }

                client.DefaultRequestHeaders.Add("x-ms-request-id", Guid.NewGuid().ToString());

                HttpResponseMessage response = null;
                if (String.Equals(verb, "get", StringComparison.OrdinalIgnoreCase))
                {
                    response = await client.GetAsync(uri);
                }
                else if (String.Equals(verb, "delete", StringComparison.OrdinalIgnoreCase))
                {
                    response = await client.DeleteAsync(uri);
                }
                else if (String.Equals(verb, "post", StringComparison.OrdinalIgnoreCase))
                {
                    response = await client.PostAsync(uri, content);
                }
                else if (String.Equals(verb, "put", StringComparison.OrdinalIgnoreCase))
                {
                    response = await client.PutAsync(uri, content);
                }
                else
                {
                    throw new InvalidOperationException(String.Format("Invalid http verb {0}!", verb));
                }

                using (response)
                {
                    if (response.IsSuccessStatusCode)
                    {
                        return(0);
                    }

                    return((-1) * (int)response.StatusCode);
                }
            }
        }
Beispiel #5
0
        public async Task InitializeToken(string subscriptionId = null)
        {
            if (string.IsNullOrEmpty(subscriptionId))
            {
                var match = Regex.Match(_url, ".*\\/subscriptions\\/(.*?)\\/", RegexOptions.IgnoreCase);
                subscriptionId = match.Success ? match.Groups[1].ToString() : string.Empty;
            }

            if (!this._authHelper.IsCacheValid())
            {
                await this._authHelper.AcquireTokens().ConfigureAwait(false);
            }

            TokenCacheInfo cacheInfo = await this._authHelper.GetToken(subscriptionId, Constants.CSMResource).ConfigureAwait(false);

            this._authorizationHeader = cacheInfo.CreateAuthorizationHeader();
        }
Beispiel #6
0
        private async Task <string[]> GetTenantIds(TokenCacheInfo cacheInfo)
        {
            using (var client = new HttpClient())
            {
                client.DefaultRequestHeaders.Add("Authorization", cacheInfo.CreateAuthorizationHeader());
                client.DefaultRequestHeaders.Add("User-Agent", Constants.UserAgent.Value);

                var url = string.Format("{0}/tenants?api-version={1}", ARMConfiguration.ARMUrl, Constants.CSMApiVersion);
                using (var response = await client.GetAsync(url))
                {
                    if (response.IsSuccessStatusCode)
                    {
                        var result = await response.Content.ReadAsAsync <ResultOf <TenantInfo> >();

                        return(result.value.Select(tenant => tenant.tenantId).ToArray());
                    }

                    throw new InvalidOperationException(await response.Content.ReadAsStringAsync());
                }
            }
        }
Beispiel #7
0
        public static async Task <int> HttpInvoke(Uri uri, TokenCacheInfo cacheInfo, string verb, DelegatingHandler handler, HttpContent content, Dictionary <string, List <string> > headers = null)
        {
            using (var client = new HttpClient(handler))
            {
                client.DefaultRequestHeaders.Add("Authorization", cacheInfo.CreateAuthorizationHeader(), headers);
                client.DefaultRequestHeaders.Add("User-Agent", Constants.UserAgent.Value, headers);
                client.DefaultRequestHeaders.Add("Accept", Constants.JsonContentType, headers);

                if (Utils.IsRdfe(uri))
                {
                    client.DefaultRequestHeaders.Add("x-ms-version", "2013-10-01", headers);
                }

                if (Utils.IsCSM(uri))
                {
                    var stamp = GetDefaultStamp();
                    if (!String.IsNullOrEmpty(stamp))
                    {
                        client.DefaultRequestHeaders.Add("x-geoproxy-stamp", stamp, headers);
                    }

                    var stampCert = GetDefaultStampCert();
                    if (!String.IsNullOrEmpty(stampCert))
                    {
                        client.DefaultRequestHeaders.Add("x-geoproxy-stampcert", stampCert, headers);
                    }
                }

                var requestId = Guid.NewGuid().ToString();
                client.DefaultRequestHeaders.Add("x-ms-request-id", requestId);
                client.DefaultRequestHeaders.Add("x-ms-client-request-id", requestId);
                client.DefaultRequestHeaders.Add("x-ms-correlation-request-id", requestId);

                client.DefaultRequestHeaders.AddRemainingHeaders(headers);

                HttpResponseMessage response = null;
                if (String.Equals(verb, "get", StringComparison.OrdinalIgnoreCase))
                {
                    response = await client.GetAsync(uri);
                }
                else if (String.Equals(verb, "delete", StringComparison.OrdinalIgnoreCase))
                {
                    response = await client.DeleteAsync(uri);
                }
                else if (String.Equals(verb, "post", StringComparison.OrdinalIgnoreCase))
                {
                    response = await client.PostAsync(uri, content);
                }
                else if (String.Equals(verb, "put", StringComparison.OrdinalIgnoreCase))
                {
                    response = await client.PutAsync(uri, content);
                }
                else if (String.Equals(verb, "patch", StringComparison.OrdinalIgnoreCase))
                {
                    using (var message = new HttpRequestMessage(new HttpMethod("PATCH"), uri))
                    {
                        message.Content = content;
                        response        = await client.SendAsync(message).ConfigureAwait(false);
                    }
                }
                else
                {
                    throw new InvalidOperationException(String.Format("Invalid http verb {0}!", verb));
                }

                using (response)
                {
                    if (response.IsSuccessStatusCode)
                    {
                        return(0);
                    }

                    return((-1) * (int)response.StatusCode);
                }
            }
        }
Beispiel #8
0
        static int Main(string[] args)
        {
            Utils.SetTraceListener(new ConsoleTraceListener());
            try
            {
                var persistentAuthHelper = new PersistentAuthHelper();
                if (args.Length > 0)
                {
                    var _parameters = new CommandLineParameters(args);
                    var verb        = _parameters.Get(0, "verb");
                    if (String.Equals(verb, "login", StringComparison.OrdinalIgnoreCase))
                    {
                        var env = _parameters.Get(1, requires: false);
                        _parameters.ThrowIfUnknown();

                        persistentAuthHelper.AzureEnvironments = env == null ? AzureEnvironments.Prod :
                                                                 (AzureEnvironments)Enum.Parse(typeof(AzureEnvironments), args[1], ignoreCase: true);
                        persistentAuthHelper.AcquireTokens().Wait();
                        return(0);
                    }
                    else if (String.Equals(verb, "listcache", StringComparison.OrdinalIgnoreCase))
                    {
                        _parameters.ThrowIfUnknown();

                        EnsureTokenCache(persistentAuthHelper);

                        foreach (var line in persistentAuthHelper.DumpTokenCache())
                        {
                            Console.WriteLine(line);
                        }
                        return(0);
                    }
                    else if (String.Equals(verb, "clearcache", StringComparison.OrdinalIgnoreCase))
                    {
                        _parameters.ThrowIfUnknown();

                        persistentAuthHelper.ClearTokenCache();
                        return(0);
                    }
                    else if (String.Equals(verb, "token", StringComparison.OrdinalIgnoreCase))
                    {
                        var tenantId = _parameters.Get(1, requires: false);
                        _parameters.ThrowIfUnknown();

                        EnsureTokenCache(persistentAuthHelper);

                        if (tenantId != null)
                        {
                            if (tenantId.StartsWith("ey"))
                            {
                                DumpClaims(tenantId);
                                return(0);
                            }

                            EnsureGuidFormat(tenantId);
                        }

                        TokenCacheInfo cacheInfo = persistentAuthHelper.GetToken(tenantId, Constants.CSMResource).Result;
                        var            bearer    = cacheInfo.CreateAuthorizationHeader();
                        Clipboard.SetText(bearer);
                        DumpClaims(cacheInfo.AccessToken);
                        Console.WriteLine();
                        Console.WriteLine("Token copied to clipboard successfully.");
                        return(0);
                    }
                    else if (String.Equals(verb, "spn", StringComparison.OrdinalIgnoreCase))
                    {
                        var tenantId = _parameters.Get(1, keyName: "tenant");
                        EnsureGuidFormat(tenantId);

                        var appId = _parameters.Get(2, keyName: "appId");
                        EnsureGuidFormat(appId);

                        var appKey = _parameters.Get(3, keyName: "appKey", requires: false);
                        if (appKey == null)
                        {
                            appKey = PromptForPassword("appKey");
                        }
                        _parameters.ThrowIfUnknown();

                        persistentAuthHelper.AzureEnvironments = AzureEnvironments.Prod;
                        var cacheInfo = persistentAuthHelper.GetTokenBySpn(tenantId, appId, appKey).Result;
                        return(0);
                    }
                    else if (String.Equals(verb, "upn", StringComparison.OrdinalIgnoreCase))
                    {
                        var username = _parameters.Get(1, keyName: "username");
                        var password = _parameters.Get(2, keyName: "password", requires: false);
                        if (password == null)
                        {
                            password = PromptForPassword("password");
                        }
                        _parameters.ThrowIfUnknown();

                        persistentAuthHelper.AzureEnvironments = AzureEnvironments.Prod;
                        var cacheInfo = persistentAuthHelper.GetTokenByUpn(username, password).Result;
                        return(0);
                    }
                    else if (String.Equals(verb, "get", StringComparison.OrdinalIgnoreCase) ||
                             String.Equals(verb, "delete", StringComparison.OrdinalIgnoreCase) ||
                             String.Equals(verb, "put", StringComparison.OrdinalIgnoreCase) ||
                             String.Equals(verb, "post", StringComparison.OrdinalIgnoreCase))
                    {
                        var path    = _parameters.Get(1, keyName: "url");
                        var verbose = _parameters.Get("-verbose", requires: false) != null;
                        if (!verbose)
                        {
                            Trace.Listeners.Clear();
                        }

                        var uri = EnsureAbsoluteUri(path, persistentAuthHelper);
                        if (!persistentAuthHelper.IsCacheValid())
                        {
                            persistentAuthHelper.AzureEnvironments = GetAzureEnvironments(uri);
                            persistentAuthHelper.AcquireTokens().Wait();
                        }

                        var content = ParseHttpContent(verb, _parameters);
                        _parameters.ThrowIfUnknown();

                        var            subscriptionId = GetTenantOrSubscription(uri);
                        TokenCacheInfo cacheInfo      = persistentAuthHelper.GetToken(subscriptionId, null).Result;
                        return(HttpInvoke(uri, cacheInfo, verb, verbose, content).Result);
                    }
                    else
                    {
                        throw new CommandLineException(String.Format("Parameter '{0}' is invalid!", verb));
                    }
                }

                PrintUsage();
                return(1);
            }
            catch (Exception ex)
            {
                DumpException(ex);
                return(-1);
            }
        }
Beispiel #9
0
        public static async Task <int> HttpInvoke(Uri uri, TokenCacheInfo cacheInfo, string verb, DelegatingHandler handler, HttpContent content, Dictionary <string, List <string> > headers = null)
        {
            using (var client = new HttpClient(handler))
            {
                client.DefaultRequestHeaders.Add("User-Agent", Constants.UserAgent.Value, headers);
                client.DefaultRequestHeaders.Add("Accept", Constants.JsonContentType, headers);

                if (Utils.IsCustom(uri))
                {
                    if (Constants.CSMResources.Contains(cacheInfo.Resource))
                    {
                        var jwt = JsonConvert.DeserializeObject <JsonWebToken>(DecodeAccessToken(cacheInfo.AccessToken));

                        if (string.IsNullOrWhiteSpace(cacheInfo.DisplayableId))
                        {
                            client.DefaultRequestHeaders.Add("x-ms-principal-name", cacheInfo.DisplayableId);
                        }

                        client.DefaultRequestHeaders.Add("x-ms-client-tenant-id", cacheInfo.TenantId);
                        client.DefaultRequestHeaders.Add("x-ms-client-object-id", cacheInfo.ObjectId);
                        if (jwt.UniqueName != null)
                        {
                            client.DefaultRequestHeaders.Add("x-ms-client-principal-name", jwt.UniqueName);
                        }

                        var principalId = GetPrincipalId(jwt);
                        if (principalId != null)
                        {
                            client.DefaultRequestHeaders.Add("x-ms-client-principal-id", principalId);
                        }

                        if (headers != null && headers.ContainsKey("usertoken"))
                        {
                            client.DefaultRequestHeaders.Add("x-ms-arm-signed-user-token", headers["usertoken"]);
                            headers.Remove("usertoken");
                        }
                        else
                        {
                            client.DefaultRequestHeaders.Add("x-ms-arm-signed-user-token", cacheInfo.AccessToken);
                        }

                        client.DefaultRequestHeaders.Add("Referer", uri.OriginalString);
                    }
                    else
                    {
                        client.DefaultRequestHeaders.Add("Authorization", "Bearer " + cacheInfo.AccessToken);
                    }
                }
                else
                {
                    client.DefaultRequestHeaders.Add("Authorization", cacheInfo.CreateAuthorizationHeader(), headers);
                }

                if (Utils.IsRdfe(uri))
                {
                    client.DefaultRequestHeaders.Add("x-ms-version", "2013-10-01", headers);
                }

                if (Utils.IsCSM(uri))
                {
                    var stamp = GetDefaultStamp();
                    if (!String.IsNullOrEmpty(stamp))
                    {
                        client.DefaultRequestHeaders.Add("x-geoproxy-stamp", stamp, headers);
                    }

                    var stampCert = GetDefaultStampCert();
                    if (!String.IsNullOrEmpty(stampCert))
                    {
                        client.DefaultRequestHeaders.Add("x-geoproxy-stampcert", stampCert, headers);
                    }
                }

                var requestId = Guid.NewGuid().ToString();
                client.DefaultRequestHeaders.Add("x-ms-request-id", requestId);
                client.DefaultRequestHeaders.Add("x-ms-client-request-id", requestId);
                client.DefaultRequestHeaders.Add("x-ms-correlation-request-id", requestId);

                client.DefaultRequestHeaders.AddRemainingHeaders(headers);

                HttpResponseMessage response = null;
                if (String.Equals(verb, "get", StringComparison.OrdinalIgnoreCase))
                {
                    response = await client.GetAsync(uri);
                }
                else if (String.Equals(verb, "delete", StringComparison.OrdinalIgnoreCase))
                {
                    response = await client.DeleteAsync(uri);
                }
                else if (String.Equals(verb, "post", StringComparison.OrdinalIgnoreCase))
                {
                    response = await client.PostAsync(uri, content);
                }
                else if (String.Equals(verb, "put", StringComparison.OrdinalIgnoreCase))
                {
                    response = await client.PutAsync(uri, content);
                }
                else if (String.Equals(verb, "patch", StringComparison.OrdinalIgnoreCase))
                {
                    using (var message = new HttpRequestMessage(new HttpMethod("PATCH"), uri))
                    {
                        message.Content = content;
                        response        = await client.SendAsync(message).ConfigureAwait(false);
                    }
                }
                else
                {
                    throw new InvalidOperationException(String.Format("Invalid http verb {0}!", verb));
                }

                using (response)
                {
                    if (response.IsSuccessStatusCode)
                    {
                        return(0);
                    }

                    return((-1) * (int)response.StatusCode);
                }
            }
        }