예제 #1
0
파일: Client.cs 프로젝트: milesdream/Rester
        private HttpRequestMessage CreateHttpRequest(Request request, IAuthenticator authenticator)
        {
            var httpRequest = new HttpRequestMessage(request.Method, new Uri(request.Uri));

            if (request.Method == HttpMethod.Post || request.Method == HttpMethod.Put)
            {
                var contentRequest = request as ContentRequest;

                if (contentRequest != null && !string.IsNullOrEmpty(contentRequest.Content) && contentRequest.Encoding != null && !string.IsNullOrEmpty(contentRequest.MediaType))
                {
                    httpRequest.Content = new StringContent(contentRequest.Content, contentRequest.Encoding, contentRequest.MediaType);
                }
            }

            var headers = MergeHeaders(request.Headers, authenticator != null ? authenticator.GetHeaders(request) : null);

            if (headers != null && headers.Count > 0)
            {
                foreach (var header in headers)
                {
                    httpRequest.Headers.Add(header.Key, header.Value);
                }
            }

            return httpRequest;
        }
예제 #2
0
파일: frmMain.cs 프로젝트: festigf/g3
 /// <summary>
 /// Download a file and return a string with its content.
 /// </summary>
 /// <param name="authenticator">
 /// Authenticator responsible for creating authorized web requests.
 /// </param>
 /// <param name="file">Drive File instance.</param>
 /// <returns>File's content if successful, null otherwise.</returns>
 public static System.IO.Stream DownloadFile(
     IAuthenticator authenticator, File file)
 {
     if (!String.IsNullOrEmpty(file.DownloadUrl))
     {
         try
         {
             HttpWebRequest request = (HttpWebRequest)WebRequest.Create(
                 new Uri(file.DownloadUrl));
             authenticator.ApplyAuthenticationToRequest(request);
             HttpWebResponse response = (HttpWebResponse)request.GetResponse();
             if (response.StatusCode == HttpStatusCode.OK)
             {
                 return response.GetResponseStream();
             }
             else
             {
                 Console.WriteLine(
                     "An error occurred: " + response.StatusDescription);
                 return null;
             }
         }
         catch (Exception e)
         {
             Console.WriteLine("An error occurred: " + e.Message);
             return null;
         }
     }
     else
     {
         // The file doesn't have any content stored on Drive.
         return null;
     }
 }
예제 #3
0
        private void Init(IAuthenticator auth, string server)
        {
            Server = server;

            RestClient = new RestClient(Server);
            RestClient.Authenticator = auth;
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="AuthenticationModule" /> class.
 /// </summary>
 /// <param name="authenticator">Used for the actual authentication.</param>
 /// <param name="principalFactory">Used to create the principal that should be used.</param>
 /// <exception cref="System.ArgumentNullException">autheonticator</exception>
 public AuthenticationModule(IAuthenticator authenticator, IPrincipalFactory principalFactory)
 {
     if (authenticator == null) throw new ArgumentNullException("authenticator");
     if (principalFactory == null) throw new ArgumentNullException("principalFactory");
     _authenticator = authenticator;
     _principalFactory = principalFactory;
 }
예제 #5
0
 public RequestRunner(
     ITransmissionSettings transmissionSettings,
     IAuthenticator authenticator)
 {
     this.transmissionSettings = transmissionSettings;
     this.authenticator = authenticator;
 }
	    /// <summary>
        /// Initializes a new instance of the <see cref="DefaultHttpPostClient"/> class.
        /// </summary>
        /// <param name="hostProvider">Instance of IHostProvider. If not specified, default one will be used.</param>
        /// <param name="auth">Instance of IAuthenticator. If not specified request will not use authentication.</param>
        public DefaultHttpPostClient([CanBeNull] IHostProvider hostProvider, [CanBeNull] IAuthenticator auth)
        {
            _hostProvider = hostProvider ?? new DefaultHostsProvider();
            _authenticator = auth;

            Init();
        }
        internal static AuthenticationHeaderValue GetAuthenticationHeaderValue(IAuthenticator authenticator, Uri uri)
        {
            AuthenticationHeaderValue authHeader = null;

            var userInfo = uri != null ? uri.UserInfo : null;
            if (!String.IsNullOrEmpty(userInfo)) 
            {
                authHeader = uri.GetAuthenticationHeader("Basic");
                if (authHeader == null)
                {
                    Log.W(Tag, "Unable to parse user info, not setting credentials");
                }
            } 
            else 
            {
                if (authenticator != null) 
                {
                    userInfo = authenticator.UserInfo;
                    var scheme = authenticator.Scheme;
                    if (userInfo != null && scheme != null)
                    {
                        authHeader = userInfo.AsAuthenticationHeader(scheme);
                    }
                }
            }

            return authHeader;
        }
		public ActionResult Create(UserInputModel userInputModel)
		{
            _repository = new InMemoryRepository();
            _authenticator = new CookieAuthenticator();

			if (_repository.GetAll<User>().Any(x => x.Username == userInputModel.Username))
			{
				ModelState.AddModelError("Username", "Username is already in use");
			}

			if (ModelState.IsValid)
			{
				var user = new User
				{
					Id = Guid.NewGuid(),
					Username = userInputModel.Username,
					Password = HashPassword(userInputModel.Password),
				};

				_repository.SaveOrUpdate(user);

                _authenticator.SetCookie("72201781859E67D4F633C34381EFE4BC928656AEE324A4B00CADA968ACD6CF33047E47479B0B68050FF4A0DB13688B5C78DAFDF53252A94E7F1D7B58A6FFD95D747F3D3AA761DECA7B6358A2E78B85D868833A9420316BDA8A5A0425D543AC1148CB69B902195C20065446A5E5F7A8E4C94A04A22304680E1211F00A12DF5E8777A343D08D0F8C0A3BFC471381E9B070E0F0608ADAEBCA8E233A21251BF57A03B52C1F03B7169CFC7C98216E7217EA649C4EDBD35E07F11A2444D40BE303BFFA28BAA921CDCC298D09A6E0297ED7D6E8");

				return RedirectToAction("Index", "Home");
			}

			return View("New", userInputModel);
		}
예제 #9
0
 public WebDavRequest(string user, string password)
 {
     if (!string.IsNullOrEmpty(user))
         _auth = new BasicAuthenticator(user, password);
     else
         _auth = new NullAuthenticator();
 }
 /// <summary>
 /// Initializes a new instance of the AuthenticatorConfiguration class.
 /// </summary>
 public AuthenticatorConfiguration(string name, IAuthenticator authenticator, IPrincipalBuilder principalBuilder)
 {
     //TODO: 4-8-2011 -- create a FleutnValidator that matches up with this and call it here
     Name = name;
     Authenticator = authenticator;
     PrincipalBuilder = principalBuilder;
 }
        /// <summary>
        /// Initializes a new instance of the Yandex.Money.Api.Sdk.Interfaces.IHttpClient interface.
        /// </summary>
        /// <param name="hostProvider">an instance of IHostProvider implementation</param>
        /// <param name="auth">an instance of IAuthenticator implementation</param>
        public DefaultHttpPostClient(IHostProvider hostProvider, IAuthenticator auth)
        {
            _hostProvider = hostProvider;
            _authenticator = auth;

            Init();
        }
예제 #12
0
 /// <summary>
 /// Initializes a new instance of the <see cref="AccountController"/> class.
 /// </summary>
 /// <param name="userSession">The user session.</param>
 /// <param name="memberService">The user repository.</param>
 /// <param name="authenticator">The authenticator.</param>
 /// <param name="cryptographer">The cryptographer.</param>
 /// <param name="authenticationService"></param>
 public AccountController(IUserSession userSession, IMemberService memberService, IAuthenticator authenticator, ICryptographer cryptographer, IAuthenticationService authenticationService)
     : base(userSession)
 {
     this.memberService = memberService;
     this.authenticator = authenticator;
     this.cryptographer = cryptographer;
     this.authenticationService = authenticationService;
 }
 /// <summary>
 /// Initializes a new instance of the DigestAuthenticatorConfiguration class.
 /// </summary>
 public DigestAuthenticatorConfiguration(string name, IAuthenticator authenticator,
     IPrincipalBuilder principalBuilder, string realm, string privateKey, IPasswordRetriever passwordRetriever)
     : base(name, authenticator, principalBuilder)
 {
     Realm = realm;
     PrivateKey = privateKey;
     PasswordRetriever = passwordRetriever;
 }
예제 #14
0
 public LoginController(IAuthenticator authenticator, IAccountRepository accountRepository, IEventBus eventBus,
                        IFacebookDataRepository facebookDataRepository)
 {
     this.authenticator = authenticator;
     this.accountRepository = accountRepository;
     this.eventBus = eventBus;
     this.facebookDataRepository = facebookDataRepository;
 }
예제 #15
0
 public Client(IAuthenticator authenticator)
 {
     _restClient = new RestClient(StravaClient.ApiBaseUrl) { Authenticator = authenticator };
     Athletes = new AthleteClient(this);
     Activities = new ActivityClient(this);
     Segments = new SegmentClient(this);
     Clubs = new ClubClient(this);
 }
 /// <summary>
 /// Initializes a new instance of the DigestAuthenticatorConfiguration class.
 /// </summary>
 public DigestAuthenticatorConfiguration(string name, IAuthenticator authenticator,
     IPrincipalBuilder principalBuilder, string realm, string privateKey)
     : base(name, authenticator, principalBuilder)
 {
     //TODO: 4-8-2011 cook up an AbstractValidator class that verifies this goop
     Realm = realm;
     PrivateKey = privateKey;
 }
예제 #17
0
        /// <inheritdoc/>
        /// <summary>
        /// Initializes a new instance of the <see cref="AuthClient"/> class and binds it with a network session.
        /// </summary>
        /// <param name="authenticator">The <see cref="IAuthenticator"/> to use for authenticating the user.</param>
        /// <param name="nexus">The <see cref="IAuthToNexusRequestHandler"/> to query for... world stuff.</param>
        /// <param name="serverSession"><inheritdoc/></param>
        /// <param name="packetFactory"><inheritdoc/></param>
        /// <param name="logger"><inheritdoc/></param>
        public AuthClient(IAuthenticator authenticator, IAuthToNexusRequestHandler nexus, IServerSession serverSession, IPacketFactory packetFactory, ILogger logger)
            : base(serverSession, packetFactory, logger)
        {
            this.authenticator = authenticator;
            this.nexus = nexus;

            this.LoginAttempts = 0;
            this.State = AuthClientState.NotLoggedIn;
        }
예제 #18
0
        public UserController(
			IAuthenticator authenticator,
			IDocumentSession session,
			IExecutionContext executionContext)
        {
            _authenticator = authenticator;
            _session = session;
            _executionContext = executionContext;
        }
예제 #19
0
 public RequestRunner(
     ITransmissionSettings transmissionSettings,
     IWebRequestGateway webRequestGateway,
     IAuthenticator authenticator)
 {
     this.transmissionSettings = transmissionSettings;
     this.webRequestGateway = webRequestGateway;
     this.authenticator = authenticator;
 }
예제 #20
0
        public AuthenticationController(IApplicationServices applicationServices, IFormsAuthentication formsAuthentication, IAuthenticator authenticator)
            : base(applicationServices)
        {
            Guard.IsNotNull(formsAuthentication, "formsAuthentication");
            Guard.IsNotNull(authenticator, "authenticator");

            this.formsAuthentication = formsAuthentication;
            this.authenticator = authenticator;
        }
예제 #21
0
 public AuthTicketService(
     [NotNull]HttpContextBase httpContext,
     [NotNull]IAuthTicketFactory ticketFactory,
     [NotNull]IAuthenticator authenticator)
 {
     this.httpContext = httpContext;
     this.ticketFactory = ticketFactory;
     this.authenticator = authenticator;
 }
예제 #22
0
        public DatabaseBackend(IDbConnectionFactory conn_factory, IDbStorageFactory storage_factory, IAuthenticator auth,
		                        OAuthHandler handler)
            : base(conn_factory)
        {
            oauthHandler = handler;
            storageFactory = storage_factory;

            // TODO move this into (Encrypted)DbStorageFactory implementation
            CreateSchema (conn_factory);
        }
예제 #23
0
        public LogWriter(ILogContext context, IAuthenticator authenticator, IClock clock)
        {
            Contract.Requires<ArgumentNullException>(context != null);
            Contract.Requires<ArgumentNullException>(authenticator != null);
            Contract.Requires<ArgumentNullException>(clock != null);

            _context = context;
            _authenticator = authenticator;
            _clock = clock;
        }
        public AuthenticatorController(IAuthenticatorDataRepository repository, IAuthenticator authenticator, IEnrollmentClient enrollClient)
        {
            if (repository == null) throw new ArgumentNullException(nameof(repository));
            if (authenticator == null) throw new ArgumentNullException(nameof(authenticator));
            if (enrollClient == null) throw new ArgumentNullException(nameof(enrollClient));

            _repository = repository;
            _authenticator = authenticator;
            _enrolClient = enrollClient;
        }
예제 #25
0
 public SignInController(IAuthenticator authenticator, ISecurityTokenizer tokenizer, IUserInfo userInfo, IUserPreferences userPreferences, ICache cache, ISessionManager sessionManager, UserManager<BookshelfUser> userManager)
 {
     this._authenticator = authenticator;
     this._tokenizer = tokenizer;
     this._userInfo = userInfo;
     this._userPreferences = userPreferences;
     this._cache = cache;
     this._sessionManager = sessionManager;
     UserManager = userManager;
 }
        public AuthenticationService()
        {
            _ConfigFetcher = DependencyService.Get<IConfigFetcher>();

            _Authenticator = DependencyService.Get<IAuthenticator>();

            _ClientId = _ConfigFetcher.GetAsync("azureActiveDirectoryAuthenticationClientId", true).Result;
            _TenantAuthority = _ConfigFetcher.GetAsync("azureActiveDirectoryAuthenticationTenantAuthorityUrl").Result;
            _ReturnUri = _ConfigFetcher.GetAsync("azureActiveDirectoryAuthenticationReturnUri").Result;
            _ResourceUri = _ConfigFetcher.GetAsync("azureActiveDirectoryAuthenticationResourceUri").Result;
        }
예제 #27
0
 public SecurityController(IAuthenticator authenticator, 
     IActionBus actionBus,
     IEventBus eventBus,
     ISequenceService sequenceService,
     IUserSecurityService userSecurityService) 
     : base(authenticator, actionBus)
 {
     EventBus = eventBus;
     _sequenceService = sequenceService;
     _userSecurityService = userSecurityService;
 }
예제 #28
0
 private void VerifyAuthenticator(IAuthenticator authenticator)
 {
     Mocker.Mock(new Uri("test:///authn/users/admin/authenticate"), "token")
         .Verifier = (WebRequest wr) =>
     {
         var req = wr as WebMocker.MockRequest;
         Assert.AreEqual("POST", wr.Method);
         Assert.AreEqual("api-key", req.Body);
     };
     Assert.AreEqual("token", authenticator.GetToken());
 }
예제 #29
0
        public FileSystemBackend(string data_path, IDbConnectionFactory factory, IAuthenticator auth, OAuthHandler handler, bool reset = false)
        {
            oauthHandler = handler;

            // TODO move this into the oauth stuff
            //DbConfig.CreateSchema ();

            this.notesBasePath = Path.Combine (data_path, "notes");
            if (!Directory.Exists (notesBasePath)) {
                Directory.CreateDirectory (notesBasePath);
            }
        }
예제 #30
0
 public MediaController(CachePolicy cachePolicy, string apiAddress, IAuthenticator authenticator) : base(
         cachePolicy, apiAddress, authenticator)
 {
 }
예제 #31
0
 public HttpClient(string baseUri, ICertificateAuthenticator auth, IConsumer consumer, IUser user)
     : this(baseUri, consumer, user)
 {
     _certAuth = auth;
     _auth     = auth;
 }
예제 #32
0
 public void setAuthenticator(IAuthenticator _authenticator)
 {
     client.Authenticator = _authenticator;
 }
예제 #33
0
 public TokenProvider(IDbContext dbContext, IAuthenticator authenticator)
     : base(dbContext)
 {
     _authenticator = authenticator;
 }
예제 #34
0
 /// <summary>
 /// Standaardconstructor.  <paramref name="veelGebruikt"/> wordt
 /// best toegewezen via inversion of control.
 /// </summary>
 /// <param name="veelGebruikt">Haalt veel gebruikte zaken op uit cache, of indien niet beschikbaar, via
 /// service</param>
 /// <param name="serviceHelper"></param>
 /// <param name="authenticator"></param>
 public GroepController(IVeelGebruikt veelGebruikt, ServiceHelper serviceHelper, IAuthenticator authenticator)
     : base(veelGebruikt, serviceHelper, authenticator)
 {
 }
예제 #35
0
 /// <summary>
 /// Releases all documents on a device configured to release all documents on sign in.
 /// </summary>
 /// <param name="authenticator">The authenticator.</param>
 /// <returns><c>true</c> if the printer release jobs, <c>false</c> otherwise.</returns>
 public abstract bool SignInReleaseAll(IAuthenticator authenticator);
예제 #36
0
 public Authenticator(IAuthenticator tokenAuthenticator, IAuthenticator certificateAuthenticator, ICredentialsCache credentialsCache)
 {
     this.tokenAuthenticator       = Preconditions.CheckNotNull(tokenAuthenticator, nameof(tokenAuthenticator));
     this.certificateAuthenticator = Preconditions.CheckNotNull(certificateAuthenticator, nameof(certificateAuthenticator));
     this.credentialsCache         = Preconditions.CheckNotNull(credentialsCache, nameof(ICredentialsCache));
 }
예제 #37
0
파일: Utils.cs 프로젝트: git-thinh/autoken
        /// <summary>
        /// Update both metadata and content of a file and return the updated file.
        /// </summary>
        public static Google.Apis.Drive.v2.Data.File UpdateResource(Google.Apis.Drive.v2.DriveService service, IAuthenticator auth, String fileId, String newTitle,
                                                                    String newDescription, String newMimeType, String content, bool newRevision)
        {
            // First retrieve the file from the API.
            Google.Apis.Drive.v2.Data.File body = service.Files.Get(fileId).Fetch();

            body.Title       = newTitle;
            body.Description = newDescription;
            body.MimeType    = newMimeType;

            //byte[] byteArray = Encoding.ASCII.GetBytes(content);
            byte[]       byteArray = Encoding.UTF8.GetBytes(content);
            MemoryStream stream    = new MemoryStream(byteArray);

            Google.Apis.Drive.v2.FilesResource.UpdateMediaUpload request = service.Files.Update(body, fileId, stream, newMimeType);
            request.Upload();


            Permission newPermission = new Permission();

            newPermission.Type     = "anyone";
            newPermission.Role     = "reader";
            newPermission.Value    = "";
            newPermission.WithLink = true;
            service.Permissions.Insert(newPermission, fileId).Fetch();


            return(request.ResponseBody);
        }
예제 #38
0
 public EndpointBuilder(string uri, IAuthenticator authn)
 {
     _uri   = uri;
     _authn = authn;
 }
예제 #39
0
 public Configured WithAuthenticator(IAuthenticator authenticator) =>
예제 #40
0
 internal Configured(IHttpClientConfiguration clientConfiguration, ILog log, IAuthenticator authenticator)
 {
     this.log                 = log ?? throw new ArgumentNullException(nameof(log));
     this.authenticator       = authenticator ?? throw new ArgumentNullException(nameof(authenticator));
     this.clientConfiguration = clientConfiguration ?? throw new ArgumentNullException(nameof(clientConfiguration));
 }
예제 #41
0
 public CategoriesEndpointBuilder(string uri, IAuthenticator authn)
     : base(uri, authn)
 {
 }
 public BitbucketDiffClient(IAuthenticator authenticator) : base(authenticator, BASE_URL)
 {
 }
예제 #43
0
 public IRequest WithAuthentication(IAuthenticator authenticator)
 {
     Authenticator = authenticator;
     return(this);
 }
예제 #44
0
        protected override void Load(ContainerBuilder builder)
        {
            // IMetricsListener
            builder.Register(
                c =>
                this.metricsConfig.Enabled
                            ? new MetricsListener(this.metricsConfig.ListenerConfig)
                            : new NullMetricsListener() as IMetricsListener)
            .As <IMetricsListener>()
            .SingleInstance();

            // IMetricsProvider
            builder.Register(
                c =>
                this.metricsConfig.Enabled
                            ? new MetricsProvider(MetricsConstants.EdgeHubMetricPrefix, this.iothubHostName, this.edgeDeviceId)
                            : new NullMetricsProvider() as IMetricsProvider)
            .As <IMetricsProvider>()
            .SingleInstance();

            // ISignatureProvider
            builder.Register(
                c =>
            {
                ISignatureProvider signatureProvider = this.edgeHubConnectionString.Map(
                    cs =>
                {
                    IotHubConnectionStringBuilder csBuilder = IotHubConnectionStringBuilder.Create(cs);
                    return(new SharedAccessKeySignatureProvider(csBuilder.SharedAccessKey) as ISignatureProvider);
                })
                                                       .GetOrElse(
                    () =>
                {
                    string edgeHubGenerationId = this.edgeHubGenerationId.Expect(() => new InvalidOperationException("Generation ID missing"));
                    string workloadUri         = this.workloadUri.Expect(() => new InvalidOperationException("workloadUri is missing"));
                    string workloadApiVersion  = this.workloadApiVersion.Expect(() => new InvalidOperationException("workloadUri version is missing"));
                    return(new HttpHsmSignatureProvider(this.edgeHubModuleId, edgeHubGenerationId, workloadUri, workloadApiVersion, Constants.WorkloadApiVersion) as ISignatureProvider);
                });
                return(signatureProvider);
            })
            .As <ISignatureProvider>()
            .SingleInstance();

            // Detect system environment
            builder.Register(c => new SystemEnvironment())
            .As <ISystemEnvironment>()
            .SingleInstance();

            // DataBase options
            builder.Register(c => new RocksDbOptionsProvider(c.Resolve <ISystemEnvironment>(), this.optimizeForPerformance))
            .As <IRocksDbOptionsProvider>()
            .SingleInstance();

            // IDbStoreProvider
            builder.Register(
                c =>
            {
                var loggerFactory = c.Resolve <ILoggerFactory>();
                ILogger logger    = loggerFactory.CreateLogger(typeof(RoutingModule));

                if (this.usePersistentStorage)
                {
                    // Create partitions for messages and twins
                    var partitionsList = new List <string> {
                        Core.Constants.MessageStorePartitionKey, Core.Constants.TwinStorePartitionKey, Core.Constants.CheckpointStorePartitionKey
                    };
                    try
                    {
                        IDbStoreProvider dbStoreprovider = DbStoreProvider.Create(
                            c.Resolve <IRocksDbOptionsProvider>(),
                            this.storagePath,
                            partitionsList);
                        logger.LogInformation($"Created persistent store at {this.storagePath}");
                        return(dbStoreprovider);
                    }
                    catch (Exception ex) when(!ExceptionEx.IsFatal(ex))
                    {
                        logger.LogError(ex, "Error creating RocksDB store. Falling back to in-memory store.");
                        return(new InMemoryDbStoreProvider());
                    }
                }
                else
                {
                    logger.LogInformation($"Using in-memory store");
                    return(new InMemoryDbStoreProvider());
                }
            })
            .As <IDbStoreProvider>()
            .SingleInstance();

            // IProductInfoStore
            builder.Register(
                c =>
            {
                var storeProvider = c.Resolve <IStoreProvider>();
                IKeyValueStore <string, string> entityStore = storeProvider.GetEntityStore <string, string>("ProductInfo");
                return(new ProductInfoStore(entityStore, this.productInfo));
            })
            .As <IProductInfoStore>()
            .SingleInstance();

            // Task<Option<IEncryptionProvider>>
            builder.Register(
                async c =>
            {
                Option <IEncryptionProvider> encryptionProviderOption = await this.workloadUri
                                                                        .Map(
                    async uri =>
                {
                    var encryptionProvider = await EncryptionProvider.CreateAsync(
                        this.storagePath,
                        new Uri(uri),
                        this.workloadApiVersion.Expect(() => new InvalidOperationException("Missing workload API version")),
                        Constants.WorkloadApiVersion,
                        this.edgeHubModuleId,
                        this.edgeHubGenerationId.Expect(() => new InvalidOperationException("Missing generation ID")),
                        Constants.InitializationVectorFileName) as IEncryptionProvider;
                    return(Option.Some(encryptionProvider));
                })
                                                                        .GetOrElse(() => Task.FromResult(Option.None <IEncryptionProvider>()));
                return(encryptionProviderOption);
            })
            .As <Task <Option <IEncryptionProvider> > >()
            .SingleInstance();

            // IStoreProvider
            builder.Register(c => new StoreProvider(c.Resolve <IDbStoreProvider>()))
            .As <IStoreProvider>()
            .SingleInstance();

            // ITokenProvider
            builder.Register(c => new ClientTokenProvider(c.Resolve <ISignatureProvider>(), this.iothubHostName, this.edgeDeviceId, this.edgeHubModuleId, TimeSpan.FromHours(1)))
            .Named <ITokenProvider>("EdgeHubClientAuthTokenProvider")
            .SingleInstance();

            // ITokenProvider
            builder.Register(
                c =>
            {
                string deviceId = WebUtility.UrlEncode(this.edgeDeviceId);
                string moduleId = WebUtility.UrlEncode(this.edgeHubModuleId);
                return(new ClientTokenProvider(c.Resolve <ISignatureProvider>(), this.iothubHostName, deviceId, moduleId, TimeSpan.FromHours(1)));
            })
            .Named <ITokenProvider>("EdgeHubServiceAuthTokenProvider")
            .SingleInstance();

            builder.Register(
                c =>
            {
                var loggerFactory = c.Resolve <ILoggerFactory>();
                var logger        = loggerFactory.CreateLogger <RoutingModule>();
                return(Proxy.Parse(this.proxy, logger));
            })
            .As <Option <IWebProxy> >()
            .SingleInstance();

            // Task<IDeviceScopeIdentitiesCache>
            builder.Register(
                async c =>
            {
                IDeviceScopeIdentitiesCache deviceScopeIdentitiesCache;
                if (this.authenticationMode == AuthenticationMode.CloudAndScope || this.authenticationMode == AuthenticationMode.Scope)
                {
                    var edgeHubTokenProvider = c.ResolveNamed <ITokenProvider>("EdgeHubServiceAuthTokenProvider");
                    var proxy = c.Resolve <Option <IWebProxy> >();
                    IDeviceScopeApiClient securityScopesApiClient = new DeviceScopeApiClient(this.iothubHostName, this.edgeDeviceId, this.edgeHubModuleId, 10, edgeHubTokenProvider, proxy);
                    IServiceProxy serviceProxy = new ServiceProxy(securityScopesApiClient);
                    IKeyValueStore <string, string> encryptedStore = await GetEncryptedStore(c, "DeviceScopeCache");
                    deviceScopeIdentitiesCache = await DeviceScopeIdentitiesCache.Create(serviceProxy, encryptedStore, this.scopeCacheRefreshRate);
                }
                else
                {
                    deviceScopeIdentitiesCache = new NullDeviceScopeIdentitiesCache();
                }

                return(deviceScopeIdentitiesCache);
            })
            .As <Task <IDeviceScopeIdentitiesCache> >()
            .AutoActivate()
            .SingleInstance();

            // Task<ICredentialsCache>
            builder.Register(
                async c =>
            {
                ICredentialsCache underlyingCredentialsCache;
                if (this.persistTokens)
                {
                    IKeyValueStore <string, string> encryptedStore = await GetEncryptedStore(c, "CredentialsCache");
                    return(new PersistedTokenCredentialsCache(encryptedStore));
                }
                else
                {
                    underlyingCredentialsCache = new NullCredentialsCache();
                }

                ICredentialsCache credentialsCache = new CredentialsCache(underlyingCredentialsCache);
                return(credentialsCache);
            })
            .As <Task <ICredentialsCache> >()
            .SingleInstance();

            // Task<IAuthenticator>
            builder.Register(
                async c =>
            {
                IAuthenticator tokenAuthenticator;
                IAuthenticator certificateAuthenticator;
                IDeviceScopeIdentitiesCache deviceScopeIdentitiesCache;
                var credentialsCacheTask = c.Resolve <Task <ICredentialsCache> >();
                // by default regardless of how the authenticationMode, X.509 certificate validation will always be scoped
                deviceScopeIdentitiesCache = await c.Resolve <Task <IDeviceScopeIdentitiesCache> >();
                certificateAuthenticator   = new DeviceScopeCertificateAuthenticator(deviceScopeIdentitiesCache, new NullAuthenticator(), this.trustBundle, true);
                switch (this.authenticationMode)
                {
                case AuthenticationMode.Cloud:
                    tokenAuthenticator = await this.GetCloudTokenAuthenticator(c);
                    break;

                case AuthenticationMode.Scope:
                    tokenAuthenticator = new DeviceScopeTokenAuthenticator(deviceScopeIdentitiesCache, this.iothubHostName, this.edgeDeviceHostName, new NullAuthenticator(), true, true);
                    break;

                default:
                    IAuthenticator cloudTokenAuthenticator = await this.GetCloudTokenAuthenticator(c);
                    tokenAuthenticator = new DeviceScopeTokenAuthenticator(deviceScopeIdentitiesCache, this.iothubHostName, this.edgeDeviceHostName, cloudTokenAuthenticator, true, true);
                    break;
                }

                ICredentialsCache credentialsCache = await credentialsCacheTask;
                return(new Authenticator(tokenAuthenticator, certificateAuthenticator, credentialsCache) as IAuthenticator);
            })
            .As <Task <IAuthenticator> >()
            .SingleInstance();

            // IClientCredentialsFactory
            builder.Register(c => new ClientCredentialsFactory(c.Resolve <IIdentityProvider>(), this.productInfo))
            .As <IClientCredentialsFactory>()
            .SingleInstance();

            // ConnectionReauthenticator
            builder.Register(
                async c =>
            {
                var edgeHubCredentials               = c.ResolveNamed <IClientCredentials>("EdgeHubCredentials");
                var connectionManagerTask            = c.Resolve <Task <IConnectionManager> >();
                var authenticatorTask                = c.Resolve <Task <IAuthenticator> >();
                var credentialsCacheTask             = c.Resolve <Task <ICredentialsCache> >();
                var deviceScopeIdentitiesCacheTask   = c.Resolve <Task <IDeviceScopeIdentitiesCache> >();
                var deviceConnectivityManager        = c.Resolve <IDeviceConnectivityManager>();
                IConnectionManager connectionManager = await connectionManagerTask;
                IAuthenticator authenticator         = await authenticatorTask;
                ICredentialsCache credentialsCache   = await credentialsCacheTask;
                IDeviceScopeIdentitiesCache deviceScopeIdentitiesCache = await deviceScopeIdentitiesCacheTask;
                var connectionReauthenticator = new ConnectionReauthenticator(
                    connectionManager,
                    authenticator,
                    credentialsCache,
                    deviceScopeIdentitiesCache,
                    TimeSpan.FromMinutes(5),
                    edgeHubCredentials.Identity,
                    deviceConnectivityManager);
                return(connectionReauthenticator);
            })
            .As <Task <ConnectionReauthenticator> >()
            .SingleInstance();

            base.Load(builder);
        }
예제 #45
0
 public XeroCoreApi(string baseUri, IAuthenticator auth, IConsumer consumer, IUser user, IJsonObjectMapper readMapper, IXmlObjectMapper writeMapper, IRateLimiter rateLimiter)
     : base(baseUri, auth, consumer, user, readMapper, writeMapper, rateLimiter)
 {
     Connect();
 }
예제 #46
0
 /// <summary>
 /// Launches The UdocxScan solution with the given authenticator with either eager or lazy authentication.
 /// </summary>
 /// <param name="authenticator">The authenticator.</param>
 /// <param name="authenticationMode">The authentication mode.</param>
 public abstract void Launch(IAuthenticator authenticator, AuthenticationMode authenticationMode);
예제 #47
0
 protected IBMService(string serviceName, IClient httpClient)
 {
     ServiceName   = serviceName;
     Client        = httpClient ?? throw new ArgumentNullException(nameof(httpClient));
     authenticator = new NoAuthAuthenticator();
 }
예제 #48
0
 public AustralianPayroll(string baseUri, IAuthenticator auth, IConsumer consumer, IUser user,
                          IJsonObjectMapper readMapper, IXmlObjectMapper writeMapper)
     : this(baseUri, auth, consumer, user, readMapper, writeMapper, null)
 {
 }
예제 #49
0
        protected override void Load(ContainerBuilder builder)
        {
            // ITransportSettings
            builder.Register(
                async c =>
            {
                IClientCredentialsFactory clientCredentialsProvider = c.Resolve <IClientCredentialsFactory>();
                IAuthenticator authenticator = await c.Resolve <Task <IAuthenticator> >();
                ITransportSettings settings  = new DefaultTransportSettings(this.scheme, HostName, this.port, this.tlsCertificate, this.clientCertAuthAllowed, authenticator, clientCredentialsProvider, this.sslProtocols);
                return(settings);
            })
            .As <Task <ITransportSettings> >()
            .SingleInstance();

            // ITransportListenerProvider
            builder.Register(c => new AmqpTransportListenerProvider())
            .As <ITransportListenerProvider>()
            .SingleInstance();

            // Task<ILinkHandlerProvider>
            builder.Register(
                async c =>
            {
                IMessageConverter <AmqpMessage> messageConverter             = new AmqpMessageConverter();
                IMessageConverter <AmqpMessage> twinMessageConverter         = new AmqpTwinMessageConverter();
                IMessageConverter <AmqpMessage> directMethodMessageConverter = new AmqpDirectMethodMessageConverter();
                var identityProvider = c.Resolve <IIdentityProvider>();
                var productInfoStore = await c.Resolve <Task <IProductInfoStore> >();
                var modelIdStore     = await c.Resolve <Task <IModelIdStore> >();
                ILinkHandlerProvider linkHandlerProvider = new LinkHandlerProvider(messageConverter, twinMessageConverter, directMethodMessageConverter, identityProvider, productInfoStore, modelIdStore);
                return(linkHandlerProvider);
            })
            .As <Task <ILinkHandlerProvider> >()
            .SingleInstance();

            // Task<AmqpProtocolHead>
            builder.Register(
                async c =>
            {
                var identityFactory                    = c.Resolve <IClientCredentialsFactory>();
                var transportSettingsTask              = c.Resolve <Task <ITransportSettings> >();
                var transportListenerProvider          = c.Resolve <ITransportListenerProvider>();
                var linkHandlerProvider                = await c.Resolve <Task <ILinkHandlerProvider> >();
                var credentialsCacheTask               = c.Resolve <Task <ICredentialsCache> >();
                var authenticatorTask                  = c.Resolve <Task <IAuthenticator> >();
                var connectionProviderTask             = c.Resolve <Task <IConnectionProvider> >();
                ICredentialsCache credentialsCache     = await credentialsCacheTask;
                IAuthenticator authenticator           = await authenticatorTask;
                IConnectionProvider connectionProvider = await connectionProviderTask;
                ITransportSettings transportSettings   = await transportSettingsTask;
                var webSocketListenerRegistry          = c.Resolve <IWebSocketListenerRegistry>();
                AmqpSettings amqpSettings              = AmqpSettingsProvider.GetDefaultAmqpSettings(
                    this.iotHubHostName,
                    authenticator,
                    identityFactory,
                    linkHandlerProvider,
                    connectionProvider,
                    credentialsCache);

                return(new AmqpProtocolHead(
                           transportSettings,
                           amqpSettings,
                           transportListenerProvider,
                           webSocketListenerRegistry,
                           authenticator,
                           identityFactory));
            })
            .As <Task <AmqpProtocolHead> >()
            .SingleInstance();

            base.Load(builder);
        }
예제 #50
0
 public XeroCoreApi(string baseUri, IAuthenticator auth, IConsumer consumer, IUser user,
                    IJsonObjectMapper readMapper, IXmlObjectMapper writeMapper)
     : this(baseUri, auth, consumer, user, readMapper, writeMapper, null)
 {
 }
예제 #51
0
 public PMAPIClient(IAuthenticator auth)
 {
     Init(auth, PMAPI_SERVER);
 }
예제 #52
0
 public void SetAuthenticator(IAuthenticator authenticator) => client_.Authenticator = authenticator;
예제 #53
0
 public PMAPIClient(IAuthenticator auth, string server)
 {
     Init(auth, server);
 }
예제 #54
0
파일: Utils.cs 프로젝트: git-thinh/autoken
        /// <summary>
        /// Create a new file and return it.
        /// </summary>
        public static Google.Apis.Drive.v2.Data.File InsertResource(Google.Apis.Drive.v2.DriveService service, IAuthenticator auth, String title,
                                                                    String description, String mimeType, String content)
        {
            // File's metadata.
            Google.Apis.Drive.v2.Data.File body = new Google.Apis.Drive.v2.Data.File();
            body.Title       = title;
            body.Description = description;
            body.MimeType    = mimeType;

            byte[]       byteArray = Encoding.ASCII.GetBytes(content);
            MemoryStream stream    = new MemoryStream(byteArray);

            Google.Apis.Drive.v2.FilesResource.InsertMediaUpload request = service.Files.Insert(body, stream, mimeType);
            request.Upload();

            return(request.ResponseBody);
        }
예제 #55
0
 public Authenticator(IAuthenticator tokenAuthenticator, string edgeDeviceId, ICredentialsCache credentialsCache)
 {
     this.edgeDeviceId       = Preconditions.CheckNonWhiteSpace(edgeDeviceId, nameof(edgeDeviceId));
     this.tokenAuthenticator = Preconditions.CheckNotNull(tokenAuthenticator, nameof(tokenAuthenticator));
     this.credentialsCache   = Preconditions.CheckNotNull(credentialsCache, nameof(ICredentialsCache));
 }
예제 #56
0
 /// <summary>
 /// Constructs a new initializer with default values.
 /// <code>GZipEnabled</code> is set to <code>true</code>, the <code>Serializer</code> is set to
 /// <code>NewtonsoftJsonSerializer</code> and <code>NullAuthenticator.Instance</code> is set as the
 /// initializer's <code>Authenticator</code>
 /// </summary>
 public Initializer()
 {
     GZipEnabled   = true;
     Serializer    = new NewtonsoftJsonSerializer();
     Authenticator = NullAuthenticator.Instance;
 }
예제 #57
0
파일: Utils.cs 프로젝트: git-thinh/autoken
 /// <summary>
 /// Build a Drive service object.
 /// </summary>
 /// <param name="credentials">OAuth 2.0 credentials.</param>
 /// <returns>Drive service object.</returns>
 internal static Google.Apis.Drive.v2.DriveService BuildService(IAuthenticator credentials)
 {
     return(new Google.Apis.Drive.v2.DriveService(credentials));
 }
예제 #58
0
 /// <summary>
 /// Initializes a new instance of the <see cref="RwsConnection"/> class.
 /// </summary>
 /// <param name="domain">The client portion of the Medidata RWS url, e.g. `mediflex`.</param>
 /// <param name="username">The username.</param>
 /// <param name="password">The password.</param>
 /// <param name="virtual_dir">The virtual directory.</param>
 public RwsConnection(string domain, string username, string password, string virtual_dir = "RaveWebServices") : this(domain, virtual_dir)
 {
     this.auth = new HttpBasicAuthenticator(username, password);
 }
예제 #59
0
 /// <summary>
 /// Initializes a new instance of the <see cref="RwsConnection"/> class, using a supplied <see cref="IAuthenticator" />.
 /// </summary>
 /// <param name="domain">The client portion of the Medidata RWS url, e.g. `mediflex`.</param>
 /// <param name="auth">The authenticator.</param>
 /// <param name="virtual_dir">The virtual directory.</param>
 public RwsConnection(string domain, IAuthenticator auth, string virtual_dir = "RaveWebServices") : this(domain, virtual_dir)
 {
     this.auth = auth;
 }
예제 #60
-1
        public WelcomeViewModel(IAuthenticator authenticator, ITokenProvider tokenProvider)
        {
            _authenticator = authenticator;
            _tokenProvider = tokenProvider;

            LoginCommand = new Command(ExecuteLoginCommand);

        }