Example #1
0
        protected Stream RestGetStream(RestRequest request)
        {
            request.Method = WebRequestMethods.Http.Get;
            var webRequest = (HttpWebRequest)WebRequest.Create(request.Url);

            webRequest.UserAgent = request.UserAgent;

            // Set authorization
            if (!string.IsNullOrWhiteSpace(request.Token))
            {
                webRequest.Headers.Add("Authorization", string.Format("Bearer {0}", request.Token));
            }

            webRequest.Headers.Add(request.Header); // Other header info like user-agent
            RestTrace(webRequest, request.BodyBytes);

            try
            {
                var webResponse = webRequest.GetResponse();
                var respStream  = webResponse.GetResponseStream();
                SecucardTrace.Info("Response stream arrived.");
                return(respStream);
            }
            catch (WebException ex)
            {
                var restException = HandelWebException(ex);
                throw restException;
            }
        }
Example #2
0
        protected string RestDelete(RestRequest request)
        {
            request.Method = "DELETE";

            var webRequest = FactoryWebRequest(request);

            try
            {
                var webResponse = webRequest.GetResponse();
                var respStream  = webResponse.GetResponseStream();

                if (respStream != null)
                {
                    using (var reader = new StreamReader(respStream, Encoding.UTF8))
                    {
                        var ret = reader.ReadToEnd();
                        SecucardTrace.Info("response:\n{0}", ret);
                        return(ret);
                    }
                }
            }
            catch (WebException ex)
            {
                var restException = HandelWebException(ex);
                throw restException;
            }

            return(null);
        }
Example #3
0
        private void OnNewEvent <T>(string target, string type, T serverEvent)
        {
            // check who ist interested in this event
            var eventKey = target + "." + type;
            Dictionary <string, Action <object> > subscribers;

            // Check if there is subscriber to that event. If not create it
            if (!_eventKeySubscriptions.TryGetValue(eventKey, out subscribers))
            {
                return;
            }

            // call registered delegates of services.
            foreach (var ele in subscribers)
            {
                try
                {
                    ele.Value?.Invoke(serverEvent);
                }
                catch (Exception ex)
                {
                    // Don't stop calling all subscribers
                    SecucardTrace.Exception(ex);
                }
            }
        }
Example #4
0
 public override void Close()
 {
     _stopRefresh = true;
     _clientTimerHeartbeat.Dispose();
     _stomp.Disconnect();
     SecucardTrace.Info("STOMP channel closed.");
 }
Example #5
0
 public override void Open()
 {
     // TOOD: Connect an start listening
     Connect(GetToken());
     SecucardTrace.Info("STOMP channel opened.");
     StartSessionRefresh();
 }
Example #6
0
        public string RestPut(RestRequest request)
        {
            request.Method = WebRequestMethods.Http.Put;
            request.PrepareBody();

            var webRequest = FactoryWebRequest(request);

            var reqStream = webRequest.GetRequestStream();

            reqStream.Write(request.BodyBytes, 0, request.BodyBytes.Length);

            try
            {
                var webResponse = webRequest.GetResponse();
                var respStream  = webResponse.GetResponseStream();

                if (respStream != null)
                {
                    using (var reader = new StreamReader(respStream, Encoding.UTF8))
                    {
                        var ret = reader.ReadToEnd();
                        SecucardTrace.Info("response:\n{0}", ret);
                        return(ret);
                    }
                }
            }
            catch (WebException ex)
            {
                var restException = HandelWebException(ex);
                throw restException;
            }

            return(null);
        }
Example #7
0
        private static void RestTrace(HttpWebRequest webRequest, byte[] body)
        {
            var sb = new StringBuilder();

            sb.AppendFormat("request:\n");
            sb.AppendLine();
            sb.AppendFormat("{0}:{1}", webRequest.Method, webRequest.RequestUri.AbsoluteUri);
            sb.AppendLine();
            sb.AppendFormat("Host: {0}", webRequest.Host);
            sb.AppendLine();
            sb.AppendFormat("Type: {0}, Length: {1}", webRequest.ContentType, webRequest.ContentLength);
            sb.AppendLine();
            if (body != null)
            {
                sb.AppendFormat("Body: {0}", Encoding.UTF8.GetString(body));
                sb.AppendLine();
            }

            var frame  = new StackFrame(1);
            var method = frame.GetMethod();
            var type   = method.DeclaringType;
            var name   = string.Empty;

            if (type != null)
            {
                name = type.Name;
            }

            var source = string.Format("{0}.{1}", name, method.Name);

            SecucardTrace.InfoSource(source, sb.ToString().Replace("{", "{{").Replace("}", "}}"));
        }
Example #8
0
        public override ObjectList <T> RequestList <T>(ChannelRequest request)
        {
            var stompRequest  = StompRequest.Create(request, _channelId, _configuration.ReplyTo, _configuration.Destination);
            var returnMessage = SendMessage(stompRequest);

            SecucardTrace.InfoSource("StompChannel.RequestList", returnMessage.EscapeCurlyBracets());
            var response = new Response(returnMessage);

            return(JsonSerializer.DeserializeJson <ObjectList <T> >(response.Data));
        }
Example #9
0
        public StompChannel(StompConfig configuration, ClientContext context)
            : base(context)
        {
            SecucardTrace.Info(string.Format("configuration = '{0}'", configuration));
            _configuration = configuration;

            _channelId = Guid.NewGuid().ToString();
            _stomp     = new StompClient(_configuration);
            _stomp.StompClientFrameArrivedEvent += StompOnStompClientFrameArrivedEvent;
            _stomp.StompClientChangedEvent      += Stomp_StompClientChangedEvent;
        }
Example #10
0
        internal static void Info(string fmt, params object[] param)
        {
            var frame  = new StackFrame(1);
            var method = frame.GetMethod();
            var type   = method.DeclaringType;
            var name   = string.Empty;

            if (type != null)
            {
                name = type.Name;
            }

            var source = string.Format("{0}.{1}", name, method.Name);

            SecucardTrace.InfoSource(source, fmt, param);
        }
Example #11
0
 public static MediaResource Create(string url)
 {
     if (!string.IsNullOrWhiteSpace(url))
     {
         try
         {
             return(new MediaResource(url));
         }
         catch (Exception e)
         {
             SecucardTrace.Error("MediaResource.Create", "Url= {0},{1} ", url, e.Message);
             // ignore here, value could be just an id as well
         }
     }
     return(null);
 }
Example #12
0
        private string SendMessage(StompRequest stompRequest)
        {
            var token = GetToken();

            var frame = new StompFrame(StompCommands.Send);

            frame.Headers.Add(StompHeader.ReplyTo, stompRequest.ReplayTo);
            frame.Headers.Add(StompHeader.ContentType, "application/json");
            frame.Headers.Add(StompHeader.UserId, token);
            frame.Headers.Add(StompHeader.CorrelationId, stompRequest.CorrelationId);
            frame.Headers.Add(StompHeader.Destination, stompRequest.Destination);

            if (!string.IsNullOrWhiteSpace(stompRequest.AppId))
            {
                frame.Headers.Add(StompHeader.AppId, stompRequest.AppId);
            }

            if (!string.IsNullOrWhiteSpace(stompRequest.Body))
            {
                frame.Body = stompRequest.Body;
                frame.Headers.Add(StompHeader.ContentLength, frame.Body.ToUTF8Bytes().Length.ToString());
            }

            // only one send at a time
            lock (_lockSend)
            {
                CheckConnection(token);
                _stomp.SendFrame(frame);
            }

            string message   = null;
            var    endWaitAt = DateTime.Now.AddSeconds(_configuration.MessageTimeoutSec);

            while (message == null && DateTime.Now < endWaitAt)
            {
                SecucardTrace.Info("Waiting for Message with correlationId={0}", stompRequest.CorrelationId);
                message = PullMessage(stompRequest.CorrelationId, _configuration.MaxMessageAgeSec);
                Thread.Sleep(500);
            }
            if (message == null)
            {
                throw new MessageTimeoutException("No answer for " + stompRequest.CorrelationId + " received within " +
                                                  _configuration.MessageTimeoutSec + "s.");
            }

            return(message);
        }
Example #13
0
        private void AwaitReceipt(string rcptId, int?timeoutSec)
        {
            if (timeoutSec == null)
            {
                timeoutSec = _config.MessageTimeoutSec;
            }

            var found       = false;
            var maxWaitTime = DateTime.Now.AddSeconds(timeoutSec.Value);

            while (DateTime.Now <= maxWaitTime && _isConnected && _error == null)
            {
                DateTime rcptDateTime;
                if (_receipts.TryRemove(rcptId, out rcptDateTime))
                {
                    found = true;
                    break;
                }
                Thread.Sleep(200);
            }

            // we can treat error as reason to disconnect
            if (_error != null || !found)
            {
                if (_isConnected)
                {
                    try
                    {
                        Disconnect();
                    }
                    catch (Exception ex)
                    {
                        SecucardTrace.Error("StompClient.AwaitReceipt", ex.Message);
                    }
                }
                if (_error != null)
                {
                    var body    = _error.Body;
                    var headers = _error.Headers;
                    _error = null;
                    throw new StompError(body, headers);
                }
                throw new NoReceiptException("No receipt frame received for sent message.");
            }
            // consider receipt as successful disconnect
        }
Example #14
0
        private void Refresh(Token token, ClientCredentials credentials)
        {
            if (credentials == null)
            {
                throw new System.Exception("Missing credentials");
            }

            SecucardTrace.Info("Refresh token: {0}", credentials);
            var refreshToken = _rest.RefreshToken(token.RefreshToken, credentials.ClientId, credentials.ClientSecret);

            token.AccessToken = refreshToken.AccessToken;
            token.ExpiresIn   = refreshToken.ExpiresIn;
            if (!string.IsNullOrWhiteSpace(refreshToken.RefreshToken))
            {
                token.RefreshToken = refreshToken.RefreshToken;
            }
            token.SetExpireTime();
        }
Example #15
0
        /// <summary>
        ///    Gracefully closes this instance and releases all resources.
        /// </summary>
        public void Close()
        {
            _isConnected = false;
            try
            {
                foreach (var channel in _context.Channels.Values)
                {
                    channel.Close();
                }
            }
            catch (Exception e)
            {
                SecucardTrace.Info(e.ToString());
            }

            OnConnectionStateChangedEvent(new ConnectionStateChangedEventArgs {
                Connected = _isConnected
            });

            SecucardTrace.Info("Secucard connect client closed.");
        }
Example #16
0
 private void CheckConnection(string token)
 {
     // auto-connect or reconnect if token has changed since last connect
     if (_stomp.StompClientStatus != EnumStompClientStatus.Connected ||
         (token != null && !token.Equals(_connectToken)))
     {
         if (_stomp.StompClientStatus == EnumStompClientStatus.Connected)
         {
             SecucardTrace.Info("Reconnect due token change.");
         }
         try
         {
             _stomp.Disconnect();
         }
         catch (Exception e)
         {
             // just log...
             SecucardTrace.Info("Error disconnecting. {0}", e);
         }
         Connect(token);
     }
 }
Example #17
0
        /// <summary>
        ///    Authenticate and open internal resources
        /// </summary>
        public void Open()
        {
            if (_isConnected)
            {
                return;
            }

            try
            {
                var token = _context.TokenManager.GetToken(true);
                SecucardTrace.Info("Auth successfull. Token = {0}", token);
            }
            catch (AuthError)
            {
                Close();
                throw;
            }

            try
            {
                foreach (var channel in _context.Channels.Values)
                {
                    channel.Open();
                }
            }
            catch (Exception)
            {
                Close();
                throw;
            }

            _isConnected = true;
            OnConnectionStateChangedEvent(new ConnectionStateChangedEventArgs {
                Connected = _isConnected
            });

            SecucardTrace.Info("Secucard connect client opened.");
        }
Example #18
0
        private static RestException HandelWebException(WebException ex)
        {
            SecucardTrace.Exception(ex);
            var wr         = ex.Response as HttpWebResponse;
            var dataStream = wr?.GetResponseStream();

            if (dataStream != null)
            {
                var reader        = new StreamReader(dataStream, Encoding.UTF8);
                var restException = new RestException
                {
                    BodyText          = reader.ReadToEnd(),
                    StatusDescription = wr.StatusDescription,
                    StatusCode        = (ex.Status == WebExceptionStatus.ProtocolError) ? ((int?)wr.StatusCode) : null
                };
                SecucardTrace.Exception(restException);
                SecucardTrace.Info(restException.StatusDescription);
                SecucardTrace.Info(restException.BodyText.EscapeCurlyBracets());
                reader.Close();
                return(restException);
            }

            throw ex;
        }
Example #19
0
        private SecucardConnect(ClientConfiguration configuration)
        {
            _configuration = configuration;

            // Setup Trace if directory is there
            if (!string.IsNullOrWhiteSpace(configuration.TraceDir))
            {
                string dir = configuration.TraceDir;
                if (!Path.IsPathRooted(configuration.TraceDir))
                {
                    dir = Path.Combine(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location),
                                       configuration.TraceDir);
                }
                if (!Directory.Exists(Path.GetDirectoryName(dir)))
                {
                    Directory.CreateDirectory(Path.GetDirectoryName(dir));
                }
                var listener = new SecucardTraceListener(dir)
                {
                    Name = "SecucardTraceListener"
                };
                System.Diagnostics.Trace.Listeners.Add(listener);
                SecucardTrace.EmptyLine();
            }

            // Check if Data storage was passed. Otherwise create memory storage
            if (configuration.DataStorage == null)
            {
                configuration.DataStorage = new MemoryDataStorage();
            }

            var context = new ClientContext
            {
                AppId = _configuration.AppId,
            };


            _context = context;

            var authConfig  = _configuration.AuthConfig;
            var stompConfig = _configuration.StompConfig;
            var restConfig  = _configuration.RestConfig;

            SecucardTrace.Info(string.Format("Creating client with configuration: {0}", configuration));

            if (_configuration.ClientAuthDetails == null)
            {
                //TODO:
            }

            context.DefaultChannel = _configuration.DefaultChannel;

            var restChannel = new RestChannel(restConfig, context);

            context.Channels.Add(ChannelOptions.ChannelRest, restChannel);


            if (_configuration.StompEnabled)
            {
                var stompChannel = new StompChannel(stompConfig, context);
                context.Channels.Add(ChannelOptions.ChannelStomp, stompChannel);
                stompChannel.StompEventArrivedEvent += context.EventDispatcher.StompMessageArrivedEvent;
            }

            var restAuth = new RestAuth(authConfig)
            {
                UserAgentInfo =
                    "secucardconnect-net-" + Version + "/net:" + Environment.OSVersion + " " + Environment.Version
            };

            context.TokenManager = new TokenManager(authConfig, _configuration.ClientAuthDetails, restAuth);
            context.TokenManager.TokenManagerStatusUpdateEvent += TokenManagerOnTokenManagerStatusUpdateEvent;


            // Prepare resource downloader
            ResourceDownloader.Get().Cache       = configuration.DataStorage;
            ResourceDownloader.Get().RestChannel = restChannel;


            _serviceDict = ServiceFactory.CreateServices(context);
            WireServiceInstances();
        }
Example #20
0
        public string GetToken(bool allowInteractive)
        {
            var token = GetCurrent();

            var authenticate = false;

            if (token == null)
            {
                // no token, authenticate first
                authenticate = true;
            }
            else if (token.IsExpired())
            {
                // try refresh if just expired, authenticate new if no refresh possible or failed
                SecucardTrace.InfoSource("Token expired: {0} , original:{1}",
                                         token.ExpireTime?.ToString() ?? "null",
                                         token.OrigExpireTime == null ? "null" : token.OrigExpireTime.ToString());
                if (token.RefreshToken == null)
                {
                    SecucardTrace.Info("No token refresh possible, try obtain new.");
                    authenticate = true;
                }
                else
                {
                    try
                    {
                        Refresh(token, ClientAuthDetails.GetClientCredentials());
                        SetCurrentToken(token);
                    }
                    catch (System.Exception ex)
                    {
                        SecucardTrace.Info("Token refresh failed, try obtain new. {0}", ex);
                        authenticate = true;
                    }
                }
            }
            else
            {
                // we should have valid token in cache, no new auth necessary
                if (_config.ExtendExpire)
                {
                    SecucardTrace.Info("Extend token expire time.");
                    token.SetExpireTime();
                    SetCurrentToken(token);
                }
                SecucardTrace.Info("Return current token: {0}", token);
            }

            if (authenticate)
            {
                var credentials = ClientAuthDetails.GetCredentials();

                if (credentials is AnonymousCredentials)
                {
                    return(null);
                }

                // new authentication is needed but only if allowed
                if ((credentials is AppUserCredentials || credentials is DeviceCredentials) && !allowInteractive)
                {
                    throw new AuthFailedException("Invalid access token, please authenticate again.");
                }

                token = Authenticate(credentials);
                token.SetExpireTime();
                token.Id = credentials.Id;
                SetCurrentToken(token);
                SecucardTrace.Info("Return new token: {0}", token);

                OnTokenManagerStatusUpdateEvent(new TokenManagerStatusUpdateEventArgs
                {
                    Status = AuthStatusEnum.Ok,
                    Token  = token
                });
            }

            return(token.AccessToken);
        }
Example #21
0
        private Token Authenticate(OAuthCredentials credentials)
        {
            if (credentials == null)
            {
                throw new AuthFailedException("Missing credentials");
            }

            SecucardTrace.Info("Authenticate credentials: {0}", credentials.ToString());

            var            pollInterval       = 0;
            var            timeout            = DateTime.Now;
            var            devicesCredentials = credentials as DeviceCredentials;
            var            isDeviceAuth       = (devicesCredentials != null);
            DeviceAuthCode codes = null;


            // if DeviceAuth then get codes an pass to app thru event. Further action required by client
            if (isDeviceAuth)
            {
                codes = _rest.GetDeviceAuthCode(devicesCredentials.ClientId, devicesCredentials.ClientSecret, devicesCredentials.DeviceId);
                if (TokenManagerStatusUpdateEvent != null)
                {
                    TokenManagerStatusUpdateEvent.Invoke(this,
                                                         new TokenManagerStatusUpdateEventArgs
                    {
                        DeviceAuthCodes = codes,
                        Status          = AuthStatusEnum.Pending
                    });
                }

                SecucardTrace.Info("Retrieved codes for device auth: {0}, now polling for auth.", codes);

                // set poll timeout, either by config or by expire time of code
                var t = codes.ExpiresIn;
                if (t <= 0 || _config.AuthWaitTimeoutSec < t)
                {
                    t = _config.AuthWaitTimeoutSec;
                }
                timeout = DateTime.Now.AddSeconds(t * 1000);

                pollInterval = codes.Interval;
                if (pollInterval <= 0)
                {
                    pollInterval = 5; // poll default 5s
                }

                devicesCredentials.DeviceCode = codes.DeviceCode;
                devicesCredentials.DeviceId   = null; // device id must be empty for next auth. step!
            }


            do
            {
                Token token = null;
                if (isDeviceAuth)
                {
                    // in case of device auth, check for cancel and delay polling
                    if (CancelAuthFlag)
                    {
                        throw new AuthCanceledException("Authorization canceled by request.");
                    }
                    Thread.Sleep(pollInterval * 1000);

                    token = _rest.ObtainAuthToken(codes.DeviceCode, devicesCredentials.ClientId,
                                                  devicesCredentials.ClientSecret);
                    if (token == null) // auth not completed yet
                    {
                        OnTokenManagerStatusUpdateEvent(new TokenManagerStatusUpdateEventArgs
                        {
                            DeviceAuthCodes = codes,
                            Status          = AuthStatusEnum.Pending
                        });
                    }
                }
                else
                {
                    var clientCredentials = credentials as ClientCredentials;
                    if (clientCredentials != null)
                    {
                        token = _rest.GetToken(clientCredentials.ClientId, clientCredentials.ClientSecret);
                    }
                }

                if (token != null)
                {
                    return(token);
                }
            } while (DateTime.Now < timeout);

            if (isDeviceAuth)
            {
                throw new AuthTimeoutException();
            }

            throw new System.Exception("Unexpected failure of authentication.");
        }
Example #22
0
 protected RestBase(RestConfig restConfig)
 {
     RestConfig = restConfig;
     ServicePointManager.ServerCertificateValidationCallback = AcceptAllCertifications;
     SecucardTrace.Info(RestConfig.Url);
 }