예제 #1
0
        /*----------------------------------------------------------------------------
        *   %%Function: CallService
        *       %%Qualified: TCore.MsalWeb.WebApiInterop.ProcessResponse
        *
        *   Core call service, returning an httpresponse
        *  ----------------------------------------------------------------------------*/
        public async Task <HttpResponseMessage> CallService(string sTarget, bool fRequireAuth)
        {
            string sAccessToken = fRequireAuth ? m_accessTokenProvider.GetAccessToken() : null;

            if (sAccessToken == null && fRequireAuth == true)
            {
                throw new Exception("Authentication failed, no access token");
            }

            HttpClient client = HttpClientCreate(sAccessToken);

            return(await GetServiceResponse(client, $"{m_apiRoot}/{sTarget}"));
        }
예제 #2
0
        public async Task <AccessToken> GetAccessTokenAsync(AccessTokenRequest request)
        {
            //TODO Refactor
            var userRole = await _tokensRepository.GetUserRole(request.RefreshToken);

            if (userRole.IsNullOrEmpty)
            {
                throw new ArgumentException(nameof(request.RefreshToken));
            }


            _claims.Add("role", userRole.ToString());
            var result = _accessTokenProvider.GetAccessToken(DateTime.Now.AddHours(_config.AccessTokenExpMinutes), _claims);

            return(result);
        }
예제 #3
0
        public async Task <AccessToken> GetAccessTokenAsync(AccessTokenRequest request)
        {
            //TODO Implement methods for token validation and getting role - introduce SINGLE RESPONSIBILITY
            var userRole = await _tokensRepository.GetTokenAsync(request.RefreshToken);

            if (userRole.IsNullOrEmpty)
            {
                throw new ArgumentException(nameof(request.RefreshToken));
            }


            _claims.Add("role", userRole.ToString());
            var result = _accessTokenProvider.GetAccessToken(DateTime.Now.AddHours(_config.AccessTokenExpMinutes), _claims);

            return(result);
        }
        // GET: /<controller>/
        public async Task <IActionResult> Index()
        {
            ViewData["AccessToken"] = await accessTokenProvider.GetAccessToken();

            ViewData["CategoryId"] = categoryId;

            // TODO: these coordinates should be resolved from the IP, using one of the publicly available services
            // I chose to keep them hard coded to show the value of the grouped views, for a European use-case
            ViewData["Latitude"]  = 47.384860;
            ViewData["Longitude"] = 8.522303;
            return(View());
        }
예제 #5
0
        protected internal async Task <string> GetAccessToken(string accessToken = null)
        {
            // accessToken or _accessToken or from _tokenProvider or from _accounts
            string token = accessToken
                           ?? _accessToken
                           ?? (_tokenProvider != null
                    ? (await _tokenProvider.GetAccessToken())
                    : null);

            if (string.IsNullOrEmpty(token))
            {
                throw new InvalidOperationException("Access Token is null. Could not get Access Token.");
            }
            return(token);
        }
예제 #6
0
        public async IAsyncEnumerable <CostResultRows> ExecuteBillingQuery(string billingQuery, [EnumeratorCancellation] CancellationToken cancel, BillingQueryClient billingQueryClient)
        {
            var azureManagementUrl =
                $"https://management.azure.com/subscriptions/{_apiSettings.SubscriptionId}/providers/Microsoft.CostManagement/query?api-version=2019-10-01";

            using var httpClient = new HttpClient();

            _logger.LogTrace($"Billing query {billingQuery}");
            var request = new HttpRequestMessage
            {
                RequestUri = new Uri(azureManagementUrl),
                Method     = HttpMethod.Post,
                Content    = new StringContent(
                    billingQuery,
                    Encoding.UTF8,
                    "application/json")
            };

            request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            var accessToken = _accessTokenProvider.GetAccessToken();

            request.Headers.Authorization =
                new AuthenticationHeaderValue("Bearer", accessToken);

            var response = await httpClient.SendAsync(request, cancel);

            if (response.StatusCode != HttpStatusCode.OK)
            {
                throw new Exception($"{response.StatusCode} {await response.Content.ReadAsStringAsync()}");
            }

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

            _logger.LogTrace($"Billing query response result {responseContent}");
            dynamic json = JsonConvert.DeserializeObject(responseContent);

            foreach (var row in json.properties.rows)
            {
                yield return(CostResultRows.Cast(json.properties.columns, row));
            }
        }
예제 #7
0
    /// <summary>
    /// Posts a list of delegation events to the Altinn Bridge API endpoint
    /// </summary>
    /// <param name="delegationEvents">A list of delegation events</param>
    /// <returns>A HTTP response message</returns>
    public async Task <HttpResponseMessage> PostDelegationEventsAsync(List <PlatformDelegationEvent> delegationEvents)
    {
        using var request = new HttpRequestMessage(HttpMethod.Post, DelegationEventEndpoint)
              {
                  Content = JsonContent.Create(delegationEvents),
                  Headers =
                  {
                      Authorization = new AuthenticationHeaderValue("Bearer", await _accessTokenProvider.GetAccessToken())
                  }
              };

        if (_logger.IsEnabled(LogLevel.Debug))
        {
            _logger.LogDebug(
                "BridgeClient posting event list to {url} with token {token} and body {body}",
                request.RequestUri,
                request.Headers.Authorization.ToString(),
                await request.Content.ReadAsStringAsync());
        }

        return(await Client.SendAsync(request));
    }
예제 #8
0
        public static NotificationSendResult Send(Uri channelUri, IAccessTokenProvider accessTokenProvider, string payload, NotificationType type, int? secondsTTL = null, bool? cache = null, bool? requestForStatus = null, string tag = null, NotificationPriority priority = NotificationPriority.Normal, int tokenRetry = 0)
        {
            NotificationSendResult result;
            byte[] payloadBytes;
            HttpWebRequest request = null;

            try
            {
                WnsDiagnostics.TraceVerbose(
                       DiagnosticsConstants.SendingWNSNotificationID,
                       "Sending WNS notification.\r\n\r\n{0}",
                       NotificationRequestStatus(channelUri.ToString(), payload, secondsTTL, cache, requestForStatus, tag, priority, tokenRetry));

                var accessToken = string.Empty;

                try
                {
                    accessToken = accessTokenProvider.GetAccessToken(true);
                }
                catch (WebException e)
                {
                    if (e.Response != null)
                    {
                        var accessTokenError = GetAccessTokenError(e.Response);
                        WnsDiagnostics.TraceError(DiagnosticsConstants.WnsAccessTokenSendResultErrorID, AccessTokenLogMessage(e.Response, accessTokenError));
                        return new WnsAccessTokenSendResult(channelUri, e, accessTokenError);
                    }
                    else
                    {
                        WnsDiagnostics.TraceError(DiagnosticsConstants.ServiceUnavailableErrorID, e.Message);
                        return new NotificationSendResult(channelUri, e.Message, HttpStatusCode.ServiceUnavailable);
                    }
                }

                request = CreateWebRequest(channelUri, accessToken, payload, type, secondsTTL, cache, requestForStatus, tag, priority, out payloadBytes);

                using (Stream requestStream = request.GetRequestStream())
                {
                    requestStream.Write(payloadBytes, 0, payloadBytes.Length);
                }

                var response = (HttpWebResponse)request.GetResponse();
                result = new NotificationSendResult(channelUri, response);

                WnsDiagnostics.TraceInformation(DiagnosticsConstants.SentWNSNotificationID, NotificationLogMessage("Sent WNS notification", result.NotificationStatus.ToString(), result, payload, request, response));
            }
            catch (WebException e)
            {
                if (e.Response != null)
                {
                    string exceptionDetails = e.Response.Headers[WnsHeaders.WWWAuthenticate];
                    if (!string.IsNullOrWhiteSpace(exceptionDetails) && exceptionDetails.Contains("Token expired"))
                    {
                        accessTokenProvider.ResetCachedToken();

                        tokenRetry++;
                        if (tokenRetry <= MaxSendRetries)
                        {
                            result = Send(channelUri, accessTokenProvider, payload, type, secondsTTL, cache, requestForStatus, tag, priority, tokenRetry);
                        }
                        else
                        {
                            result = new NotificationSendResult(channelUri, e);
                        }
                    }
                    else
                    {
                        result = new NotificationSendResult(channelUri, e);
                    }

                    WnsDiagnostics.TraceError(DiagnosticsConstants.WNSNotificationFailureID, NotificationLogMessage("WNS notification failure", e.Message, result, payload, request, e.Response));
                }
                else
                {
                    WnsDiagnostics.TraceError(DiagnosticsConstants.ServiceUnavailableErrorID, e.Message);
                    return new NotificationSendResult(channelUri, e.Message, HttpStatusCode.ServiceUnavailable);
                }
            }
            catch (Exception e)
            {
                result = new NotificationSendResult(channelUri, e);

                WnsDiagnostics.TraceException(DiagnosticsConstants.WNSNotificationFailureID, e, "WNS notification failure: {0}\r\n\r\n{1}", e.Message, result);
            }

            return result;
        }
예제 #9
0
        public static void SendAsynchronously(Uri channelUri, IAccessTokenProvider accessTokenProvider, string payload, Action<NotificationSendResult> sent, Action<NotificationSendResult> error, NotificationType type, int? secondsTTL = null, bool? cache = null, bool? requestForStatus = null, string tag = null, NotificationPriority priority = NotificationPriority.Normal, int tokenRetry = 0)
        {
            byte[] payloadBytes;

            try
            {
                WnsDiagnostics.TraceVerbose(
                    DiagnosticsConstants.SendingWNSNotificationID,
                    "Sending WNS notification.\r\n\r\n{0}",
                    NotificationRequestStatus(channelUri.ToString(), payload, secondsTTL, cache, requestForStatus, tag, priority, tokenRetry));

                var accessToken = string.Empty;

                try
                {
                    accessToken = accessTokenProvider.GetAccessToken(true);
                }
                catch (WebException e)
                {
                    if (e.Response != null)
                    {
                        var accessTokenError = GetAccessTokenError(e.Response);
                        WnsDiagnostics.TraceError(DiagnosticsConstants.WnsAccessTokenSendResultErrorID, AccessTokenLogMessage(e.Response, accessTokenError));
                        error(new WnsAccessTokenSendResult(channelUri, e, accessTokenError));
                    }
                    else
                    {
                        WnsDiagnostics.TraceError(DiagnosticsConstants.ServiceUnavailableErrorID, e.Message);
                        error(new NotificationSendResult(channelUri, e.Message, HttpStatusCode.ServiceUnavailable));
                    }
                }

                if (!string.IsNullOrEmpty(accessToken))
                {
                    var request = CreateWebRequest(channelUri, accessToken, payload, type, secondsTTL, cache, requestForStatus, tag, priority, out payloadBytes);

                    // Get the request stream asynchronously.
                    request.BeginGetRequestStream(
                        requestAsyncResult =>
                        {
                            try
                            {
                                using (Stream requestStream = request.EndGetRequestStream(requestAsyncResult))
                                {
                                    // Start writing the payload to the stream.
                                    requestStream.Write(payloadBytes, 0, payloadBytes.Length);
                                }

                                // Switch to receiving the response from WNS asynchronously.
                                request.BeginGetResponse(
                                    responseAsyncResult =>
                                    {
                                        try
                                        {
                                            using (
                                                var response =
                                                    (HttpWebResponse)request.EndGetResponse(responseAsyncResult))
                                            {
                                                var result = new NotificationSendResult(channelUri, response);
                                                if (result.StatusCode == HttpStatusCode.OK)
                                                {
                                                    WnsDiagnostics.TraceInformation(DiagnosticsConstants.SentWNSNotificationID, NotificationLogMessage("Sent WNS notification", result.NotificationStatus.ToString(), result, payload, request, response));
                                                    sent(result);
                                                }
                                                else
                                                {
                                                    error(result);
                                                    WnsDiagnostics.TraceError(DiagnosticsConstants.WNSNotificationFailureID, "WNS notification failure:\r\n\r\n{0}", result);
                                                }
                                            }
                                        }
                                        catch (WebException e)
                                        {
                                            if (e.Response != null)
                                            {
                                                var result = new NotificationSendResult(channelUri, e);

                                                string exceptionDetails = e.Response.Headers[WnsHeaders.WWWAuthenticate];
                                                if (!string.IsNullOrWhiteSpace(exceptionDetails) &&
                                                    exceptionDetails.Contains("Token expired"))
                                                {
                                                    accessTokenProvider.ResetCachedToken();

                                                    tokenRetry++;
                                                    if (tokenRetry <= MaxSendRetries)
                                                    {
                                                        SendAsynchronously(channelUri, accessTokenProvider, payload, sent, error, type, secondsTTL, cache, requestForStatus, tag, priority, tokenRetry);
                                                    }
                                                    else
                                                    {
                                                        WnsDiagnostics.TraceError(DiagnosticsConstants.WNSNotificationFailureID, NotificationLogMessage("WNS notification failure", e.Message, result, payload, request, e.Response));
                                                        error(result);
                                                    }
                                                }
                                                else
                                                {
                                                    WnsDiagnostics.TraceError(DiagnosticsConstants.WNSNotificationFailureID, NotificationLogMessage("WNS notification failure", e.Message, result, payload, request, e.Response));
                                                    error(result);
                                                }
                                            }
                                            else
                                            {
                                                WnsDiagnostics.TraceError(DiagnosticsConstants.ServiceUnavailableErrorID, e.Message);
                                                error(new NotificationSendResult(channelUri, e.Message, HttpStatusCode.ServiceUnavailable));
                                            }
                                        }
                                        catch (Exception ex3)
                                        {
                                            var result = new NotificationSendResult(channelUri, ex3);
                                            WnsDiagnostics.TraceException(DiagnosticsConstants.GeneralNotificationFailureID, ex3, "WNS notification failure: {0}\r\n\r\n{1}", ex3.Message, result);
                                            error(result);
                                        }
                                    },
                                    null);
                            }
                            catch (Exception ex2)
                            {
                                var result = new NotificationSendResult(channelUri, ex2);
                                WnsDiagnostics.TraceException(DiagnosticsConstants.GeneralNotificationFailureID, ex2, "WNS notification failure: {0}\r\n\r\n{1}", ex2.Message, result);
                                error(result);
                            }
                        },
                        null);
                }
            }
            catch (Exception ex1)
            {
                var result = new NotificationSendResult(channelUri, ex1);
                WnsDiagnostics.TraceException(DiagnosticsConstants.GeneralNotificationFailureID, ex1, "WNS notification failure: {0}\r\n\r\n{1}", ex1.Message, result);
                error(result);
            }
        }
예제 #10
0
 private void RefreshAccessToken()
 {
     _accessToken = _accessTokenProvider.GetAccessToken();
 }