Add UserDetailsService implementation to use DB users
This commit is contained in:
@@ -2,13 +2,13 @@ package net.kapcake.bankingservice.config;
|
|||||||
|
|
||||||
import org.springframework.context.annotation.Bean;
|
import org.springframework.context.annotation.Bean;
|
||||||
import org.springframework.context.annotation.Configuration;
|
import org.springframework.context.annotation.Configuration;
|
||||||
import org.h2.tools.Server;
|
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
|
||||||
import java.sql.SQLException;
|
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||||
|
|
||||||
@Configuration
|
@Configuration
|
||||||
public class BankingServiceConfig {
|
public class BankingServiceConfig {
|
||||||
@Bean(initMethod = "start", destroyMethod = "stop")
|
@Bean
|
||||||
public Server h2Server() throws SQLException {
|
public PasswordEncoder passwordEncoder() {
|
||||||
return Server.createTcpServer("-tcp", "-tcpAllowOthers", "-tcpPort", "9092");
|
return PasswordEncoderFactories.createDelegatingPasswordEncoder();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,28 @@
|
|||||||
|
package net.kapcake.bankingservice.security;
|
||||||
|
|
||||||
|
import net.kapcake.bankingservice.domain.User;
|
||||||
|
import net.kapcake.bankingservice.repositories.UserRepository;
|
||||||
|
import org.springframework.security.core.userdetails.UserDetails;
|
||||||
|
import org.springframework.security.core.userdetails.UserDetailsService;
|
||||||
|
import org.springframework.security.core.userdetails.UsernameNotFoundException;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
|
||||||
|
import static org.springframework.security.core.userdetails.User.withUsername;
|
||||||
|
|
||||||
|
@Service
|
||||||
|
public class UserDetailsServiceImpl implements UserDetailsService {
|
||||||
|
private final UserRepository userRepository;
|
||||||
|
|
||||||
|
public UserDetailsServiceImpl(UserRepository userRepository) {
|
||||||
|
this.userRepository = userRepository;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
@Transactional
|
||||||
|
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
|
||||||
|
User user = userRepository.findByUsername(username)
|
||||||
|
.orElseThrow(() -> new UsernameNotFoundException("User (" + username + ") does not exist"));
|
||||||
|
return withUsername(username).password(user.getPassword()).authorities("USER").build();
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user