示例#1
0
        public static TokenHolder RefreshToken(string token)
        {
            EmployeeToken employeeInfo = Decode(token, REFRESHSECRETKEY);
            TokenHolder   tokenHolder  = CreateToken(employeeInfo);

            return(tokenHolder);
        }
 private void SetTokens(TokenHolder tokens)
 {
     _tokenHolder = tokens;
     // use the provided access token from now on
     _httpClient.DefaultRequestHeaders.Authorization =
         new AuthenticationHeaderValue("Bearer", _tokenHolder.AccessToken.ToInsecureString());
 }
 internal SimpleFulltextIndexReader(SearcherReference searcherRef, string[] properties, Analyzer analyzer, TokenHolder propertyKeyTokenHolder)
 {
     this._searcherRef            = searcherRef;
     this._properties             = properties;
     this._analyzer               = analyzer;
     this._propertyKeyTokenHolder = propertyKeyTokenHolder;
 }
示例#4
0
        public MluviiClient(IOptions <ServiceOptions> serviceOptions)
        {
            this.serviceOptions = serviceOptions;

            authHttpClient = new HttpClient
            {
                BaseAddress = new Uri($"https://{serviceOptions.Value.MluviiDomain}")
            };

            apiHttpClient = new HttpClient
            {
                BaseAddress           = new Uri($"https://{serviceOptions.Value.MluviiDomain}"),
                DefaultRequestHeaders = { }
            };

            tokenHolder = new TokenHolder(async() =>
            {
                var post = new Dictionary <string, string>
                {
                    { "response_type", "token" },
                    { "grant_type", "client_credentials" },
                    { "client_id", serviceOptions.Value.ClientId },
                    { "client_secret", serviceOptions.Value.ClientSecret },
                };

                using (var formContent = new FormUrlEncodedContent(post))
                {
                    var resp = await authHttpClient.PostAsync("/login/connect/token", formContent);
                    resp.EnsureSuccessStatusCode();

                    var reply = JsonConvert.DeserializeAnonymousType(await resp.Content.ReadAsStringAsync(), new { access_token = string.Empty });
                    return(reply.access_token);
                }
            });
        }
示例#5
0
        public void ForExcRemove()
        {
            var t = new TokenHolder();

            t.ClassPart  = "";
            t.ValuePart  = "";
            t.LineNumber = 5000;
            Token.Add(t);
        }
示例#6
0
        public int vpa       = 0;           //Value Part Array Counter



        public void AssignAll(string ClassName, string ValuePart, int Ln)
        {
            var t = new TokenHolder();

            t.ClassPart  = ClassName;
            t.ValuePart  = ValuePart;
            t.LineNumber = Ln;
            Token.Add(t);
            tn++;
        }
示例#7
0
 private void FindTeamHolder(int index)
 {
     TokenHolder[] allHolders = FindObjectsOfType <TokenHolder>();
     foreach (TokenHolder obj in allHolders)
     {
         if (obj.teamIndex == index)
         {
             holder = obj;
         }
     }
 }
示例#8
0
        internal LuceneFulltextIndex(PartitionedIndexStorage storage, IndexPartitionFactory partitionFactory, FulltextIndexDescriptor descriptor, TokenHolder propertyKeyTokenHolder) : base(storage, partitionFactory, descriptor)
        {
            this._analyzer               = descriptor.Analyzer();
            this._identifier             = descriptor.Name;
            this._type                   = descriptor.Schema().entityType();
            this._properties             = descriptor.PropertyNames();
            this._propertyKeyTokenHolder = propertyKeyTokenHolder;
            File indexFolder = storage.IndexFolder;

            _transactionsFolder = new File(indexFolder.Parent, indexFolder.Name + ".tx");
        }
 public OpenIdRenewalHandler(
     HttpClient httpClient,
     TokenHolder tokens,
     IAuthenticationHandler authenticationHandler,
     ILogger logger)
 {
     _authHandler = authenticationHandler;
     _httpClient  = httpClient;
     _logger      = logger;
     SetTokens(tokens);
 }
示例#10
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: private int getOrCreateForName(org.neo4j.kernel.impl.core.TokenHolder tokens, String name) throws org.neo4j.internal.kernel.api.exceptions.schema.IllegalTokenNameException
        private int GetOrCreateForName(TokenHolder tokens, string name)
        {
            _ktx.assertOpen();
            int id = tokens.GetIdByName(CheckValidTokenName(name));

            if (id != NO_TOKEN)
            {
                return(id);
            }
//JAVA TO C# CONVERTER TODO TASK: Method reference arbitrary object instance method syntax is not converted by Java to C# Converter:
            _ktx.assertAllows(AccessMode::allowsTokenCreates, "Token create");
            return(tokens.GetOrCreateId(name));
        }
示例#11
0
        /// <summary>
        /// Finds out if the user already exists in the database, if not then it gets created
        /// </summary>
        /// <returns></returns>
        internal async Task <bool> BuildWindowsUser()
        {
            CustomUser user = await UserManager.FindByNameAsync(windowsUserName);

            if ((user != null) && (!string.IsNullOrEmpty(user.Id)))
            {
                //user already exists
                if (!user.IsUserAutoGenerated)
                {
                    //weird circumstance.  existing user in the database was NOT auto created, but entered in explicitly.
                    throw new InvalidOperationException("User with login name " + windowsUserName + " exists, but not as a windows authorized user");
                }
                else
                {
#if !DEBUG
                    if (Request.IsSecureConnection)
                    {
#endif
                    string tokenURL = Url.Absolute(Url.Content("~/token"));
                    await TokenHolder.SetBearerTokenFromOAuth(tokenURL, user.UserName, windowsAuthPassword);

#if !DEBUG
                }
#endif
                    await SignInManager.SignInAsync(user, true, true);

                    return(true);
                }
            }
            else
            {
                //user does NOT exist in database, create user default details
                user = GetAutoCreateUser();
                var result = await UserManager.CreateAsync(user);

                if (result.Succeeded)
                {
                    //not ideal.  we don't know the user ID, so we have to search the user manager again to make sure it got created
                    user = await UserManager.FindByNameAsync(user.UserName);

                    //add user role if we like
                    //await UserManager.AddToRoleAsync(user.Id, "WhateverRoleIsInYourDatabase");
                    return(await BuildWindowsUser());    //return back through the method, it should just pass through the 'does user exist' check this time without issue
                }
                else
                {
                    throw new InvalidOperationException(string.Join("|", result.Errors));
                }
            }
            //return false;
        }
示例#12
0
        public void Setup()
        {
            configuration = TestHelpers.GetIConfigurationRoot(Directory.GetCurrentDirectory());

            var services = new ServiceCollection();

            // Simple configuration object injection (no IOptions<T>)
            services.AddSingleton(configuration);
            serviceProvider = services.BuildServiceProvider();
            rmc             = serviceProvider.GetRequiredService <ResourceManagementRepo>();
            azure           = serviceProvider.GetRequiredService <AzureDeploymentClient>();
            tokenHolder     = serviceProvider.GetRequiredService <TokenHolder>();
            omsClient       = serviceProvider.GetRequiredService <OmsClient>();
        }
示例#13
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: private void getOrCreateForNames(org.neo4j.kernel.impl.core.TokenHolder tokenHolder, String[] names, int[] ids) throws org.neo4j.internal.kernel.api.exceptions.schema.IllegalTokenNameException
        private void GetOrCreateForNames(TokenHolder tokenHolder, string[] names, int[] ids)
        {
            _ktx.assertOpen();
            AssertSameLength(names, ids);
            for (int i = 0; i < names.Length; i++)
            {
                ids[i] = tokenHolder.GetIdByName(CheckValidTokenName(names[i]));
                if (ids[i] == NO_TOKEN)
                {
//JAVA TO C# CONVERTER TODO TASK: Method reference arbitrary object instance method syntax is not converted by Java to C# Converter:
                    _ktx.assertAllows(AccessMode::allowsTokenCreates, "Token create");
                    tokenHolder.GetOrCreateIds(names, ids);
                    return;
                }
            }
        }
        public async Task RefereshAuthenticationAsync()
        {
            _httpClient.DefaultRequestHeaders.Remove("Authorization");

            if (!string.IsNullOrEmpty(_tokenHolder.RefreshToken.ToInsecureString()))
            {
                try
                {
                    _logger.LogInformation($"Getting a new access token using refresh token");
                    var scopes            = _tokenHolder.Scopes;
                    var tokenInfoResponse = await RefreshOpenIdTokenAsync(_tokenHolder.RefreshToken, scopes);

                    _logger.LogInformation($"Obtained a new access token using refresh token");
                    var tokens = new TokenHolder(tokenInfoResponse, scopes);
                    SetTokens(tokens);

                    // fire the 'token updated' event
                    TokenUpdated?.Invoke(tokens);

                    return;
                }
                catch (Exception ex)
                {
                    _logger.LogInformation(ex, "Could not refersh access token using the refresh_token");
                }
            }

            // authenticate again (using credentials or whatever the handler can do for us)
            if (_authHandler != null)
            {
                _logger.LogInformation($"Getting a new access token using {_authHandler.GetType()}");
                var tokens = await _authHandler.AuthenticateAsync();

                _logger.LogInformation($"Obtained a new access token using {_authHandler.GetType()}");
                SetTokens(tokens);

                // fire the 'token updated' event
                TokenUpdated?.Invoke(tokens);
            }
            else
            {
                throw new AuthenticationException(
                          "Unable to refresh access token and there is no way to re-authenticate.");
            }
        }
        public void AddTokenHolder(TokenHolder tokenHolder)
        {
            if (tokenHolder == null)
            {
                throw new ArgumentNullException();
            }

            if (String.IsNullOrWhiteSpace(tokenHolder.TokenId) || String.IsNullOrWhiteSpace(tokenHolder.DisplayName))
            {
                throw new ArgumentException();
            }

            using (var context = this.GetDbContext())
            {
                if (!context.TokenHolders.Any(item => item.TokenId == tokenHolder.TokenId))
                {
                    context.TokenHolders.Add(tokenHolder);
                    context.SaveChanges();
                }
            }
        }
示例#16
0
        private static TokenHolder CreateToken(EmployeeToken employeeInfo)
        {
            if (employeeInfo.VerifyObjectNull(throwEdit: false))
            {
                throw new EditException()
                      {
                          Edits = (new List <Edit>()
                    {
                        new Edit()
                        {
                            FieldName = "Invalid Data", Message = "Data should not be null."
                        }
                    })
                      };
            }

            TokenHolder tokenHolder = new TokenHolder();
            var         currentTime = (long)(DateTime.Now - new DateTime(1970, 1, 1, 0, 0, 0, 0).ToLocalTime()).TotalSeconds;
            var         payload     = new Dictionary <string, object>();

            payload.Add("userInfo", employeeInfo);
            payload.Add("exp", currentTime + EXPIRYTIME);

            IJwtAlgorithm     algorithm  = new HMACSHA256Algorithm();
            IJsonSerializer   serializer = new JsonNetSerializer();
            IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
            IJwtEncoder       encoder    = new JwtEncoder(algorithm, serializer, urlEncoder);

            tokenHolder.AccessToken = encoder.Encode(payload, SECRETKEY);

            var refreshPayload = new Dictionary <string, object>();

            refreshPayload.Add("userInfo", employeeInfo);
            refreshPayload.Add("CurrentDate", DateTime.Now.ToString());

            tokenHolder.RefreshToken = encoder.Encode(payload, REFRESHSECRETKEY);
            return(tokenHolder);
        }
        private async Task ProcessSignIn(SignInRequestSubmitted e)
        {
            var signInTime = this.signInService.SignIn(e.Person.DisplayName, e.Person.IsVisitor, e.Person.TokenId);

            await this.messagingClient.Publish(new PersonSignedIn(signInTime, e.Person));

            if (!String.IsNullOrWhiteSpace(e.Person.TokenId))
            {
                var tokenHolder = new TokenHolder()
                {
                    DisplayName = e.Person.DisplayName,
                    IsVisitor   = e.Person.IsVisitor,
                    TokenId     = e.Person.TokenId
                };

                var existingTokenHolder = this.tokenHolderService.GetTokenHolderByTokenId(tokenHolder.TokenId);

                if (existingTokenHolder == null)
                {
                    this.tokenHolderService.AddTokenHolder(tokenHolder);
                }
            }
        }
示例#18
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldRecoverCounts() throws Exception
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void ShouldRecoverCounts()
        {
            // GIVEN
            Node node = CreateNode(_label);

            CheckPoint();
            DeleteNode(node);

            // WHEN
            CrashAndRestart();

            // THEN
            // -- really the problem was that recovery threw exception, so mostly assert that.
            using ([email protected] tx = _db.DependencyResolver.resolveDependency(typeof(Kernel)).beginTransaction(@explicit, LoginContext.AUTH_DISABLED))
            {
                assertEquals(0, tx.DataRead().countsForNode(-1));
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final org.neo4j.kernel.impl.core.TokenHolder holder = db.getDependencyResolver().resolveDependency(org.neo4j.kernel.impl.core.TokenHolders.class).labelTokens();
                TokenHolder holder  = _db.DependencyResolver.resolveDependency(typeof(TokenHolders)).labelTokens();
                int         labelId = holder.GetIdByName(_label.name());
                assertEquals(0, tx.DataRead().countsForNode(labelId));
                tx.Success();
            }
        }
 internal PartitionedFulltextIndexReader(IList <PartitionSearcher> partitionSearchers, string[] properties, Analyzer analyzer, TokenHolder propertyKeyTokenHolder) : this(partitionSearchers.Select(PartitionSearcherReference::new).Select(searcher->new SimpleFulltextIndexReader(searcher, properties, analyzer, propertyKeyTokenHolder)).ToList())
示例#20
0
        internal static FulltextIndexDescriptor ReadOrInitialiseDescriptor(StoreIndexDescriptor descriptor, string defaultAnalyzerName, TokenHolder propertyKeyTokenHolder, File indexFolder, FileSystemAbstraction fileSystem)
        {
            Properties indexConfiguration = new Properties();

            if (descriptor.Schema() is FulltextSchemaDescriptor)
            {
                FulltextSchemaDescriptor schema = ( FulltextSchemaDescriptor )descriptor.Schema();
                indexConfiguration.putAll(Schema.IndexConfiguration);
            }
            LoadPersistedSettings(indexConfiguration, indexFolder, fileSystem);
            bool           eventuallyConsistent = bool.Parse(indexConfiguration.getProperty(INDEX_CONFIG_EVENTUALLY_CONSISTENT));
            string         analyzerName         = indexConfiguration.getProperty(INDEX_CONFIG_ANALYZER, defaultAnalyzerName);
            Analyzer       analyzer             = CreateAnalyzer(analyzerName);
            IList <string> names = new List <string>();

            foreach (int propertyKeyId in descriptor.Schema().PropertyIds)
            {
                try
                {
                    names.Add(propertyKeyTokenHolder.GetTokenById(propertyKeyId).name());
                }
                catch (TokenNotFoundException e)
                {
                    throw new System.InvalidOperationException("Property key id not found.", new PropertyKeyIdNotFoundKernelException(propertyKeyId, e));
                }
            }
            IList <string> propertyNames = Collections.unmodifiableList(names);

            return(new FulltextIndexDescriptor(descriptor, propertyNames, analyzer, analyzerName, eventuallyConsistent));
        }
示例#21
0
        private const string REFRESHSECRETKEY = "MICREFRESH"; //Refresh Key Confidential

        public static TokenHolder GenerateToken(EmployeeToken employeeInfo)
        {
            TokenHolder tokenHolder = CreateToken(employeeInfo);

            return(tokenHolder);
        }
示例#22
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Before public void setUp() throws Exception
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void SetUp()
        {
            _creator = mock(typeof(TokenCreator));
            _holder  = new DelegatingTokenHolder(_creator, "Dummy");
        }
示例#23
0
 public TokenHolders(TokenHolder propertyKeyTokens, TokenHolder labelTokens, TokenHolder relationshipTypeTokens)
 {
     this._propertyKeyTokens      = propertyKeyTokens;
     this._labelTokens            = labelTokens;
     this._relationshipTypeTokens = relationshipTypeTokens;
 }
示例#24
0
 public InternalAutoIndexOperations(TokenHolder propertyKeyLookup, EntityType type)
 {
     this._propertyKeyLookup = propertyKeyLookup;
     this._type = type;
 }
示例#25
0
        private async Task <TokenBalance> GetTokenBalanceAsync(TokenHolder tokenHolder)
        {
            var balance = await _contractClient.CallFunctionAsync <BigInteger>(tokenHolder.TokenAddress, _contractAbi, "balanceOf", tokenHolder.HolderAddress);

            return(new TokenBalance(tokenHolder, balance));
        }
 public async Task RequestSignIn(TokenHolder tokenHolder)
 {
     await this.messageBrokerService.Publish(new SignInRequestSubmitted(new Person(tokenHolder.TokenId, tokenHolder.DisplayName, tokenHolder.IsVisitor)));
 }