private async Task <User> AuthenticateUser(User userLogin, BCryptPasswordHasher _BCrypt) { var userAuthenticateUsername = await dbContext.Users.FirstOrDefaultAsync(x => x.Username == userLogin.Username); var userAuthenticateEmail = await dbContext.Users.FirstOrDefaultAsync(x => x.Email == userLogin.Email); if (userAuthenticateUsername == null && userAuthenticateEmail == null) { return(null); } else if (userAuthenticateEmail == null) { if ((userLogin.Username == userAuthenticateUsername.Username && _BCrypt.AuthenticateUser(userLogin.Password, userAuthenticateUsername) == true)) { return(userAuthenticateUsername); } return(null); } else if (userAuthenticateUsername == null) { if ((userLogin.Email == userAuthenticateEmail.Email && _BCrypt.AuthenticateUser(userLogin.Password, userAuthenticateEmail) == true)) { return(userAuthenticateEmail); } return(null); } return(null); }
private List <User> SeedUsers(int totalAdmin, int totalManager, int totalCustomer, IReadOnlyList <UserTableSeederModel> userModels) { var list = new List <User>(); var total = totalAdmin + totalManager + totalCustomer; var hasher = new BCryptPasswordHasher <User>(); var password = hasher.HashPassword(null, DEFAULT_PASSWORD); for (var i = 0; i < total; i++) { var item = new User { Id = i + 1, Username = userModels[i].Username, Email = userModels[i].Email, Password = password, Active = true, UserRoleId = i < totalAdmin ? 1 : i < totalAdmin + totalManager ? 2 : 3, CreatedAt = userModels[i].Timestamp, UpdatedAt = userModels[i].Timestamp, ConnectId = Guid.NewGuid().ToString() }; list.Add(item); } return(list); }
public void TestPasswordHashers() { Startup.BooksApp.LogTestStart(); //run it only for MS SQL, to avoid slowing down console run for all servers if (Startup.ServerType != DbServerType.MsSql) { return; } IPasswordHasher hasher; var salt = Guid.NewGuid().ToByteArray(); var pwd = "MyPassword_*&^"; long start, timeMs; bool match; string hash; // You can use this test to approximate the 'difficulty' of hashing algorithm for your computer. // It prints the time it took to hash the pasword. This time should not be too low, desirably no less than 100 ms. hasher = new BCryptPasswordHasher(workFactor: 10); //each +1 doubles the effort; on my machine: 10 -> 125ms, 11->242ms start = Util.GetPreciseMilliseconds(); hash = hasher.HashPassword(pwd, salt); timeMs = Util.GetPreciseMilliseconds() - start; match = hasher.VerifyPassword(pwd, salt, hasher.WorkFactor, hash); Assert.IsTrue(match, "BCrypt hasher failed."); Debug.WriteLine("BCrypt hasher time, ms: " + timeMs); hasher = new Pbkdf2PasswordHasher(iterationCount: 2000); // on my machine: 2000-> 13ms, 5000->32ms start = Util.GetPreciseMilliseconds(); hash = hasher.HashPassword(pwd, salt); timeMs = Util.GetPreciseMilliseconds() - start; match = hasher.VerifyPassword(pwd, salt, hasher.WorkFactor, hash); Assert.IsTrue(match, "Pbkdf hasher failed."); Debug.WriteLine("Pbkdf hasher time, ms: " + timeMs); }
public UserService(IConfiguration config) { var client = new MongoClient(config.GetConnectionString("DB")); var database = client.GetDatabase("Auth"); _users = database.GetCollection <User>("Users"); _passwordHasher = new BCryptPasswordHasher <User>(); }
public void HashPassword_WithDefaultSettings_ExpectVerifiableHash() { var password = Guid.NewGuid().ToString(); var hasher = new BCryptPasswordHasher <string>(); var hashedPassword = hasher.HashPassword("", password); BCrypt.Net.BCrypt.Verify(password, hashedPassword).Should().BeTrue(); }
public void VerifyHashedPassword_WithDefaultSettings_ExpectSuccess() { var password = Guid.NewGuid().ToString(); var hashedPassword = BCrypt.Net.BCrypt.HashPassword(password); var hasher = new BCryptPasswordHasher <string>(); hasher.VerifyHashedPassword("", hashedPassword, password).Should().Be(PasswordVerificationResult.Success); }
public void VerifyHashedPassword_WhenSuppliedPasswordDoesNotMatch_ExpectFailure() { var password = Guid.NewGuid().ToString(); var hashedPassword = BCrypt.Net.BCrypt.HashPassword(Guid.NewGuid().ToString()); var hasher = new BCryptPasswordHasher <string>(); hasher.VerifyHashedPassword("", hashedPassword, password).Should().Be(PasswordVerificationResult.Failed); }
public void VerifyHashedPassword_WhenCorrectV10Password_ExpectSuccess() { const string password = "******"; const string hashedPassword = "******"; var hasher = new BCryptPasswordHasher <string>(); hasher.VerifyHashedPassword("", hashedPassword, password).Should().Be(PasswordVerificationResult.Success); }
public void VerifyHashedPassword_WhenPasswordCreatedWithEnhancedEntropyButVerifiedWithout_ExpectFailure() { var options = new BCryptPasswordHasherOptions { EnhancedEntropy = true }; var password = Guid.NewGuid().ToString(); var hashedPassword = BCrypt.Net.BCrypt.HashPassword(password, options.WorkFactor); var hasher = new BCryptPasswordHasher <string>(new OptionsWrapper <BCryptPasswordHasherOptions>(options)); hasher.VerifyHashedPassword("", hashedPassword, password).Should().Be(PasswordVerificationResult.Failed); }
public void VerifyHashedPassword_WithEnhancedEntropy_ExpectSuccess() { var options = new BCryptPasswordHasherOptions { EnhancedEntropy = true }; var password = Guid.NewGuid().ToString(); var hashedPassword = BCrypt.Net.BCrypt.HashPassword(password, options.WorkFactor, true); var hasher = new BCryptPasswordHasher <string>(new OptionsWrapper <BCryptPasswordHasherOptions>(options)); hasher.VerifyHashedPassword("", hashedPassword, password).Should().Be(PasswordVerificationResult.Success); }
public async Task <ActionResult <MessageModel> > SimulatePurchase(WalletRequestModel requestModel, ClaimsPrincipal currentUser, string username) { var userAuthenticate = await dbContext.Users.FirstOrDefaultAsync(x => x.Username == username); var product = requestModel.Product; var reciever = requestModel.Reciever; var amount = requestModel.Amount; Wallet wallet = requestModel.Wallet; Wallet walletExists = null; WalletResponseModel walletResponseModel = new WalletResponseModel(); BCryptPasswordHasher _BCrypt = new BCryptPasswordHasher(); if (currentUser.HasClaim(c => c.Type == "Roles")) { if (userAuthenticate != null) { try { walletExists = await dbContext.Wallets.FirstOrDefaultAsync(x => x.Iban == wallet.Iban); if (walletExists != null && (wallet.CardNumber == walletExists.CardNumber && wallet.CardExpirationDate == walletExists.CardExpirationDate && _BCrypt.AuthenticateWalletCVV(wallet, walletExists))) { if (walletExists.CardExpirationDate < DateTime.Now) { responseMessage.Message = "Wallet Card is expired"; return(StatusCode(406, responseMessage)); } return(await ValidatePurchaseAmountAndBankAccount(userAuthenticate, currentUser, walletExists, product, reciever, amount, _transactionsService)); } else { responseMessage.Message = "Wallet not found! Invalid Credentials!"; return(StatusCode(404, responseMessage)); } } catch (NullReferenceException) { responseMessage.Message = "Wallet not found! Invalid Credentials!"; return(StatusCode(404, responseMessage)); } } else { responseMessage.Message = "User not found!"; return(StatusCode(404, responseMessage)); } } responseMessage.Message = "You are not autorized to do such actions!"; return(StatusCode(403, responseMessage)); }
public void HashPassword_WithCustomWorkFactor_ExpectVerifiableHash() { var random = new Random(); var password = Guid.NewGuid().ToString(); var hasher = new BCryptPasswordHasher <string>( new OptionsWrapper <BCryptPasswordHasherOptions>( new BCryptPasswordHasherOptions { WorkFactor = random.Next(8, 18) })); var hashedPassword = hasher.HashPassword("", password); BCrypt.Net.BCrypt.Verify(password, hashedPassword).Should().BeTrue(); }
public void HashPassword_WithPasswordCreatedWithoutEnhancedEntropyButVerifiedWith_ExpectHashNotToVerify() { var password = Guid.NewGuid().ToString(); var hasher = new BCryptPasswordHasher <string>( new OptionsWrapper <BCryptPasswordHasherOptions>( new BCryptPasswordHasherOptions { EnhancedEntropy = false })); var hashedPassword = hasher.HashPassword("", password); BCrypt.Net.BCrypt.Verify(password, hashedPassword, true).Should().BeFalse(); BCrypt.Net.BCrypt.EnhancedVerify(password, hashedPassword).Should().BeFalse(); }
public async Task <ActionResult <MessageModel> > CreateWallet(ClaimsPrincipal currentUser, WalletRequestModel requestModel) { string role = ""; var username = requestModel.Username; Wallet wallet = requestModel.Wallet; BCryptPasswordHasher _BCrypt = new BCryptPasswordHasher(); if (currentUser.HasClaim(c => c.Type == "Roles")) { string userRole = currentUser.Claims.FirstOrDefault(currentUser => currentUser.Type == "Roles").Value; role = userRole; } if (role == "Admin") { var userAuthenticate = await dbContext.Users.FirstOrDefaultAsync(x => x.Username == username); if (userAuthenticate != null) { try { if (dbContext.Wallets.Where(x => x.UserId == userAuthenticate.Id).Count() < 7) { if (ValidateUser(userAuthenticate) && ValidateWallet(wallet)) { wallet.UserId = userAuthenticate.Id; wallet.Iban = IBANGenerator.GenerateIBANInVitoshaBank("Wallet", dbContext); wallet.CardNumber = GenerateCardInfo.GenerateNumber(11); var CVV = GenerateCardInfo.GenerateCVV(3); wallet.Cvv = (_BCrypt.HashPassword(CVV)); wallet.CardExpirationDate = DateTime.Now.AddMonths(60); await dbContext.AddAsync(wallet); await dbContext.SaveChangesAsync(); SendEmail(userAuthenticate.Email, _config); responseMessage.Message = "Wallet created succesfully!"; return(StatusCode(200, responseMessage)); } else if (ValidateUser(userAuthenticate) == false) { responseMessage.Message = "User not found!"; return(StatusCode(404, responseMessage)); } else if (ValidateWallet(wallet) == false) { responseMessage.Message = "Don't put negative value!"; return(StatusCode(400, responseMessage)); } } } catch (NullReferenceException) { responseMessage.Message = "User not found!"; return(StatusCode(404, responseMessage)); } } responseMessage.Message = "User already has 7 wallets!"; return(StatusCode(400, responseMessage)); } else { responseMessage.Message = "You are not autorized to do such actions!"; return(StatusCode(403, responseMessage)); } }
public async Task <ActionResult <MessageModel> > CreateCredit(ClaimsPrincipal currentUser, CreditRequestModel requestModel) { string role = ""; string username = requestModel.Username; Credit credit = requestModel.Credit; int period = requestModel.Period; BCryptPasswordHasher _BCrypt = new BCryptPasswordHasher(); if (currentUser.HasClaim(c => c.Type == "Roles")) { string userRole = currentUser.Claims.FirstOrDefault(currentUser => currentUser.Type == "Roles").Value; role = userRole; } if (role == "Admin") { var userAuthenticate = await dbContext.Users.FirstOrDefaultAsync(x => x.Username == username); if (userAuthenticate != null) { if (dbContext.Credits.Where(x => x.UserId != userAuthenticate.Id).Count() < 3) { if (ValidateUser(userAuthenticate) && ValidateCredit(credit)) { credit.Iban = IBANGenerator.GenerateIBANInVitoshaBank("Credit", dbContext); credit.Interest = 6.9m; credit.CreditAmount = CalculateInterest.CalculateCreditAmount(credit.Amount, period, credit.Interest); credit.Instalment = CalculateInterest.CalculateInstalment(credit.CreditAmount, credit.Interest, period); credit.CreditAmountLeft = credit.CreditAmount; credit.PaymentDate = DateTime.Now.AddMonths(1); credit.UserId = userAuthenticate.Id; await dbContext.AddAsync(credit); await dbContext.SaveChangesAsync(); SendEmail(userAuthenticate.Email); responseMessage.Message = "Credit created succesfully!"; return(StatusCode(200, responseMessage)); } else if (ValidateUser(userAuthenticate) == false) { responseMessage.Message = "User not found!"; return(StatusCode(404, responseMessage)); } else if (ValidateCredit(credit) == false) { responseMessage.Message = "Don't put negative value!"; return(StatusCode(400, responseMessage)); } } } responseMessage.Message = "User already has 3 active credits!"; return(StatusCode(400, responseMessage)); } else { responseMessage.Message = "You are not autorized to do such actions!"; return(StatusCode(403, responseMessage)); } }
public CustomUserManager(CustomUserStore store) : base(store) { PasswordHasher = new BCryptPasswordHasher(); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "etimo-id", Version = "v1" }); }); services.UseEtimoIdData(); var siteSettings = new SiteSettings(); Configuration.GetSection("SiteSettings").Bind(siteSettings); services.AddSingleton(siteSettings); var cryptologySettings = new CryptologySettings(); Configuration.GetSection("CryptologySettings").Bind(cryptologySettings); services.AddSingleton(cryptologySettings); services.AddSingleton(cryptologySettings.PasswordSettings); var oauth2Settings = new OAuth2Settings(); Configuration.GetSection("OAuth2Settings").Bind(oauth2Settings); services.AddSingleton(oauth2Settings); var jwtSettings = new JwtSettings(); Configuration.GetSection("JwtSettings").Bind(jwtSettings); services.AddSingleton(jwtSettings); services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { options.RequireHttpsMetadata = false; options.SaveToken = true; options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, ValidateAudience = true, ValidateLifetime = true, ValidateIssuerSigningKey = true, ValidIssuer = jwtSettings.Issuer, ValidAudience = jwtSettings.Issuer, IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtSettings.Secret)), ClockSkew = TimeSpan.Zero }; }); services.AddAuthorization(config => { AddScopePolicies(config, InbuiltScopes.All); AddCombinedScopePolicies(config, new Dictionary <string, string[]> { { CombinedScopes.ReadApplicationRole, new string[] { ApplicationScopes.Read, RoleScopes.Read } }, { CombinedScopes.ReadRoleScope, new string[] { RoleScopes.Read, ScopeScopes.Read } }, { CombinedScopes.ReadUserApplication, new string[] { UserScopes.Read, ApplicationScopes.Read } }, { CombinedScopes.ReadUserRole, new string[] { UserScopes.Read, RoleScopes.Read } } }); }); Log.Logger = new LoggerConfiguration() .Enrich.FromLogContext() .WriteTo.Console() .CreateLogger(); services.AddSingleton(Log.Logger); var passwordHasher = new BCryptPasswordHasher(cryptologySettings); services.AddSingleton <IPasswordHasher>(passwordHasher); services.AddTransient <IPasswordGenerator, PasswordGeneratorAdapter>(); // ApplicationServices services.AddTransient <IAddApplicationService, AddApplicationService>(); services.AddTransient <IAuthenticateClientService, AuthenticateClientService>(); services.AddTransient <IDeleteApplicationService, DeleteApplicationService>(); services.AddTransient <IFindApplicationService, FindApplicationService>(); services.AddTransient <IGenerateClientSecretService, GenerateClientSecretService>(); services.AddTransient <IGetApplicationsService, GetApplicationsService>(); services.AddTransient <IUpdateApplicationService, UpdateApplicationService>(); // AuditLogServices services.AddTransient <IFindAuditLogService, FindAuditLogService>(); services.AddTransient <IGetAuditLogsService, GetAuditLogsService>(); // AuthorizationServices services.AddTransient <IValidateTokenService, ValidateTokenService>(); services.AddTransient <IAuthorizeService, AuthorizeService>(); services.AddTransient <IGenerateTokenService, GenerateTokenService>(); // RoleServices services.AddTransient <IAddRoleScopeRelationService, AddRoleScopeRelationService>(); services.AddTransient <IAddRoleService, AddRoleService>(); services.AddTransient <IDeleteRoleScopeRelationService, DeleteRoleScopeRelationService>(); services.AddTransient <IDeleteRoleService, DeleteRoleService>(); services.AddTransient <IFindRoleService, FindRoleService>(); services.AddTransient <IGetRolesService, GetRolesService>(); services.AddTransient <IUpdateRoleService, UpdateRoleService>(); // ScopeServices services.AddTransient <IAddScopeService, AddScopeService>(); services.AddTransient <IDeleteScopeService, DeleteScopeService>(); services.AddTransient <IFindScopeService, FindScopeService>(); services.AddTransient <IGetScopesService, GetScopesService>(); services.AddTransient <IUpdateScopeService, UpdateScopeService>(); // UserServices services.AddTransient <IAddUserRoleRelationService, AddUserRoleRelationService>(); services.AddTransient <IAddUserService, AddUserService>(); services.AddTransient <IAuthenticateUserService, AuthenticateUserService>(); services.AddTransient <IDeleteUserRoleRelationService, DeleteUserRoleRelationService>(); services.AddTransient <IDeleteUserService, DeleteUserService>(); services.AddTransient <IFindUserService, FindUserService>(); services.AddTransient <IGetUsersService, GetUsersService>(); services.AddTransient <IUpdateUserService, UpdateUserService>(); // Token Generators services.AddTransient <IAuthorizationCodeTokenGenerator, AuthorizationCodeTokenGenerator>(); services.AddTransient <IClientCredentialsTokenGenerator, ClientCredentialsTokenGenerator>(); services.AddTransient <IResourceOwnerCredentialsTokenGenerator, ResourceOwnerCredentialsTokenGenerator>(); services.AddTransient <IRefreshTokenGenerator, RefreshTokenGenerator>(); services.AddTransient <IJwtTokenFactory, JwtTokenFactory>(); // Repositories services.AddTransient <IApplicationRepository, ApplicationRepository>(); services.AddTransient <IAccessTokenRepository, AccessTokenRepository>(); services.AddTransient <IAuditLogRepository, AuditLogRepository>(); services.AddTransient <IAuthorizationCodeRepository, AuthorizationCodeRepository>(); services.AddTransient <IRefreshTokenRepository, RefreshTokenRepository>(); services.AddTransient <IRoleRepository, RoleRepository>(); services.AddTransient <IScopeRepository, ScopeRepository>(); services.AddTransient <IUserRepository, UserRepository>(); services.AddDistributedMemoryCache(); services.AddControllersWithViews() .AddJsonOptions(options => { options.JsonSerializerOptions.PropertyNamingPolicy = SnakeCaseNamingPolicy.Instance; options.JsonSerializerOptions.IgnoreNullValues = true; }) .AddRazorRuntimeCompilation(); }
public async Task <ActionResult <MessageModel> > CreateChargeAccount(ClaimsPrincipal currentUser, ChargeAccountRequestModel requestModel, IDebitCardsService _debitCardService) { string role = ""; var username = requestModel.Username; ChargeAccount chargeAcc = requestModel.ChargeAccount; BCryptPasswordHasher _BCrypt = new BCryptPasswordHasher(); if (currentUser.HasClaim(c => c.Type == "Roles")) { string userRole = currentUser.Claims.FirstOrDefault(currentUser => currentUser.Type == "Roles").Value; role = userRole; } if (role == "Admin") { var userAuthenticate = await dbContext.Users.FirstOrDefaultAsync(x => x.Username == username); if (userAuthenticate != null) { if (dbContext.ChargeAccounts.Where(x => x.UserId == userAuthenticate.Id).Count() < 10) { try { if (ValidateUser(userAuthenticate) && ValidateChargeAccount(chargeAcc)) { chargeAcc.UserId = userAuthenticate.Id; chargeAcc.Iban = IBANGenerator.GenerateIBANInVitoshaBank("ChargeAccount", dbContext); await dbContext.AddAsync(chargeAcc); await dbContext.SaveChangesAsync(); Card card = new Card(); await _debitCardService.CreateDebitCard(currentUser, username, chargeAcc, card); SendEmail(userAuthenticate.Email, _config); responseModel.Message = "Charge Account created succesfully"; return(StatusCode(201, responseModel)); } else if (ValidateUser(userAuthenticate) == false) { responseModel.Message = "User not found!"; return(StatusCode(404, responseModel)); } else if (ValidateChargeAccount(chargeAcc) == false) { responseModel.Message = "Invalid parameteres!"; return(StatusCode(400, responseModel)); } } catch (NullReferenceException) { responseModel.Message = "Invalid parameteres!"; return(StatusCode(400, responseModel)); } } responseModel.Message = "User already has 10 Charge Accounts!"; return(StatusCode(400, responseModel)); } else { responseModel.Message = "User not found!"; return(StatusCode(404, responseModel)); } } else { responseModel.Message = "You are not authorized to do such actions"; return(StatusCode(403, responseModel)); } }