public Func <string> GetToken(
            string username,
            string password,
            string authorityUrl,
            string clientName,
            string apiName,
            string apiSecret)
        {
            return(() =>
            {
                if (null != _response)
                {
                    var jwttoken = _jwthandler.ReadToken(_response.AccessToken);

                    if (jwttoken.ValidTo > DateTime.Now)
                    {
                        return _response.AccessToken;
                    }
                }

                var client = new HttpClient();

                var request = new DiscoveryDocumentRequest()
                {
                    Policy =
                    {
                        RequireHttps       = false,
                        RequireKeySet      = false,
                        ValidateEndpoints  = false,
                        ValidateIssuerName = false
                    },
                    Address = authorityUrl
                };

                return RetryPolicies.WaitAndRetryForever <Exception, string>(
                    attemptDelay: TimeSpan.FromMilliseconds(10000),
                    onRetry: (ex, timespan) => this.LogError($"Failed to reach auth server {authorityUrl} - [{ex}]- [{ex.InnerException}]"),
                    doTry: () =>
                {
                    var disco = client.GetDiscoveryDocumentAsync(request).Result;

                    if (disco.IsError)
                    {
                        throw new Exception(disco.Error);
                    }

                    _response = client.RequestPasswordTokenAsync(new PasswordTokenRequest
                    {
                        Address = disco.TokenEndpoint,
                        ClientId = clientName,
                        ClientSecret = apiSecret,
                        Scope = apiName,
                        UserName = username,
                        Password = password
                    }).Result;


                    if (_response.IsError)
                    {
                        throw new Exception("Failed to acquire token", _response.Exception);
                    }

                    return _response.AccessToken;
                }
                    );
            });
        }
Exemplo n.º 2
0
        public Task StartAsync(CancellationToken cancellationToken)
        {
            _cancellationTokens = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);

            var address = _server.Features.Get <IServerAddressesFeature>().Addresses.First();
            var uri     = new Uri(address);

            Uri hostUri = null;

#if DEBUG
            //if run on dev machine, use provided hosturl
            hostUri = uri;
#elif COMPOSE
            //if run via docker-compose, use the container id, resolved by docker cluster dns
            hostUri = new Uri($"{uri.Scheme}://{_serviceConfiguration.Id}:{uri.Port}");
#else
            //if run on kubernetes, use service name which is resolved by the cluster dns
            hostUri = new Uri($"{uri.Scheme}://{_serviceConfiguration.Name}:{uri.Port}");
#endif



            _registrationID = $"{_serviceConfiguration.Id}-{hostUri.Port}";

            var registration = new AgentServiceRegistration()
            {
                ID      = _registrationID,
                Name    = _serviceConfiguration.Name,
                Address = hostUri.Host,
                Port    = hostUri.Port,
                Checks  = new[] {
                    new AgentCheckRegistration()
                    {
                        HTTP          = $"{hostUri.Scheme}://{hostUri.Host}:{hostUri.Port}{ConsulRegistrationConstants.HealthCheckUrl}",
                        Notes         = $"Checks {ConsulRegistrationConstants.HealthCheckUrl} on host",
                        Timeout       = TimeSpan.FromSeconds(3),
                        TLSSkipVerify = true,
                        Interval      = TimeSpan.FromSeconds(10)
                    }
                }
            };

            RetryPolicies.WaitAndRetryForever <Exception>(
                attemptDelay: TimeSpan.FromMilliseconds(_retryTimeout),
                onRetry: (ex, timespan) => this.LogError($"Failed to register {_serviceConfiguration.Id} [{hostUri}] in Consul [{_serviceConfiguration.Consul}] - [{ex.Message}]"),
                doTry: () =>
            {
                this.LogInformation($"Try registering {_serviceConfiguration.Id} [{hostUri}] in Consul [{_serviceConfiguration.Consul}]");

                _consulClient.Agent.ServiceDeregister(registration.ID, _cancellationTokens.Token).Wait();
                _consulClient.Agent.ServiceRegister(registration, _cancellationTokens.Token).Wait();
            }
                );


            this.LogInformation($"Registered {_serviceConfiguration.Id} [{hostUri}] in Consul [{_serviceConfiguration.Consul}]");

            _lifetime.ApplicationStopping.Register(() =>
            {
                _consulClient.Agent.ServiceDeregister(registration.ID).Wait();
            });


            return(Task.CompletedTask);
        }