Example #1
0
        public async Task <IActionResult> GetData([FromBody] AccessTokenModel model)
        {
            IAccessToken accessToken = await m_token_service.GetToken(model.Token);

            if (accessToken == null || accessToken.HasExpired)
            {
                return(NotFound());
            }

            return(Ok(new UserDataModel(accessToken.User)));
        }
Example #2
0
        public async Task <string> GetAccessToken()
        {
            IAccessTokenService accessTokenService = _sp.GetService <IAccessTokenService>();
            var result = await accessTokenService.GetToken(Config.AppId, Config.AppSecret);

            return(result.access_token);
        }
        public async Task Test_GetToken()
        {
            IAccessTokenService accessTokenService = _sp.GetService <IAccessTokenService>();
            var result = await accessTokenService.GetToken(Config.AppId, Config.AppSecret);

            Assert.IsNotNull(result);
            Assert.IsNotNull(result.access_token);
        }
Example #4
0
 /// <summary>
 /// Logs in the user. User will be propmpted for credentials.
 /// </summary>
 protected override async Task OnExecuteAsync(CommandLineApplication app)
 {
     try
     {
         _accessTokenService.InvalidateCredentials();
         await _accessTokenService.GetToken(new TokenRequestContext(new[] { "https://management.azure.com/user_impersonation" }));
     }
     catch (Exception e)
     {
         Console.WriteLine(e);
     }
 }
        public async Task <IActionResult> GetActiveOrders([FromBody] AccessTokenModel model)
        {
            IAccessToken accessToken = await m_token_service.GetToken(model.Token);

            if (accessToken == null || accessToken.HasExpired)
            {
                return(BadRequest());
            }

            return(Ok((await m_order_provider.GetActiveOrders(accessToken.User)).Select(x => new OrderModel(accessToken, x)).ToArray()));
        }
Example #6
0
        public async Task <ActionResult> Authenticate([FromBody] UserLoginModel model)
        {
            if (ModelState.IsValid)
            {
                var loginResult = await _userManager.PasswordSignInAsync(model.Username, model.Password, model.Hostname);

                if (!loginResult.Success)
                {
                    return(BadRequest(loginResult.Message));
                }
                var user  = loginResult.User;
                var token = _accessTokenService.GetToken(user.ID, user.Username);
                return(Ok(token));
            }
            return(BadRequest(ModelState));
        }
        /// <inheritdoc/>
        public async Task <DocumentClient> GetDocumentClient(string environment)
        {
            if (_clients.TryGetValue(environment, out DocumentClient documentClient))
            {
                return(documentClient);
            }

            try
            {
                _accountConfig.TryGetValue(environment, out CosmosAccountConfig config);

                ConnectionPolicy connectionPolicy = new ConnectionPolicy
                {
                    ConnectionMode     = ConnectionMode.Gateway,
                    ConnectionProtocol = Protocol.Https,
                };

                string token = await _accessTokenService.GetToken(new TokenRequestContext(new[] { "https://management.azure.com/user_impersonation" }));

                using HttpClient client = new HttpClient();

                string url = $"https://management.azure.com/subscriptions/{config.SubscriptionId}/resourceGroups/{config.ResourceGroup}/providers/Microsoft.DocumentDB/databaseAccounts/{config.AccountName}/listKeys?api-version=2020-04-01";
                client.DefaultRequestHeaders.Add("Authorization", $"Bearer {token}");
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                HttpResponseMessage res = await client.PostAsync(url, null);

                if (res.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    JObject responseObject = JObject.Parse(await res.Content.ReadAsStringAsync());
                    config.PrimaryKey = responseObject["primaryMasterKey"].ToString();
                    _accountConfig[environment].PrimaryKey = config.PrimaryKey;

                    documentClient = new DocumentClient(new Uri($"https://altinn-{environment}-cosmos-db.documents.azure.com:443/"), config.PrimaryKey, connectionPolicy);
                    _clients.Add(environment, documentClient);
                }

                client.Dispose();
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }

            return(documentClient);
        }
        private bool PostAcknowledgment(SendAcknowledgementCommand sendAcknowledgementCommand)
        {
            var token       = accessTokenService.GetToken();
            var accessToken = accessTokenService.ExtractAccessToken(token);

            //add a retry policy here
            using (var httpClient = new HttpClient())
            {
                httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", accessToken);
                var auditApiAcknowledgementControllerUrl = "http://localhost:8094/api/Acknowledgement";
                using (
                    var httpResponse =
                        httpClient.PostAsJsonAsync(new Uri(auditApiAcknowledgementControllerUrl), sendAcknowledgementCommand)
                        .Result)
                {
                    return(httpResponse.IsSuccessStatusCode);
                }
            }
        }
        private bool StartConnectionToHub()
        {
            if (HubConnectionIsAlreadyConnected())
            {
                return(false);
            }

            //add retry policy to get access token
            var tokenContent = accessTokenService.GetToken();
            var accessToken  = accessTokenService.ExtractAccessToken(tokenContent);

            accessTokenExpiryDate = accessTokenService.ExtractAccessTokenExpiryDate(tokenContent);

            var queryString = new Dictionary <string, string> {
                { "bearer_token", HttpUtility.UrlEncode(accessToken) }
            };

            var hubUrl = "http://localhost:8093";

            hubConnection = new HubConnection(hubUrl, queryString)
            {
                TraceLevel           = TraceLevels.All,
                TraceWriter          = new Log4NetTextWriter(new MessagingLogger()),
                DeadlockErrorTimeout = TimeSpan.FromMinutes(5)
            };

            RegisterHubConnectionEvents();

            hubProxy = hubConnection.CreateHubProxy <IBackOfficeHub, IBackOfficeHubClient>(HubName);

            //subscribe before connection is started so that you can make your replay all messages call
            // inside the connection event
            SetUpHubConnectionSubscriptions();

            hubConnection.Start(new ServerSentEventsTransport()).Wait();

            return(true);
        }