public AuthenticationResult Authenticate(string login, string password) { login = login.SafeTrim(); if(string.IsNullOrEmpty(login)) return new AuthenticationResult(AuthenticationResultCode.NoSuchUser); if(string.IsNullOrEmpty(password)) return new AuthenticationResult(AuthenticationResultCode.WrongPassword); var user = referencedDataManager.FindUserByLogin(login); if(user == null) return new AuthenticationResult(AuthenticationResultCode.NoSuchUser); if(!user.IsActive) return new AuthenticationResult(AuthenticationResultCode.InactiveUser); if(string.IsNullOrEmpty(user.PasswordHash) || string.IsNullOrEmpty(user.PasswordSalt)) { /*logger.Error("An active user can't have an empty password hash or salt. UserId: {0}, Login: {1}", user.UserId, user.Login);*/ return new AuthenticationResult(AuthenticationResultCode.InternalError); } var passwordHash = passwordHasher.HashPassword(password, user.PasswordSalt); if(user.PasswordHash != passwordHash) return new AuthenticationResult(AuthenticationResultCode.WrongPassword); if(user.PasswordHash != passwordHash) return new AuthenticationResult(AuthenticationResultCode.WrongPassword); var authenticationToken = new AuthenticationToken(user.UserId); var encryptedBase64EncodedToken = authenticationTokenCryptography.EncryptTokenToBase64(authenticationToken); return new AuthenticationResult(encryptedBase64EncodedToken, user.UserId); }
public byte[] EncryptToken(AuthenticationToken authenticationToken) { byte[] tokenBytes = authenticationToken.Serialize(); var symmetricAlgorithm = new AesCryptoServiceProvider { Key = Convert.FromBase64String(authenticationKey) }; symmetricAlgorithm.GenerateIV(); var transform = symmetricAlgorithm.CreateEncryptor(); using (var stream = new MemoryStream()) { var writer = new BinaryWriter(stream); writer.Write(symmetricAlgorithm.IV.Length); writer.Write(symmetricAlgorithm.IV); using (var cryptoStream = new CryptoStream(stream, transform, CryptoStreamMode.Write)) { cryptoStream.Write(tokenBytes, 0, tokenBytes.Length); } return stream.ToArray(); } }
public string EncryptTokenToBase64(AuthenticationToken authenticationToken) { return Convert.ToBase64String(EncryptToken(authenticationToken)); }