/// <summary> /// Helper method for creating DirectoryService and adding header /// for subsequent requests for the service. It also adds helper properties for collections of subtypes of DirectoryObject /// such as users, contacts etc. /// </summary> public DirectoryDataService(IAuthToken token, IServiceSettings settings) : this(new Uri(settings.DirectoryServiceURL + @"/" + settings.TenantDomainName)) { this.AuthToken = token; this.Settings = settings; // Register the event handler that adds the headers for HTTP requests including the Authorization header. this.BuildingRequest += new EventHandler<BuildingRequestEventArgs>(OnBuildingRequest); }
public async Task LoginAsync(IConnection connection, string userAgent, IAuthToken authToken) { var serverVersionCollector = new ServerVersionCollector(); connection.Enqueue(new InitMessage(userAgent, authToken.AsDictionary()), serverVersionCollector); await connection.SyncAsync().ConfigureAwait(false); ((ServerInfo)connection.Server).Version = serverVersionCollector.Server; }
private void Init(IAuthToken authToken) { var initCollector = new InitCollector(); Enqueue(new InitMessage(_userAgent, authToken.AsDictionary()), initCollector); Sync(); ((ServerInfo)Server).Version = initCollector.Server; _client.UpdateBoltProtocol(initCollector.Server); }
public async Task LoginAsync(IConnection connection, string userAgent, IAuthToken authToken) { await connection .EnqueueAsync(new InitMessage(userAgent, authToken.AsDictionary()), new V1.InitResponseHandler(connection)) .ConfigureAwait(false); await connection.SyncAsync().ConfigureAwait(false); }
public static IDictionary <string, object> AsDictionary(this IAuthToken authToken) { if (authToken is AuthToken) { return(((AuthToken)authToken).Content); } throw new ClientException($"Unknown authentication token, `{authToken}`. Please use one of the supported " + $"tokens from `{nameof(AuthTokens)}`."); }
public SessionPool(Uri uri, IAuthToken authToken, ILogger logger, Config config, IConnection connection = null) : base(logger) { _uri = uri; _authToken = authToken; _config = config; _connection = connection; _idleSessionPoolSize = config.MaxIdleSessionPoolSize; }
private async Task InitAsync(IAuthToken authToken) { var initCollector = new InitCollector(); Enqueue(new InitMessage(_userAgent, authToken.AsDictionary()), initCollector); await SyncAsync().ConfigureAwait(false); ((ServerInfo)Server).Version = initCollector.Server; _client.UpdateBoltProtocol(initCollector.Server); }
public AuthController( IAuthToken authToken, IAuthService authServices, ISysLoginLogService loginLogService ) { _authToken = authToken; _authService = authServices; _loginLogService = loginLogService; }
public async Task LoginAsync(IConnection connection, string userAgent, IAuthToken authToken) { var collector = new HelloMessageResponseCollector(); connection.Enqueue(new HelloMessage(userAgent, authToken.AsDictionary()), collector); await connection.SyncAsync().ConfigureAwait(false); ((ServerInfo)connection.Server).Version = collector.Server; connection.UpdateId(collector.ConnectionId); }
public Authenticator([NotNull] IAuthToken authToken, [NotNull] IRestClientFactory restClientFactory) { _authToken = authToken; _restClientFactory = restClientFactory; _amagnoUser = ConfigurationManager.AppSettings.Get("amagno_user") ?? throw new InvalidOperationException("Repository is useless without amagno user"); _amagnoPass = ConfigurationManager.AppSettings.Get("amagno_pass") ?? throw new InvalidOperationException("Repository is useless without amagno pass"); }
public void ShouldReturnsAuthTokenByCorrectAuthParameters() { var node = Factory.GetConfigNode("salesforce/clients/client/param[@desc='authenticator'][1]", true); var authenticator = Factory.CreateObject(node, false) as IAuthenticator; IAuthToken authToken = authenticator.Authenticate(); Assert.NotNull(authToken); Assert.IsNotNullOrEmpty(authToken.TokenType); Assert.IsNotNullOrEmpty(authToken.AccessToken); }
private AuthResult <TUser> PrepareAuthResult(TUser user, IAuthToken token, IAuthToken refreshToken) { user.PasswordHash = null; //Do not show password hash to user return(new AuthResult <TUser>(AuthResultType.Success) { Token = token, RefreshToken = refreshToken, User = user }); }
public ConnectionPool(Uri uri, IAuthToken authToken, EncryptionManager encryptionManager, ConnectionPoolSettings connectionPoolSettings, ILogger logger) : base(logger) { _uri = uri; _authToken = authToken; _encryptionManager = encryptionManager; _idleSessionPoolSize = connectionPoolSettings.MaxIdleSessionPoolSize; _logger = logger; }
internal DirectDriver(Uri uri, IAuthToken authToken, EncryptionManager encryptionManager, ConnectionPoolSettings connectionPoolSettings, ILogger logger) { Throw.ArgumentNullException.IfNull(uri, nameof(uri)); Throw.ArgumentNullException.IfNull(authToken, nameof(authToken)); Throw.ArgumentNullException.IfNull(encryptionManager, nameof(encryptionManager)); Throw.ArgumentNullException.IfNull(connectionPoolSettings, nameof(connectionPoolSettings)); Uri = uri; _logger = logger; _connectionPool = new ConnectionPool(uri, authToken, encryptionManager, connectionPoolSettings, _logger); }
public Session(Uri uri, IAuthToken authToken, Config config, IConnection conn = null, Action <Guid> releaseAction = null) : base(config?.Logger) { if (uri != null && uri.Scheme.ToLowerInvariant() != Scheme) { throw new NotSupportedException($"Unsupported protocol: {uri.Scheme}"); } _connection = conn ?? new SocketConnection(uri, authToken, config); _releaseAction = releaseAction ?? (x => {}); _logger = config?.Logger; }
public SocketConnection(ISocketClient socketClient, IAuthToken authToken, ILogger logger, IMessageResponseHandler messageResponseHandler = null) { Throw.ArgumentNullException.IfNull(socketClient, nameof(socketClient)); _messageHandler = messageResponseHandler ?? new MessageResponseHandler(logger); _client = socketClient; Task.Run(() => _client.Start()).Wait(); // add init requestMessage by default Enqueue(new InitMessage("neo4j-dotnet/1.0.0", authToken.AsDictionary())); }
/// <summary> /// Returns a driver for a Neo4j instance with custom configuration. /// </summary> /// <param name="uri"> /// The URI to the Neo4j instance. Should be in the form /// <c>bolt://<server location>:<port></c>. If <c>port</c> is not supplied the default of <c>7687</c> will /// be used.</param> /// <param name="authToken">Authentication to use, <see cref="AuthTokens" />.</param> /// <param name="config"> /// Configuration for the driver instance to use, if <c>null</c> <see cref="Config.DefaultConfig" /> /// is used. /// </param> /// <returns>A new driver to the database instance specified by the <paramref name="uri"/>.</returns> public static IDriver Driver(Uri uri, IAuthToken authToken, Config config) { Throw.ArgumentNullException.IfNull(uri, nameof(uri)); Throw.ArgumentNullException.IfNull(authToken, nameof(authToken)); config = config ?? Config.DefaultConfig; var connectionSettings = new ConnectionSettings(authToken, config); var bufferSettings = new BufferSettings(config); var connectionFactory = new PooledConnectionFactory(connectionSettings, bufferSettings, config.Logger); return(CreateDriver(uri, config, connectionFactory)); }
public SocketConnection(ISocketClient socketClient, IAuthToken authToken, ILogger logger, IMessageResponseHandler messageResponseHandler = null) { Throw.ArgumentNullException.IfNull(socketClient, nameof(socketClient)); _responseHandler = messageResponseHandler ?? new MessageResponseHandler(logger); _client = socketClient; Task.Run(() => _client.Start()).Wait(); // add init requestMessage by default Init(authToken); }
protected StressTest(ITestOutputHelper output, Uri databaseUri, IAuthToken authToken) { _output = output ?? throw new ArgumentNullException(nameof(output)); _databaseUri = databaseUri; _authToken = authToken; _driver = GraphDatabase.Driver(databaseUri, authToken, o => o .WithLogger(new StressTestLogger(_output, LoggingEnabled)) .WithMaxConnectionPoolSize(100).WithConnectionAcquisitionTimeout(TimeSpan.FromMinutes(1))); CleanupDatabase(); }
public InternalDriverProvider(string uri, IAuthToken authToken, Config config, N4pperManager manager) : base(manager) { if (string.IsNullOrEmpty(uri)) { throw new ArgumentNullException(nameof(uri)); } _uri = uri; _authToken = authToken ?? AuthTokens.None; _config = config ?? new Config(); }
/// <summary> /// Returns a driver for a Neo4j instance with custom configuration. /// </summary> /// <param name="uri"> /// The URI to the Neo4j instance. Should be in the form /// <c>neo4j://<server location>:<port></c>. /// If <c>port</c> is not supplied the default of <c>7687</c> will be used.</param> /// <param name="authToken">Authentication to use, <see cref="AuthTokens" />.</param> /// <param name="action"> /// Defines how to build a driver configuration <see cref="Config"/> using <see cref="ConfigBuilder"/>. /// If set to <c>null</c>, then no modification will be carried out on the build. /// As a result, a default config with default settings will be used <see cref="Config" /> when creating the new driver. /// </param> /// <returns>A new driver to the database instance specified by the <paramref name="uri"/>.</returns> public static IDriver Driver(Uri uri, IAuthToken authToken, Action <ConfigBuilder> action) { Throw.ArgumentNullException.IfNull(uri, nameof(uri)); Throw.ArgumentNullException.IfNull(authToken, nameof(authToken)); var config = ConfigBuilders.BuildConfig(action); var connectionSettings = new ConnectionSettings(uri, authToken, config); var bufferSettings = new BufferSettings(config); var connectionFactory = new PooledConnectionFactory(connectionSettings, bufferSettings, config.Logger); return(CreateDriver(uri, config, connectionFactory)); }
/// <summary> /// Validate refresh token /// </summary> /// <returns>if token is valid - (true, null), otherwise (false, [reason])</returns> private async Task <bool> ValidaateRefreshToken(string userName, string sessionId, string refreshTokenToVerify) { IAuthToken savedRefreshToken = await _userStore.GetRefreshToken(userName, sessionId); //retrieve the refresh token from data storage if (savedRefreshToken == null || savedRefreshToken.Token != refreshTokenToVerify || savedRefreshToken.ExpireDate < DateTime.UtcNow) { return(false); } return(true); }
public void Authenticate(IConnection connection, string userAgent, IAuthToken authToken) { var initCollector = new InitCollector(); connection.Enqueue(new InitMessage(userAgent, authToken.AsDictionary()), initCollector); connection.Sync(); ((ServerInfo)connection.Server).Version = initCollector.Server; if (!(ServerVersion.Version(initCollector.Server) >= ServerVersion.V3_2_0)) { connection.ResetMessageReaderAndWriterForServerV3_1(); } }
public GraphRepository(GraphDbSettings graphDbSettings, ICypherBuilderFactory cypherBuilderFactory, IDriver driver = null) { Guard.ArgumentNotNull(graphDbSettings, nameof(graphDbSettings)); Guard.IsNullOrWhiteSpace(graphDbSettings.Url, nameof(graphDbSettings.Url)); Guard.IsNullOrWhiteSpace(graphDbSettings.Username, nameof(graphDbSettings.Username)); Guard.IsNullOrWhiteSpace(graphDbSettings.Password, nameof(graphDbSettings.Password)); Guard.ArgumentNotNull(cypherBuilderFactory, nameof(cypherBuilderFactory)); IAuthToken authToken = AuthTokens.Basic(graphDbSettings.Username, graphDbSettings.Password); _driver = driver ?? GraphDatabase.Driver(graphDbSettings.Url, authToken); _cypherBuilderFactory = cypherBuilderFactory; }
public SocketConnection(Uri uri, ConnectionSettings connectionSettings, BufferSettings bufferSettings, ILogger logger = null) { _idPrefix = $"conn-{uri.Host}:{uri.Port}-"; _id = $"{_idPrefix}{UniqueIdGenerator.GetId()}"; _logger = new PrefixLogger(logger, FormatPrefix(_id)); _client = new SocketClient(uri, connectionSettings.SocketSettings, bufferSettings, _logger); _authToken = connectionSettings.AuthToken; _userAgent = connectionSettings.UserAgent; Server = new ServerInfo(uri); _responsePipeline = new ResponsePipeline(_logger); }
public SocketConnection(Uri uri, ConnectionSettings connectionSettings, BufferSettings bufferSettings, IConnectionListener metricsListener = null, IDriverLogger logger = null) { _id = $"conn-{UniqueIdGenerator.GetId()}"; _logger = new PrefixLogger(logger, FormatPrefix(_id)); _client = new SocketClient(uri, connectionSettings.SocketSettings, bufferSettings, metricsListener, _logger); _authToken = connectionSettings.AuthToken; _userAgent = connectionSettings.UserAgent; Server = new ServerInfo(uri); _responseHandler = new MessageResponseHandler(_logger); }
protected async override Task <HttpResponseMessage> SendAsync(HttpRequestMessage Request, CancellationToken CancelToken) { if (null != Request.Headers.Authorization) { if (Request.Headers.Authorization.Scheme.ToUpper() == "FORCE") { Guid Token; if (!Guid.TryParse(Request.Headers.Authorization.Parameter, out Token)) { return(new HttpResponseMessage(System.Net.HttpStatusCode.Unauthorized)); } AuthTokenDataStore Tokens = new AuthTokenDataStore(); await Tokens.Delete(0); IAuthToken ValidToken = (await Tokens.Get("Token", Token)).FirstOrDefault(); if (null == ValidToken) { return(new HttpResponseMessage(System.Net.HttpStatusCode.Unauthorized)); } UserDataStore Users = new UserDataStore(); IUser User = await Users.Get(ValidToken.UserId); if (null == User) { return(new HttpResponseMessage(System.Net.HttpStatusCode.Unauthorized)); } Thread.CurrentPrincipal = new GenericPrincipal(new DevSpaceIdentity(User), null); Request.GetRequestContext().Principal = Thread.CurrentPrincipal; await Tokens.Update(ValidToken.UpdateExpires(DateTime.UtcNow.AddMinutes(-1))); // Complete the request. We'll set the login cookie on the way out HttpResponseMessage Response = await base.SendAsync(Request, CancelToken); CookieHeaderValue SessionCookie = new CookieHeaderValue("SessionToken", (await Users.CreateSession((Thread.CurrentPrincipal.Identity as DevSpaceIdentity).Identity)).SessionToken.ToString()); #if DEBUG == false SessionCookie.Secure = true; #endif SessionCookie.HttpOnly = true; Response.Headers.AddCookies(new CookieHeaderValue[] { SessionCookie }); return(Response); } } return(await base.SendAsync(Request, CancelToken)); }
internal Driver(Uri uri, IAuthToken authToken, Config config) { Throw.ArgumentNullException.IfNull(uri, nameof(uri)); Throw.ArgumentNullException.IfNull(authToken, nameof(authToken)); Throw.ArgumentNullException.IfNull(config, nameof(config)); if (uri.Port == -1) { var builder = new UriBuilder(uri.Scheme, uri.Host, 7687); uri = builder.Uri; } Uri = uri; _sessionPool = new SessionPool(uri, authToken, config?.Logger, config); }
public SingleInstance(string httpUri, string boltUri, string homePath, string password) { HttpUri = new Uri(httpUri); BoltUri = new Uri(boltUri); BoltRoutingUri = new Uri(BoltRoutingScheme + $"{BoltUri.Host}:{BoltUri.Port}"); if (homePath == null) { HomePath = "UNKNOWN"; } else { HomePath = new DirectoryInfo(homePath).FullName; } AuthToken = AuthTokens.Basic(Username, password); }
/// <summary> /// Checks if a Given Auth Token is valid /// </summary> /// <param name="authToken">The Auth Token string</param> /// <param name="authenticationToken">The Auth Token to validate</param> /// <returns>Whether the token is valid</returns> public virtual bool VerifyAuthToken(string authToken, out IAuthToken authenticationToken) { authenticationToken = null; if (string.IsNullOrWhiteSpace(authToken)) { return(false); } var token = _authTokenRepository.GetAllQuery() .Where(x => x.Token.Equals(authToken)) .FirstOrDefault(); authenticationToken = token; return(token != null); }
public IServiceCollection AddGraphContext <T>(string uri, IAuthToken authToken = null, Config config = null) where T : GraphContext { authToken = authToken ?? AuthTokens.None; config = config ?? new Config(); Services.AddSingleton <DriverProvider <T> >( provider => new InternalDriverProvider <T>( provider.GetRequiredService <N4pperManager>()) { _Uri = uri, _AuthToken = authToken, _Config = config }); Services.AddSingleton <T>(); return(Services); }