Esempio n. 1
0
        /// <summary>
        /// 执行前
        /// </summary>
        /// <param name="context">上下文</param>
        /// <returns></returns>
        public override Task OnRequestAsync(ApiRequestContext context)
        {
            var parameter = BasicAuth.GetParameter(this.userName, this.password);

            context.HttpContext.RequestMessage.Headers.Authorization = new AuthenticationHeaderValue("Basic", parameter);
            return(Task.CompletedTask);
        }
Esempio n. 2
0
        /// <summary>
        /// Retrieves the appropiate Authorization
        /// </summary>
        /// <param name="auth">Object representing the EventManager.Auth section inside AppSettings.json</param>
        /// <returns>Authorization as an IAuthHandler</returns>
        public static IAuthHandler Create(AuthConfig authConfig)
        {
            IAuthHandler authHandler;

            Enum.TryParse(authConfig.Type, out AuthType authType);
            Log.Debug($"AuthFactory.Create: {authType}");

            switch (authType)
            {
            case AuthType.None:
                authHandler = new NoneAuth(authConfig);
                break;

            case AuthType.Basic:
                authHandler = new BasicAuth(authConfig);
                break;

            case AuthType.OAuthClientPassword:
                authHandler = new OAuthClientPassword(authConfig);
                break;

            case AuthType.CustomAuth:
                authHandler = new CustomAuthAdapter(authConfig);
                break;

            default:
                authHandler = new NoneAuth(authConfig);
                break;
            }

            return(authHandler);
        }
Esempio n. 3
0
    private void TryBasicAuth()
    {
        _basicAuth = TryAuthBy <BasicAuth>().SetLoginButton(loginButton);
        _basicAuth.UserAuthErrorEvent += error => OnUnsuccessfulLogin?.Invoke(error);

        ConfigBaseAuth();
    }
Esempio n. 4
0
        /// <summary>
        /// Initializes a new instance of the <see cref="RESTfulHTTPServer.src.controller.SimpleHTTPServer"/> class.
        /// </summary>
        /// <param name="port">Port.</param>
        /// <param name="routingManager">Routing manager.</param>
        /// <param name="basicAuth">Basic auth.</param>
        public SimpleRESTServer(int port, RoutingManager routingManager, BasicAuth basicAuth)
        {
            _routingManager = routingManager;
            _basicAuth      = basicAuth;

            Initialize(port);
        }
Esempio n. 5
0
        /// <summary>
        /// Construct server with given port.
        /// </summary>
        /// <param name="path">Directory path to serve.</param>
        /// <param name="port">Port of the server.</param>
        public SimpleRESTServer(int port, RoutingManager routingManager)
        {
            _routingManager = routingManager;
            _basicAuth      = null;

            Initialize(port);
        }
Esempio n. 6
0
        /// <summary>
        /// Initializes a new instance of the <see cref="T:plivo.Client.SystemHttpClient"/> class.
        /// </summary>
        /// <param name="basicAuth">Basic auth.</param>
        /// <param name="proxyServerSettings">Proxy settings.</param>
        public SystemHttpClient(BasicAuth basicAuth, Dictionary <string, string> proxyServerSettings)
        {
            HttpClientHandler httpClientHandler = new HttpClientHandler()
            {
                PreAuthenticate       = true,
                UseDefaultCredentials = false
            };

            _client = new System.Net.Http.HttpClient(httpClientHandler);
            var authHeader =
                new AuthenticationHeaderValue("Basic",
                                              Convert.ToBase64String(Encoding.UTF8.GetBytes(
                                                                         $"{basicAuth.AuthId}:{basicAuth.AuthToken}"
                                                                         )
                                                                     )
                                              );

            _client.DefaultRequestHeaders.Authorization = authHeader;
            _client.DefaultRequestHeaders.Add("User-Agent", "plivo-dotnet/" +
                                              Version.SdkVersion);
            _client.BaseAddress = new Uri("https://api.plivo.com/" + Version.ApiVersion + "/");

            _jsonSettings = new JsonSerializerSettings
            {
                ContractResolver  = new PascalCasePropertyNamesContractResolver(),
                NullValueHandling = NullValueHandling.Ignore
            };
        }
Esempio n. 7
0
 /// <summary>
 /// Initializes a new instance of the <see cref="T:plivo.PlivoApi"/> class.
 /// </summary>
 /// <param name="authId">Auth identifier.</param>
 /// <param name="authToken">Auth token.</param>
 /// <param name="proxyAddress">Proxy Address.</param>
 /// <param name="proxyPort">Proxy Port.</param>
 /// <param name="proxyUsername">Proxy Username.</param>
 /// <param name="proxyPassword">Proxy Password.</param>
 public PlivoApi(
     string authId        = null,
     string authToken     = null,
     string proxyAddress  = null,
     string proxyPort     = null,
     string proxyUsername = null,
     string proxyPassword = null
     )
 {
     BasicAuth     = new BasicAuth(authId, authToken);
     Client        = new HttpClient(BasicAuth, proxyAddress, proxyPort, proxyUsername, proxyPassword);
     _account      = new Lazy <AccountInterface>(() => new AccountInterface(Client));
     _subaccount   = new Lazy <SubaccountInterface>(() => new SubaccountInterface(Client));
     _application  = new Lazy <ApplicationInterface>(() => new ApplicationInterface(Client));
     _call         = new Lazy <CallInterface>(() => new CallInterface(Client));
     _conference   = new Lazy <ConferenceInterface>(() => new ConferenceInterface(Client));
     _message      = new Lazy <MessageInterface>(() => new MessageInterface(Client));
     _powerpack    = new Lazy <PowerpackInterface>(() => new PowerpackInterface(Client));
     _media        = new Lazy <MediaInterface>(() => new MediaInterface(Client));
     _endpoint     = new Lazy <EndpointInterface>(() => new EndpointInterface(Client));
     _pricing      = new Lazy <PricingInterface>(() => new PricingInterface(Client));
     _recording    = new Lazy <RecordingInterface>(() => new RecordingInterface(Client));
     _number       = new Lazy <RentedNumberInterface>(() => new RentedNumberInterface(Client));
     _phoneNumber  = new Lazy <PhoneNumberInterface>(() => new PhoneNumberInterface(Client));
     _address      = new Lazy <AddressInterface>(() => new AddressInterface(Client));
     _identity     = new Lazy <IdentityInterface>(() => new IdentityInterface(Client));
     _callFeedback = new Lazy <CallFeedbackInterface>(() => new CallFeedbackInterface(Client));
 }
Esempio n. 8
0
        public static NexmoResponse RedactWithIdAndType(string NEXMO_REDACT_ID, string NEXMO_REDACT_PRODUCT, string NEXMO_REDACT_TYPE)
        {
            var client = BasicAuth.GetClient();
            var result = client.Redact.RedactTransaction(redactRequest: new Redact.RedactRequest(NEXMO_REDACT_ID, NEXMO_REDACT_PRODUCT, NEXMO_REDACT_TYPE));

            return(result);
        }
Esempio n. 9
0
        public override void OnAuthorization(HttpActionContext actionContext)
        {
            if (actionContext.Request.Headers.Authorization == null)
            {
                actionContext.Response = actionContext.Request
                                         .CreateResponse(System.Net.HttpStatusCode.Unauthorized);
            }
            else
            {
                // Will be email:password (base64 encoded)
                var authenticationToken        = actionContext.Request.Headers.Authorization.Parameter;
                var decodedAuthenticationToken = Encoding.UTF8.GetString(Convert.FromBase64String(authenticationToken));

                var userNamePasswordArray = decodedAuthenticationToken.Split(':');
                var username = userNamePasswordArray[0];
                var password = userNamePasswordArray[1];

                if (BasicAuth.LogIn(username, password))
                {
                    Thread.CurrentPrincipal = new GenericPrincipal(new GenericIdentity(username), null);
                }
                else
                {
                    actionContext.Response = actionContext.Request
                                             .CreateResponse(System.Net.HttpStatusCode.Unauthorized);
                }
            }
        }
Esempio n. 10
0
    /// <summary>
    /// Use this for initialization
    /// </summary>
    void Start()
    {
        // Make sure the applications continues to run in the background
        Application.runInBackground = true;

        // ------------------------------
        // Creating a Simple REST server
        // ------------------------------

        // 1. Create the routing table
        // HTTP Type     - URL routing path with variables  - Class and method to be called
        // HTTP Type     - /foo/bar/{variable}              - DelegetorClass.MethodToBeCalled
        RoutingManager routingManager = new RoutingManager();

        routingManager.AddRoute(new Route(Route.Type.GET, "/color/{objname}", "MaterialInvoke.GetColor"));
        routingManager.AddRoute(new Route(Route.Type.POST, "/color/{objname}", "MaterialInvoke.SetColor"));
        routingManager.AddRoute(new Route(Route.Type.DELETE, "/color/{objname}", "MaterialInvoke.DeleteColor"));

        // Starts the Simple REST Server
        // With or without basic authorisation flag
        if (!username.Equals("") && !password.Equals(""))
        {
            RESTfulHTTPServer.src.controller.Logger.Log(TAG, "Create basic auth");
            BasicAuth basicAuth = new BasicAuth(username, password);
            new SimpleRESTServer(port, routingManager, basicAuth);
        }
        else
        {
            new SimpleRESTServer(port, routingManager);
        }
    }
Esempio n. 11
0
        public static bool DeleteApplication(string NEXMO_APPLICATION_ID)
        {
            var client = BasicAuth.GetClient();

            var response = client.ApplicationV2.Delete(NEXMO_APPLICATION_ID);

            return(response);
        }
Esempio n. 12
0
        public static AppResponse GetApplication(string NEXMO_APPLICATION_ID)
        {
            var client = BasicAuth.GetClient();

            var response = client.ApplicationV2.Get(appId: NEXMO_APPLICATION_ID);

            return(response);
        }
Esempio n. 13
0
        public static IList <AppResponse> GetAllApplications()
        {
            var client = BasicAuth.GetClient();

            var response = client.ApplicationV2.List();

            return(response);
        }
Esempio n. 14
0
 public AccessToken(String authId, String authToken, String username)
 {
     BasicAuth = new BasicAuth(authId, authToken);
     if (username.Length == 0)
     {
         throw new PlivoValidationException("username empty");
     }
     Username = username;
 }
Esempio n. 15
0
        public void LogoutTest()
        {
            BasicAuth          target      = new BasicAuth(userAgent, server);                                        // TODO: Initialize to an appropriate value
            string             accessToken = "USYSD1266FEEF8254D936098966E88854CCC_naci-045-033.d.usys.fsglobal.net"; // TODO: Initialize to an appropriate value
            var                expected    = System.Net.HttpStatusCode.OK;                                            // TODO: Initialize to an appropriate value
            BasicAuthEventArgs actual;

            actual = target.Logout(accessToken);
            Assert.AreEqual(expected, actual.StatusCode);
        }
Esempio n. 16
0
        public static NumberVerify.SearchResponse Search(string REQUEST_ID)
        {
            var client = BasicAuth.GetClient();

            var result = client.NumberVerify.Search(new NumberVerify.SearchRequest
            {
                request_id = REQUEST_ID
            });

            return(result);
        }
Esempio n. 17
0
 public UserDataContract Authenticate(Credentials creds)
 {
     if (creds == null && WebOperationContext.Current != null)
     {
         creds = new BasicAuth(WebOperationContext.Current.IncomingRequest.Headers["Authorization"]).Creds;
     }
     using (var dbContext = new UserTokenDbContext())
     {
         return(new DatabaseTokenBuilder(dbContext).Build(creds));
     }
 }
Esempio n. 18
0
        public static Number.SearchResults ListOwnNumbers(string NUMBER_SEARCH_CRITERIA, string NUMBER_SEARCH_PATTERN)
        {
            var client   = BasicAuth.GetClient();
            var response = client.Number.ListOwnNumbers(new Number.SearchRequest()
            {
                pattern        = NUMBER_SEARCH_CRITERIA,
                search_pattern = NUMBER_SEARCH_PATTERN
            });

            return(response);
        }
        private static void ValidateBasicAuthentication()
        {
            var authorization = WebOperationContext.Current?.IncomingRequest.Headers["Authorization"];

            if (string.IsNullOrWhiteSpace(authorization))
            {
                throw new WebFaultException(HttpStatusCode.Forbidden);
            }
            var basicAuth = new BasicAuth(authorization);
            var token     = AuthService.Authenticate(basicAuth.Creds);
        }
Esempio n. 20
0
        public static NumberVerify.ControlResponse Cancel(string REQUEST_ID)
        {
            var client = BasicAuth.GetClient();

            var result = client.NumberVerify.Control(new NumberVerify.ControlRequest
            {
                request_id = REQUEST_ID,
                cmd        = "cancel"
            });

            return(result);
        }
Esempio n. 21
0
        public static NumberVerify.ControlResponse TriggerNext(string REQUEST_ID)
        {
            var client = BasicAuth.GetClient();

            var result = client.NumberVerify.Control(new NumberVerify.ControlRequest
            {
                request_id = REQUEST_ID,
                cmd        = "trigger_next_event"
            });

            return(result);
        }
Esempio n. 22
0
        public static NumberVerify.CheckResponse Check(string CODE, string REQUEST_ID)
        {
            var client = BasicAuth.GetClient();

            var result = client.NumberVerify.Check(new NumberVerify.CheckRequest
            {
                request_id = REQUEST_ID,
                code       = CODE
            });

            return(result);
        }
Esempio n. 23
0
        public async Task OnRequestAsync()
        {
            var apiAction = new ApiActionDescriptor(typeof(ITestApi).GetMethod("PostAsync"));
            var context   = new TestRequestContext(apiAction, "value");

            var basicAuth = new BasicAuth("laojiu", "123456");
            await basicAuth.OnRequestAsync(new ApiParameterContext(context, 0));

            var auth = Convert.ToBase64String(Encoding.ASCII.GetBytes("laojiu:123456"));

            Assert.True(context.HttpContext.RequestMessage.Headers.Authorization.Parameter == auth);
        }
Esempio n. 24
0
        public static SMS.SMSResponse SendSMS(string TO_NUMBER, string NEXMO_BRAND_NAME, string message)
        {
            var client = BasicAuth.GetClient();

            var results = client.SMS.Send(new SMS.SMSRequest
            {
                from = NEXMO_BRAND_NAME,
                to   = TO_NUMBER,
                text = message
            });

            return(results);
        }
Esempio n. 25
0
 public override int GetHashCode()
 {
     unchecked
     {
         int hashCode = base.GetHashCode();
         hashCode = (hashCode * 397) ^ (Url != null ? Url.GetHashCode() : 0);
         hashCode = (hashCode * 397) ^ IgnoreInvalidSSLCertificate.GetHashCode();
         hashCode = (hashCode * 397) ^ (HttpHeaders != null ? HttpHeaders.GetHashCode() : 0);
         hashCode = (hashCode * 397) ^ (BasicAuth != null ? BasicAuth.GetHashCode() : 0);
         hashCode = (hashCode * 397) ^ (Signature != null ? Signature.GetHashCode() : 0);
         return(hashCode);
     }
 }
Esempio n. 26
0
        public static NumberVerify.VerifyResponse StartVerify(string NUMBER)
        {
            var client     = BasicAuth.GetClient();
            var BRAND_NAME = "AcmeInc";

            var result = client.NumberVerify.Verify(new NumberVerify.VerifyRequest
            {
                number = NUMBER,
                brand  = BRAND_NAME
            });

            return(result);
        }
Esempio n. 27
0
        public void LoginAsyncTest()
        {
            this._TestTrigger = new AutoResetEvent(false);

            BasicAuth target   = new BasicAuth(userAgent, server);
            string    username = "";
            string    password = "";

            target.LoginCompleted += new BasicAuth.LoginCompletedHandler(target_LoginCompleted);
            target.LoginAsync(username, password, devKey);

            this._TestTrigger.WaitOne();
        }
Esempio n. 28
0
        public void LogoutAsyncTest()
        {
            this._TestTrigger = new AutoResetEvent(false);

            BasicAuth target = new BasicAuth(userAgent, server); // TODO: Initialize to an appropriate value

            target.LogoutCompleted += new BasicAuth.LogoutCompletedHandler(target_LogoutCompleted);
            string accessToken = "";

            target.LogoutAsync(accessToken);

            this._TestTrigger.WaitOne();
        }
Esempio n. 29
0
        /// <summary>
        /// Initializes a new instance of the <see cref="T:plivo.Client.HttpClient"/> class.
        /// </summary>
        /// <param name="basicAuth">Basic auth.</param>
        /// <param name="proxyAddress">Proxy Address.</param>
        /// <param name="proxyPort">Proxy Port.</param>
        /// <param name="proxyUsername">Proxy Username.</param>
        /// <param name="proxyPassword">Proxy Password.</param>
        /// <param name="baseUri">Switch between environments</param>

        public HttpClient(BasicAuth basicAuth,
                          string proxyAddress  = null, string proxyPort     = null,
                          string proxyUsername = null, string proxyPassword = null, string baseUri = null)
        {
            _client = new SystemHttpClient(basicAuth,
                                           new Dictionary <string, string>
            {
                { "Address", proxyAddress },
                { "Password", proxyPassword },
                { "Username", proxyUsername },
                { "Port", proxyPort }
            }, baseUri);
            _basicAuth = basicAuth;
        }
Esempio n. 30
0
        /// <summary>
        /// Construct server with suitable port.
        /// </summary>
        /// <param name="path">Directory path to serve.</param>
        public SimpleRESTServer(RoutingManager routingManager)
        {
            _routingManager = routingManager;
            _basicAuth      = null;

            TcpListener l = new TcpListener(IPAddress.Loopback, 0);

            l.Start();
            int port = ((IPEndPoint)l.LocalEndpoint).Port;

            l.Stop();

            Initialize(port);
        }