コード例 #1
0
        public void TestMethod1()   
        {
            var tokenGenerator = new TokenGenerator();
            // var token = tokenGenerator.GetIdPToken("https://testfs.fcsamerica.com/adfs/services/trust/13/usernamemixed", "https://teststs.fcsamerica.net/", "FCSAmerica\\username", "password" );

            var token = tokenGenerator.GetIdPToken("https://testfs.fcsamerica.com/adfs/services/trust/13/windowsmixed", "https://teststs.fcsamerica.net/");
            var stsToken = tokenGenerator.GetSTSToken(token, "https://teststs.fcsamerica.net/", "devfcma.fcsamerica.net:AGL");
        }
コード例 #2
0
        public void SetupEmailConfirmation(int userId)
        {
            Require.Positive(userId, nameof(userId));

            var token   = TokenGenerator.GenerateToken();
            var request = new ConfirmationRequest(userId, token, ConfirmationType.MailConfirmation);

            _confirmationRepository.SaveConfirmationRequest(request);

            var confirmationLink = new Uri(new Uri("http://emploi.lod-misis.ru/confirm/"), token);

            _mailingRepository.SaveMail(new NotificationModel(new [] { userId }, "Подтверждение регистрации на Emploi", confirmationLink.ToString()));
        }
コード例 #3
0
ファイル: Protocol.cs プロジェクト: HenrikWM/anonymous-tokens
        public void Setup()
        {
            // Import parameters for the elliptic curve prime256v1
            _ecParameters = CustomNamedCurves.GetByOid(X9ObjectIdentifiers.Prime256v1);

            _initiator      = new Initiator();
            _tokenGenerator = new TokenGenerator();
            _tokenVerifier  = new TokenVerifier(new InMemorySeedStore());

            SetupWithInMemoryKeyStores();

            SetupWithGeneratedKeys();
        }
コード例 #4
0
        public async Task CreateJournalNoteAsyncSuccess()
        {
            //Arrange
            var pageNumber = 1;
            var client     = _factory.CreateClient();

            var tokenHelper = new TokenGenerator();
            var accessToken = await tokenHelper.GetToken().ConfigureAwait(false);

            client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", accessToken);

            var dataToGetCitizenId = await client.GetAsync($"/citizens?pagenumber={pageNumber}").ConfigureAwait(false);

            var dataBody = await dataToGetCitizenId.Content.ReadAsStringAsync().ConfigureAwait(false);

            var actualData        = JsonConvert.DeserializeObject <CitizenList>(dataBody);
            var momentumCitizenId = actualData.Result.Select(x => x.CitizenId).FirstOrDefault();

            var requestUri = $"/citizens/journal/{momentumCitizenId}";

            List <JournalNoteDocumentRequestModel> documentList = new List <JournalNoteDocumentRequestModel>()
            {
                new JournalNoteDocumentRequestModel()
                {
                    Content     = "testContent",
                    ContentType = "application/octet-stream",
                    Name        = "TestName.pdf"
                }
            };

            JournalNoteRequestModel mcaRequestModel = new JournalNoteRequestModel()
            {
                Cpr       = "0101005402",
                Title     = "testTitle",
                Body      = "testBody",
                Type      = JournalNoteType.SMS,
                Documents = documentList
            };
            string _serializedRequest = JsonConvert.SerializeObject(mcaRequestModel);

            //Act
            var response = await client.PostAsync(requestUri, new StringContent(_serializedRequest, Encoding.UTF8, "application/json"));

            var responseBody = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

            var actualResponse = JsonConvert.DeserializeObject(responseBody);

            //Assert
            response.StatusCode.Should().Be(HttpStatusCode.OK);
            actualResponse.Should().BeEquivalentTo("OK");
        }
コード例 #5
0
        public void DisallowTokensTooLong()
        {
            Assert.Throws <Exception>(() =>
            {
                var payload = new Dictionary <string, object>
                {
                    { "uid", "blah" },
                    { "longVar", "123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345612345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234561234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456" }
                };

                var tokenGenerator = new TokenGenerator(FIREBASE_SUPER_SECRET_KEY);
                var token          = tokenGenerator.CreateToken(payload);
            });
        }
コード例 #6
0
        public void DisallowUidTooLong()
        {
            Assert.Throws <Exception>(() =>
            {
                var payload = new Dictionary <string, object>
                {
                    //                10        20        30        40        50        60        70        80        90       100       110       120       130       140       150       160       170       180       190       200       210       220       230       240       250    257
                    { "uid", "12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567" }
                };

                var tokenGenerator = new TokenGenerator(FIREBASE_SUPER_SECRET_KEY);
                var token          = tokenGenerator.CreateToken(payload);
            });
        }
コード例 #7
0
        public void SetupJwtAuthentication()
        {
            if (_apiClient.DefaultRequestHeaders.Contains("Authorization"))
            {
                return;
            }

            var gen = new TokenGenerator(new TokenOptions("API Test",
                                                          "Test",
                                                          new SymmetricSecurityKey(Encoding.UTF8.GetBytes("VeryLongSecureString12345")),
                                                          1));

            _apiClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {gen.GenerateAccessToken("abcde", new List<Claim>())}");
        }
コード例 #8
0
        public async Task<TokenResult> GetAccessToken(LoginAccountViewModel userInfo)
        {
            var user = await GetUserByUserNameOrEmail(userInfo);
            if (user == null)
            {
                return new TokenResult(null);
            }

            UpdateUserStatus(user, UserAvailabilityStatus.Online);
            var userRole = await GetFirstUserRole(user);
            var identity = GetIdentity(user, userRole);
            var token = TokenGenerator.GenerateSecurityToken(identity);
            return new TokenResult(user, userRole, token);
        }
コード例 #9
0
        public async Task GetUserFromBearerToken(RequestContext <IScenePeerClient> ctx)
        {
            var app = await _environment.GetApplicationInfos();

            var data = TokenGenerator.DecodeToken <BearerTokenData>(ctx.ReadObject <string>(), app.PrimaryKey);

            if (data == null)
            {
                throw new ClientException("Invalid Token");
            }
            var session = await _sessions.GetSession(data.PeerId);

            ctx.SendValue(session?.User.Id);
        }
コード例 #10
0
        private static string ReturnMethodName(string line)
        {
            string[] sp = line.Split();

            foreach (string x in sp)
            {
                if (!TokenGenerator.IsAccessModifier(x) && !TokenGenerator.IsReturnType(x))
                {
                    return(x);
                }
            }

            return(null);
        }
コード例 #11
0
        private static string ReturnClassName(string line)
        {
            string[] sp = line.Split();

            foreach (string x in sp)
            {
                if (!TokenGenerator.IsAccessModifier(x) && x != "class")
                {
                    return(x);
                }
            }

            return(null);
        }
コード例 #12
0
        [HttpPost] // Login
        public IActionResult Login(UserDTO dto)
        {
            var user = _userManager.FindByNameAsync(dto.Username).Result;

            if (user.PasswordHash == HashGenerator.GenerateHash(dto.Password))
            {
                string token = TokenGenerator.GenerateEncodedToken(user);
                return(Ok(token));
            }
            else
            {
                return(BadRequest());
            }
        }
コード例 #13
0
        public async Task <TokenEntity> GetUser(string username, string password)
        {
            var userEntity = await userRepository.GetUser(username, password);

            if (userEntity != null)
            {
                TokenGenerator tokenGenerator = new TokenGenerator();
                return(tokenGenerator.GenerateToken(userEntity, _authSettings.secret));
            }
            else
            {
                return(null);
            }
        }
コード例 #14
0
        public void EmptyString_ReturnsEmptyList()
        {
            //************* GIVEN
            var          generator      = TokenGenerator.Default();
            string       textString     = "";
            List <Token> expectedTokens = new List <Token>();

            //************* WHEN
            var tokens = generator.TokenizeThisString(textString);

            //************* GIVEN
            Assert.IsNotNull(tokens);
            Assert.AreEqual(expectedTokens.Count, tokens.Count());
        }
コード例 #15
0
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        static void Main(string[] args)
        {
            var tokenGenerator = new TokenGenerator();

            if (args.Contains(@"-token"))
            {
                Console.WriteLine(
                    tokenGenerator.Generate(
                        args.Contains(@"-uStat") || args.Contains(@"-all"),
                        args.Contains(@"-qStat") || args.Contains(@"-all")));
            }

            Console.ReadKey();
        }
コード例 #16
0
        public async Task <User> DeleteAsync(User user)
        {
            var body = await VerifyOneAsync(user.Username, user.Password);

            if (body != null && TokenGenerator.VerifyJWTToken(body.Token.Substring(1).Substring(0, body.Token.Length - 2), user.Token))
            {
                using var cmd   = Db.Connection.CreateCommand();
                cmd.CommandText = Statement.DeleteAsync;
                BindParams(cmd, user.Username, user.Password);
                await cmd.ExecuteNonQueryAsync();
            }

            return(body);
        }
            public void WhenEncryptedByCertificate_ReturnsExpectedResult(SecurityKey key)
            {
                // Arrange
                var encryptingCredentials = new EncryptingCredentials(key, SecurityAlgorithms.RsaOAEP, SecurityAlgorithms.Aes256CbcHmacSha512);
                var verifier  = new TokenVerifier(encryptingKey: key);
                var generator = new TokenGenerator(_nullLogger, signingCredentials: null, encryptingCredentials: encryptingCredentials);
                // Act
                var token  = generator.Generate(_validEntitlements);
                var result = verifier.Verify(token, _audience, _issuer, _contosoFinanceApp, _approvedAddress);

                // Assert
                result.Errors.Should().BeEmpty();
                result.Value.Applications.Should().Contain(_contosoFinanceApp);
            }
コード例 #18
0
        public static async Task <string> SavePasswordResetToken(this UserManager <User> userManager, IUserStore <User> userStore, User user, int lifeTimeOfTokenInHours)
        {
            if (user == null)
            {
                return(null);
            }
            var token = TokenGenerator.GenerateToken();

            user.PasswordResetToken = token;
            user.PasswordResetTokenExpirationTime = DateTime.UtcNow.AddHours(lifeTimeOfTokenInHours);
            await userStore.UpdateAsync(user, CancellationToken.None);

            return(token);
        }
コード例 #19
0
        public Main()
        {
            _firebase = new FirebaseClient("https://ecoband-5e79f.firebaseio.com/");
            _firebaseTokenGenerator = new TokenGenerator("AIzaSyCC_CjT8LY2ZiR2VhU5ufRsmboYw7USJiA");
            _beatsBuffer            = new Queue <int>(7);

            _ble.StateChanged             += OnStateChanged;
            _adapter.ScanTimeoutElapsed   += OnScanTimeoutElapsed;
            _adapter.DeviceAdvertised     += OnDeviceAdvertised;
            _adapter.DeviceDiscovered     += OnDeviceDiscovered;
            _adapter.DeviceConnected      += OnDeviceConnected;
            _adapter.DeviceDisconnected   += OnDeviceDisconnected;
            _adapter.DeviceConnectionLost += OnDeviceConnectionLost;
        }
コード例 #20
0
ファイル: UserSocketProcessor.cs プロジェクト: MuHuMbl/test
 public UserSocketProcessor(
     IMessageConsumer <MessageReceivedEventArgs> messageConsumer,
     IMessagePublisher <MessageReceivedEventArgs> messagePublisher,
     IEnumerable <IMessageProcessor> messageProcessors,
     TokenGenerator tokenGenerator,
     ILogger <UserSocketProcessor> logger)
 {
     _tokenGenerator    = tokenGenerator;
     _messageConsumer   = messageConsumer;
     _messagePublisher  = messagePublisher;
     _logger            = logger;
     _messageProcessors = messageProcessors.ToDictionary(x => x.MessageType, y => y);
     _messageConsumer.NewMessageReceived += OnNewMessageReceived;
 }
コード例 #21
0
        public void AllowNoUidWithAdmin()
        {
            var tokenOptions = new TokenOptions(null, null, true, false);

            var tokenGenerator = new TokenGenerator(FIREBASE_SUPER_SECRET_KEY);
            var token          = tokenGenerator.CreateToken(null, tokenOptions);
            var payload1       = new Dictionary <string, object>();
            var token1         = tokenGenerator.CreateToken(payload1, tokenOptions);
            var payload2       = new Dictionary <string, object>
            {
                { "foo", "bar" }
            };
            var token2 = tokenGenerator.CreateToken(payload2, tokenOptions);
        }
コード例 #22
0
        public static object Action(Int32[] ids, String action, String rejectReason = "")
        {
            Int32 LoginUserId = 0;

            if (HttpContext.Current.Session["UserId"] != null)
            {
                LoginUserId = Convert.ToInt32(HttpContext.Current.Session["UserId"].ToString());
            }
            try
            {
                string      idString = String.Join(",", ids);
                List <User> users    = IUserService.GetDataByFilter(" ID in (" + idString + ")", 0, 0, false);
                if (action == "Deactivate")
                {
                    users.ForEach(x =>
                    {
                        x.UpdatedBy = LoginUserId;
                        x.UpdatedOn = DateTime.Now;
                        x.Status    = 0;
                    });
                    IUserService.UpdateBulkData(users);
                }
                if (action == "Activate")
                {
                    users.ForEach(x =>
                    {
                        x.UpdatedBy = LoginUserId;
                        x.UpdatedOn = DateTime.Now;
                        x.Status    = 1;
                    });
                    IUserService.UpdateBulkData(users);
                }
                if (action == "GenerateToken")
                {
                    users.ForEach(x =>
                    {
                        x.UpdatedBy    = LoginUserId;
                        x.UpdatedOn    = DateTime.Now;
                        x.ApiAuthToken = TokenGenerator.Get(x.Username);
                    });
                    IUserService.UpdateBulkData(users);
                }
                return(true);
            }
            catch (Exception ex)
            {
                Console.WriteLine("User accounts action: " + ex.Message);
                return(false);
            }
        }
コード例 #23
0
        public Dictionary <string, dynamic> CreateDonation(string token, string receiver_card_token /*if equals "null", so use default*/, string title, string description)
        {
            try
            {
                var  user         = db.Users.Where(u => u.Token == token).FirstOrDefault();
                Card receiverCard = new Card();

                if (receiver_card_token == "null")
                {
                    receiverCard = db.Cards.Where(c => c.OwnerId == user.Id && c.IsDefault == true).FirstOrDefault();
                }
                else
                {
                    receiverCard = db.Cards.Where(c => c.OwnerId == user.Id && c.CardToken == receiver_card_token).FirstOrDefault();
                }

                string donationToken = "";
                do
                {
                    donationToken = TokenGenerator.Generate(baseTokenLength);
                } while (db.Donations.Where(d => d.DonationToken == donationToken).Count() != 0);

                Donation d = new Donation()
                {
                    DonationToken  = donationToken,
                    OwnerId        = user.Id,
                    ReceiverCardId = receiverCard.Id,
                    Title          = title,
                    Description    = description
                };

                db.Donations.Add(d);
                db.SaveChanges();

                return(new Dictionary <string, dynamic>()
                {
                    { "success", true },
                    { "donation_token", donationToken }
                });
            }
            catch (Exception e)
            {
                return(new Dictionary <string, dynamic>()
                {
                    { "success", false },
                    { "donation_token", "" },
                    { "err", e.InnerException.Message }
                });
            }
        }
コード例 #24
0
        public void Test()
        {
            var options = new TokenOptions()
                          .WithDigits()
                          .WithLength(18)
                          .WithAllDistinctCharacters()
                          .NeverStartsWith('0')
                          .WithPrefix("GTX");

            for (int i = 0; i < 1000; i++)
            {
                var token = TokenGenerator.Generate(options);
            }
        }
コード例 #25
0
        public async Task <IActionResult> PutAsync(int id, [FromBody] Estabelecimento item)
        {
            if (item.Id != id)
            {
                return(BadRequest(new {
                    status = 400,
                    message = "Id Inválido."
                }));
            }

            if (item == null)
            {
                return(BadRequest(new {
                    status = 400,
                    message = "Objeto Inválido."
                }));
            }

            if (ModelState.IsValid)
            {
                var token    = Request.Headers["Authorization"];
                var userId   = TokenGenerator.GetIdProfissional(token);
                var response = await _estabelecimentoRepository.UpdateAsync(item);

                if (response.Equals("success"))
                {
                    return(Ok(new {
                        status = HttpContext.Response.StatusCode,
                        message = "Atualizado com sucesso.",
                        data = item,
                        token = TokenGenerator.ReBuildToken(token)
                    }));
                }

                return(BadRequest(new {
                    status = 400,
                    message = response
                }));
            }
            else
            {
                return(BadRequest(new {
                    status = 400,
                    message = ModelState.Values.SelectMany(m => m.Errors)
                              .Select(e => e.ErrorMessage)
                              .ToList()
                }));
            }
        }
コード例 #26
0
        /// <summary>
        /// Get a new session token
        /// </summary>
        /// <param name="req">The info of the refresh</param>
        /// See <see cref="Areas.Identity.Models.RefreshRequest"/> to know the param structure
        /// <returns>The IActionResult of the refresh request</returns>
        /// See <see cref="Areas.Identity.Models.UserSession"/> the response structure
        public IActionResult refresh([FromBody] RefreshRequest req)
        {
            if (TokenGenerator.isValidClaim(req.token))
            {
                return(StatusCode(401));
            }

            string email        = TokenGenerator.getEmailClaim(req.token);
            string refreshToken = TokenGenerator.getRefreshTokenClaim(req.token);

            if (refreshToken == null)
            {
                return(StatusCode(401));
            }

            List <UserToken> savedRefreshToken = _context.UserToken.Where(ut => ut.refreshToken == refreshToken).ToList();

            if (savedRefreshToken.Count() != 1)
            {
                return(StatusCode(401));
            }

            if (savedRefreshToken.First().expirationTime < DateTime.Now)
            {
                try
                {
                    _context.Remove(savedRefreshToken.First());
                    _context.SaveChanges();
                }
                catch (Exception) { }
                return(StatusCode(401));
            }

            User user = _context.User.Where(u => u.email == email).First();

            if (!user.open)
            {
                return(BadRequest(new { error = "YoureBanned" }));
            }

            UserSession session = MakeUserSession.getUserSession(_context, user, req.provider);

            if (session == null)
            {
                return(StatusCode(500));
            }

            return(Ok(session));
        }
コード例 #27
0
        public bool SendForgetPassowrdEmail(SendEmailLogicModel model)
        {
            if (!_userRepository.Query().Any(x => x.Email == model.MailLogicModel.EmailTo))
            {
                return(false);
            }

            var userModel = _userRepository.Query().FirstOrDefault(x => x.Email == model.MailLogicModel.EmailTo);

            using (var unitOfwork = _unitOfWorkFactory.GetCurrentUnitOfWork())
            {
                if (userModel != null)
                {
                    userModel.ResetPasswordToken = TokenGenerator.EncodeToken(model.MailLogicModel.EmailTo + "&" + DateTime.UtcNow.ToString(CultureInfo.InvariantCulture));
                    userModel.ExpiredTime        = DateTime.Now.AddHours(1);
                    _userRepository.Save(userModel);
                }
                unitOfwork.Commit();
            }

            var titletxt = model.MailContentLogicModel.MailTitle;
            var bodytxt  = model.MailContentLogicModel.Content;

            bodytxt = bodytxt.Replace("{webname}", model.MailLogicModel.WebName);
            bodytxt = bodytxt.Replace("{weburl}", model.MailLogicModel.WebUrl);
            bodytxt = bodytxt.Replace("{webtel}", model.MailLogicModel.WebTel);
            if (userModel != null)
            {
                bodytxt = bodytxt.Replace("{linkurl}", model.MailLogicModel.AbsUrl + "?code=" + userModel.ResetPasswordToken);
            }

            try
            {
                SendEmailLogicModel.SendMail(model.MailLogicModel.EmailSmtp,
                                             model.MailLogicModel.EmailSsl,
                                             model.MailLogicModel.EmailUserName,
                                             TokenGenerator.DecodeToken(model.MailLogicModel.EmailPassWord),
                                             model.MailLogicModel.EmailNickName,
                                             model.MailLogicModel.EmailFrom,
                                             model.MailLogicModel.EmailTo,
                                             titletxt, bodytxt);
            }
            catch
            {
                return(false);
            }

            return(true);
        }
コード例 #28
0
        public IHttpActionResult GetGeneratedToken()
        {
            response.status = "FAILURE";
            try
            {
                TokenGenerator tokenGenerator = new TokenGenerator();
                response.stringParam1 = tokenGenerator.Encrypt(tokenGenerator.generateCode(10)) + ":" + tokenGenerator.Encrypt("ARJOCAMAHAMAGEAPP");
                response.status       = "SUCCESS";
            }
            catch (Exception e) {
                response.message = e.InnerException.InnerException.Message.ToString();
            }

            return(Ok(response));
        }
コード例 #29
0
        public string RefreshToken(string strToken)
        {
            TokenGenerator tokenGenerator = new TokenGenerator();
            string         decryptToken   = tokenGenerator.Decrypt(key, strToken);

            var objToken = JsonConvert.DeserializeObject <UserDTO>(decryptToken);

            objToken.FechaGeneracion = DateTime.Now;

            var jsonObject = JsonConvert.SerializeObject(objToken);

            string newToken = tokenGenerator.Encrypt(key, jsonObject);

            return(newToken);
        }
コード例 #30
0
ファイル: Trans.cs プロジェクト: surprise3465/WallPaper
        /// <summary>
        /// 谷歌翻译
        /// </summary>
        /// <param name="text">待翻译文本</param>
        /// <param name="fromLanguage">自动检测:auto</param>
        /// <param name="toLanguage">中文:zh-CN,英文:en</param>
        /// <returns>翻译后文本</returns>
        public string GoogleTranslate(string text, string fromLanguage, string toLanguage)
        {
            CookieContainer cc = new CookieContainer();

            string tk             = TokenGenerator.GetToken(text);
            string googleTransUrl = "https://translate.google.cn/translate_a/single?client=t&sl=" + fromLanguage + "&tl=" + toLanguage + "&hl=en&dt=at&dt=bd&dt=ex&dt=ld&dt=md&dt=qca&dt=rw&dt=rm&dt=ss&dt=t&ie=UTF-8&oe=UTF-8&otf=1&ssel=0&tsel=0&kc=1&tk=" + tk + "&q=" + HttpUtility.UrlEncode(text);

            var ResultHtml = GetResultHtml(googleTransUrl, cc, "https://translate.google.cn/");

            dynamic TempResult = Newtonsoft.Json.JsonConvert.DeserializeObject(ResultHtml);

            string ResultText = Convert.ToString(TempResult[0][0][0]);

            return(ResultText);
        }
コード例 #31
0
        //POST : /api/ApplicationUser/Login
        public async Task <IActionResult> Login(LoginModel model)
        {
            ApplicationUser user = await _userManager.FindByEmailAsync(model.Email);

            if (user == null || await _userManager.CheckPasswordAsync(user, model.Password) == false)
            {
                return(BadRequest(new { message = "Username or password is incorrect." }));
            }

            string token = new TokenGenerator(_applicationSettings.JWTSecret).GenerateToken(user);

            string myId = user.Id;

            return(Ok(new { token, myId }));
        }
コード例 #32
0
ファイル: ILGenerator.cs プロジェクト: Profit0004/mono
		internal ILGenerator (Module m, TokenGenerator token_gen, int size)
		{
			if (size < 0)
				size = 128;
			code = new byte [size];
			token_fixups = new ILTokenInfo [8];
			module = m;
			this.token_gen = token_gen;
		}