Beispiel #1
0
        public async Task <GetAccessTokenResponse> Handle(ValidateCredentialsAndCreateAccessTokenRequest request, CancellationToken cancellationToken)
        {
            var credentialBytes = Convert.FromBase64String(request.Credentials);
            var credentials     = Encoding.UTF8.GetString(credentialBytes).Split(':', 2);

            if (credentials.Length != 2)
            {
                _logger.LogInformation($"Invalid auth header [{request.Credentials}] - expected 'Basic appkey:appsecret'");
                return(null);
            }

            var apiClient = await _apiClientRepository.GetAsync(credentials[0]);

            if (apiClient == null)
            {
                _logger.LogInformation($"Could not find api client for appkey [{credentials[0]}]");
                return(null);
            }

            if (SaltHashHelper.CreateHash(credentials[1], apiClient.AppSecretSalt) != apiClient.AppSecretHash)
            {
                _logger.LogInformation($"Invalid login attempt");
                return(null);
            }

            var userAccountApiAccess = await _userAccountApiAccessRepository.GetByRefreshTokenAsync(request.RefreshToken);

            if (userAccountApiAccess == null)
            {
                _logger.LogInformation($"Unknown refresh token: {request.RefreshToken}");
                return(null);
            }

            if (userAccountApiAccess.RevokedDateTime != null)
            {
                _logger.LogInformation($"API Access has been revoked");
                return(new GetAccessTokenResponse("user_revoked", null));
            }

            var tokenData   = GuidString.NewGuidString();
            var tokenExpiry = DateTime.UtcNow.AddMinutes(30);
            await _userAccountTokenRepository.CreateAsync(userAccountApiAccess, tokenData, tokenExpiry);

            var tokenOptions = _configuration.GetSection("SmallListerApiJwt");
            var signingKey   = tokenOptions.GetValue("SigningKey", "");
            var issuer       = tokenOptions.GetValue("Issuer", "");
            var audience     = tokenOptions.GetValue("Audience", "");

            var tokenHandler            = new JwtSecurityTokenHandler();
            var securityTokenDescriptor = new SecurityTokenDescriptor
            {
                Subject            = new ClaimsIdentity(new[] { new Claim(ClaimTypes.Name, tokenData) }),
                Audience           = audience,
                Issuer             = issuer,
                Expires            = tokenExpiry,
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(Encoding.UTF8.GetBytes(signingKey)), SecurityAlgorithms.HmacSha256Signature)
            };

            return(new GetAccessTokenResponse(null, tokenHandler.WriteToken(tokenHandler.CreateToken(securityTokenDescriptor))));
        }
Beispiel #2
0
        public void Validate()
        {
            var con = DbHelper.GetDbConnection();

            con.Open();
            var name     = "Justin_Vazquez";
            var password = "******";

            if (!string.IsNullOrWhiteSpace(UserAccess.GetName(con, name)))
            {
                var userID = UserAccess.GetIdByName(con, name);
                var hash   = UserAccess.GetHash(con, userID);
                var salt   = UserAccess.GetSalt(con, userID);

                try
                {
                    if (SaltHashHelper.ValidatePassword(password, hash, salt))
                    {
                        Console.Write(UserAccess.GetUser(con, name, hash));
                    }
                    else
                    {
                        Console.Write("Error");
                    }
                }
                catch (Exception error)
                {
                    Console.Write(error);
                }
                finally
                {
                    con.Close();
                }
            }
        }
Beispiel #3
0
 public HtmlWordsServiceTest()
 {
     _dbOptions        = new DbContextOptions <WordsDbContext>();
     _wordsDbContext   = new Mock <WordsDbContext>(_dbOptions).Object;
     _logger           = new Mock <ILogger <HtmlWordsService> >().Object;
     _saltHashHelper   = new SaltHashHelper();
     _htmlWordsService = new HtmlWordsService(_wordsDbContext, _logger, _saltHashHelper);
 }
Beispiel #4
0
        public void CreateSaltHash()
        {
            var password = "******";

            var(salt, hash) = SaltHashHelper.CreateHash(password);

            salt.Should().NotBeNullOrEmpty();
            hash.Should().NotBeNullOrEmpty();
        }
Beispiel #5
0
        public void VerifyHash()
        {
            var password = "******";

            var(salt, hash) = SaltHashHelper.CreateHash(password);

            var verify = SaltHashHelper.CreateHash(password, salt);

            verify.Should().Be(hash);
        }
Beispiel #6
0
 public HtmlWordsService(
     WordsDbContext wordsDbContext,
     ILogger <HtmlWordsService> logger,
     SaltHashHelper saltHashHelper
     )
 {
     _words          = new List <string>();
     _wordsDbContext = wordsDbContext;
     _logger         = logger;
     _saltHashHelper = saltHashHelper;
 }
        public async Task <CreateExternalClientResponse> Handle(CreateExternalClientRequest request, CancellationToken cancellationToken)
        {
            var user = await _userAccountRepository.GetUserAccountAsync(request.User);

            var appKey    = GuidString.NewGuidString();
            var appSecret = GuidString.NewGuidString();

            var(appSecretSalt, appSecretHash) = SaltHashHelper.CreateHash(appSecret);

            await _apiClientRepository.CreateAsync(request.Model.Name, request.Model.Uri, appKey, appSecretHash, appSecretSalt, user);

            return(new CreateExternalClientResponse(request.Model.Name, request.Model.Uri, appKey, appSecret));
        }
Beispiel #8
0
        /// <summary>
        /// Legt einen neuen User in der Datenbank an
        /// </summary>
        /// <param name="name">User Name</param>
        /// <param name="password">User Password</param>
        /// <returns>Einen HttpStatusCode OK bei Erfolg InternalServerError bei Fehlschlag</returns>
        public HttpStatusCode Anlegen(string name, string password)
        {
            var con = DbHelper.GetDbConnection();

            con.Open();

            if (string.IsNullOrWhiteSpace(UserAccess.GetName(con, name)))
            {
                var HashnSalt = SaltHashHelper.CreateHash(password);
                UserAccess.AddUser(con, name, HashnSalt.Item1);
                UserAccess.AddSalt(con, UserAccess.GetIdByName(con, name), HashnSalt.Item2);
                return(HttpStatusCode.OK);
            }
            else
            {
                return(HttpStatusCode.InternalServerError);
            }
        }
Beispiel #9
0
        public void UserAnlegen()
        {
            var con = DbHelper.GetDbConnection();

            con.Open();
            if (string.IsNullOrEmpty(UserAccess.GetName(con, "Test")))
            {
                var SaltnHash = SaltHashHelper.CreateHash("Test");
                UserAccess.AddUser(con, "Test", SaltnHash.Item1);
                var ID = UserAccess.GetIdByName(con, "Test");
                UserAccess.AddSalt(con, ID, SaltnHash.Item2);
            }
            else
            {
                Console.Write("Error");
            }
            con.Close();
        }
Beispiel #10
0
        /// <summary>
        /// Ändert das Passwort eines Users
        /// </summary>
        /// <param name="name">User Name</param>
        /// <param name="password">Aktuelles User Password</param>
        /// <param name="newPassword">Neues User Password</param>
        /// <returns>Einen HttpStatusCode OK bei Erfolg InternalServerError bei Fehlschlag</returns>
        public HttpStatusCode ChangePassword(string name, string password, string newPassword)
        {
            //Validierung des Users
            var User = Login(name, password);

            if (User != null)
            {
                var con = DbHelper.GetDbConnection();
                con.Open();
                //Erstellt einen neuen Hash und Updated diesen und den Salt des Users
                var HashnSalt = SaltHashHelper.CreateHash(newPassword);
                UserAccess.ChangeHash(con, name, HashnSalt.Item1);
                UserAccess.ChangeSalt(con, name, HashnSalt.Item2);
                con.Close();
                return(HttpStatusCode.OK);
            }
            else
            {
                return(HttpStatusCode.BadRequest);
            }
        }
Beispiel #11
0
        public async Task InitializeAsync()
        {
            using var serviceScope = _factory.Services.CreateScope();
            using var context      = serviceScope.ServiceProvider.GetRequiredService <SqliteDataContext>();
            context.Migrate();

            var userAccount = await context.UserAccounts.AddAsync(new UserAccount { AuthenticationUri = "http://test/user/1" });

            var userList = await context.UserLists.AddAsync(new UserList { Name = "Test list", UserAccount = userAccount.Entity });

            await context.UserItems.AddRangeAsync(
                new UserItem { Description = "Test item 1", UserAccount = userAccount.Entity },
                new UserItem { Description = "Test item 2", UserAccount = userAccount.Entity, UserList = userList.Entity, NextDueDate = DateTime.Today },
                new UserItem { Description = "Test item 3", UserAccount = userAccount.Entity, UserList = userList.Entity, NextDueDate = DateTime.Today.AddDays(-1), Repeat = ItemRepeat.Daily }
                );

            var(appSecretSalt, appSecretHash) = SaltHashHelper.CreateHash(appSecret);
            await context.ApiClients.AddAsync(new ApiClient { AppKey = appKey, AppSecretSalt = appSecretSalt, AppSecretHash = appSecretHash, RedirectUri = redirectUri, CreatedBy = userAccount.Entity, DisplayName = "test-api-client" });

            await context.SaveChangesAsync();
        }
Beispiel #12
0
        /// <summary>
        /// Methode um einen User für den Login zu Validieren
        /// </summary>
        /// <param name="name">User Name</param>
        /// <param name="password">User Password</param>
        /// <returns>Ein Objekt vom Typ User</returns>
        public UserModel Login(string name, string password)
        {
            var con = DbHelper.GetDbConnection();

            con.Open();

            //Wenn der User existiert dann weiter.
            if (!string.IsNullOrWhiteSpace(UserAccess.GetName(con, name)))
            {
                //Hash und Salt aus der Datenbank anhand der UserID die durch den Username ermittelt wird
                var userID = UserAccess.GetIdByName(con, name);
                var hash   = UserAccess.GetHash(con, userID);
                var salt   = UserAccess.GetSalt(con, userID);

                try
                {
                    //Validiert den Hash aus der Datenbank mit dem Passwort aus der Login-Form
                    if (SaltHashHelper.ValidatePassword(password, hash, salt))
                    {
                        var user = UserAccess.GetUser(con, name, hash);
                        user.KlassenName = StundeplanAccess.GetKlasseText(con, user.Klasse);
                        return(user);
                    }
                    else
                    {
                        return(null);
                    }
                }
                catch (Exception error)
                {
                    Console.Write(error);
                }
                finally
                {
                    con.Close();
                }
            }

            return(null);
        }
Beispiel #13
0
 public SaltHashHelperTest()
 {
     _saltHashHelper = new SaltHashHelper();
 }