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"); }
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())); }
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(); }
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"); }
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); }); }
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); }); }
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>())}"); }
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); }
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); }
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); }
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); }
[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()); } }
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); } }
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()); }
/// <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(); }
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); }
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); }
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; }
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; }
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); }
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); } }
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 } }); } }
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); } }
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() })); } }
/// <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)); }
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); }
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)); }
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); }
/// <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); }
//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 })); }
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; }