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); }
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; } }
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); }
public override void Close() { _stopRefresh = true; _clientTimerHeartbeat.Dispose(); _stomp.Disconnect(); SecucardTrace.Info("STOMP channel closed."); }
public override void Open() { // TOOD: Connect an start listening Connect(GetToken()); SecucardTrace.Info("STOMP channel opened."); StartSessionRefresh(); }
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; }
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); }
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(); }
/// <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."); }
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); } }
/// <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."); }
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; }
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(); }
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); }
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."); }
protected RestBase(RestConfig restConfig) { RestConfig = restConfig; ServicePointManager.ServerCertificateValidationCallback = AcceptAllCertifications; SecucardTrace.Info(RestConfig.Url); }