Пример #1
0
        private async Task <AuthenticationHeaderValue> GetAuthenticationHeaderForAppServiceAsync(string resource, CancellationToken cancellationToken = default(CancellationToken))
        {
            var endpoint = Environment.GetEnvironmentVariable("MSI_ENDPOINT") ?? throw new ArgumentNullException("MSI_ENDPOINT");
            var secret   = Environment.GetEnvironmentVariable("MSI_SECRET") ?? throw new ArgumentNullException("MSI_SECRET");
            HttpRequestMessage msiRequest = new HttpRequestMessage(HttpMethod.Get, $"{endpoint}?resource={resource}&api-version={MSITokenProvider.appServiceMsiApiVersion}");

            msiRequest.Headers.Add("Metadata", "true");
            msiRequest.Headers.Add("Secret", secret);

            var    msiResponse = await(new HttpClient()).SendAsync(msiRequest, cancellationToken);
            string content     = await msiResponse.Content.ReadAsStringAsync();

            dynamic loginInfo = JsonConvert.DeserializeObject(content);
            string  tokenType = loginInfo.token_type;

            if (tokenType == null)
            {
                throw MSILoginException.TokenTypeNotFound(content);
            }
            string accessToken = loginInfo.access_token;

            if (accessToken == null)
            {
                throw MSILoginException.AcessTokenNotFound(content);
            }
            return(new AuthenticationHeaderValue(tokenType, accessToken));
        }
Пример #2
0
        public async Task <AuthenticationHeaderValue> GetAuthenticationHeaderAsync(CancellationToken cancellationToken)
        {
            HttpRequestMessage msiRequest = new HttpRequestMessage(HttpMethod.Post, $"http://localhost:{port}/oauth2/token");

            msiRequest.Headers.Add("Metadata", "true");

            IDictionary <string, string> parameters = new Dictionary <string, string>();

            parameters.Add("resource", $"{resource}");
            msiRequest.Content = new FormUrlEncodedContent(parameters);

            var    msiResponse = await(new HttpClient()).SendAsync(msiRequest, cancellationToken);
            string content     = await msiResponse.Content.ReadAsStringAsync();

            dynamic loginInfo = JsonConvert.DeserializeObject(content);
            string  tokenType = loginInfo.token_type;

            if (tokenType == null)
            {
                throw MSILoginException.TokenTypeNotFound(content);
            }
            string accessToken = loginInfo.access_token;

            if (accessToken == null)
            {
                throw MSILoginException.AcessTokenNotFound(content);
            }
            return(new AuthenticationHeaderValue(tokenType, accessToken));
        }
        private async Task <MSIToken> GetTokenFromMSIExtensionAsync(int port, string resource, CancellationToken cancellationToken)
        {
            HttpRequestMessage msiRequest = new HttpRequestMessage(HttpMethod.Post, $"http://localhost:{port}/oauth2/token");

            msiRequest.Headers.Add("Metadata", "true");

            IDictionary <string, string> parameters = new Dictionary <string, string>
            {
                { "resource", $"{resource}" }
            };

            if (this.msiLoginInformation.UserAssignedIdentityObjectId != null)
            {
                parameters.Add("object_id", this.msiLoginInformation.UserAssignedIdentityObjectId);
            }
            else if (this.msiLoginInformation.UserAssignedIdentityClientId != null)
            {
                parameters.Add("client_id", this.msiLoginInformation.UserAssignedIdentityClientId);
            }
            else if (this.msiLoginInformation.UserAssignedIdentityResourceId != null)
            {
                parameters.Add("msi_res_id", this.msiLoginInformation.UserAssignedIdentityResourceId);
            }
            else
            {
                throw new ArgumentException("MSI: UserAssignedIdentityObjectId, UserAssignedIdentityClientId or UserAssignedIdentityResourceId must be set");
            }

            msiRequest.Content = new FormUrlEncodedContent(parameters);

            var    msiResponse = await(new HttpClient()).SendAsync(msiRequest, cancellationToken);
            string content     = await msiResponse.Content.ReadAsStringAsync();

            dynamic loginInfo = JsonConvert.DeserializeObject(content);

            if (loginInfo.access_token == null)
            {
                throw MSILoginException.AcessTokenNotFound(content);
            }
            if (loginInfo.token_type == null)
            {
                throw MSILoginException.TokenTypeNotFound(content);
            }
            //
            MSIToken msiToken = new MSIToken
            {
                AccessToken = loginInfo.access_token,
                TokenType   = loginInfo.token_type
            };

            return(msiToken);
        }
        private async Task <AuthenticationHeaderValue> GetAuthenticationHeaderForVirtualMachineAsync(string resource, CancellationToken cancellationToken = default(CancellationToken))
        {
            int port = msiLoginInformation.Port == null ? 50342 : msiLoginInformation.Port.Value;
            HttpRequestMessage msiRequest = new HttpRequestMessage(HttpMethod.Post, $"http://localhost:{port}/oauth2/token");

            msiRequest.Headers.Add("Metadata", "true");

            IDictionary <string, string> parameters = new Dictionary <string, string>
            {
                { "resource", $"{resource}" }
            };

            if (this.msiLoginInformation.UserAssignedIdentityObjectId != null)
            {
                parameters.Add("object_id", this.msiLoginInformation.UserAssignedIdentityObjectId);
            }
            else if (this.msiLoginInformation.UserAssignedIdentityClientId != null)
            {
                parameters.Add("client_id", this.msiLoginInformation.UserAssignedIdentityClientId);
            }
            else if (this.msiLoginInformation.UserAssignedIdentityResourceId != null)
            {
                parameters.Add("msi_res_id", this.msiLoginInformation.UserAssignedIdentityResourceId);
            }

            msiRequest.Content = new FormUrlEncodedContent(parameters);

            var    msiResponse = await(new HttpClient()).SendAsync(msiRequest, cancellationToken);
            string content     = await msiResponse.Content.ReadAsStringAsync();

            dynamic loginInfo = JsonConvert.DeserializeObject(content);
            string  tokenType = loginInfo.token_type;

            if (tokenType == null)
            {
                throw MSILoginException.TokenTypeNotFound(content);
            }
            string accessToken = loginInfo.access_token;

            if (accessToken == null)
            {
                throw MSILoginException.AcessTokenNotFound(content);
            }
            return(new AuthenticationHeaderValue(tokenType, accessToken));
        }
        private async Task <MSIToken> RetrieveTokenFromIMDSWithRetryAsync(string resource, CancellationToken cancellationToken)
        {
            var uriBuilder = new UriBuilder(MSITokenProvider.imdsEndpoint);
            //
            var query = new Dictionary <string, string>
            {
                ["api-version"] = MSITokenProvider.imdsMsiApiVersion,
                ["resource"]    = resource
            };

            if (this.msiLoginInformation.UserAssignedIdentityObjectId != null)
            {
                query["object_id"] = this.msiLoginInformation.UserAssignedIdentityObjectId;
            }
            else if (this.msiLoginInformation.UserAssignedIdentityClientId != null)
            {
                query["client_id"] = this.msiLoginInformation.UserAssignedIdentityClientId;
            }
            else if (this.msiLoginInformation.UserAssignedIdentityResourceId != null)
            {
                query["msi_res_id"] = this.msiLoginInformation.UserAssignedIdentityResourceId;
            }

            uriBuilder.Query = await new FormUrlEncodedContent(query).ReadAsStringAsync();
            string url = uriBuilder.ToString();
            //
            int retry    = 1;
            int maxRetry = retrySlots.Count;

            //
            while (retry <= maxRetry)
            {
                //
                using (HttpRequestMessage msiRequest = new HttpRequestMessage(HttpMethod.Get, url))
                {
                    msiRequest.Headers.Add("Metadata", "true");
                    using (HttpResponseMessage msiResponse = await(new HttpClient()).SendAsync(msiRequest, cancellationToken))
                    {
                        int statusCode = ((int)msiResponse.StatusCode);
                        if (ShouldRetry(statusCode))
                        {
                            int retryTimeoutInMs = retrySlots[new Random().Next(retry)] * 1000;
                            retryTimeoutInMs = (statusCode == 410 && retryTimeoutInMs < imdsUpgradeTimeInMs) ? imdsUpgradeTimeInMs : retryTimeoutInMs;
                            retry++;
                            if (retry > maxRetry)
                            {
                                break;
                            }
                            else
                            {
                                await SdkContext.DelayProvider.DelayAsync(retryTimeoutInMs, cancellationToken);
                            }
                        }
                        else if (statusCode != 200)
                        {
                            string content = await msiResponse.Content.ReadAsStringAsync();

                            throw new HttpRequestException($"Code: {statusCode} ReasonReasonPhrase: {msiResponse.ReasonPhrase} Body: {content}");
                        }
                        else
                        {
                            string content = await msiResponse.Content.ReadAsStringAsync();

                            dynamic loginInfo = JsonConvert.DeserializeObject(content);
                            if (loginInfo.access_token == null)
                            {
                                throw MSILoginException.AccessTokenNotFound(content);
                            }
                            if (loginInfo.token_type == null)
                            {
                                throw MSILoginException.TokenTypeNotFound(content);
                            }
                            //
                            MSIToken msiToken = new MSIToken
                            {
                                AccessToken = loginInfo.access_token,
                                ExpireOn    = loginInfo.expires_on,
                                TokenType   = loginInfo.token_type
                            };
                            return(msiToken);
                        }
                    }
                }
            }
            throw new MSIMaxRetryReachedException(maxRetry);
        }