配置中的默认管理员用户和数据库中的其他用户

Default admin user in config and other users from database

我正在使用 spring 引导,带有 spring 安全和 jpa。我想在配置中有管理员用户,在数据库中有其他用户。问题是当我添加 UserDetailsService 时,来自 application.properties 的管理员用户停止工作。

application.properties:

spring.security.user.name=admin
spring.security.user.password={bcrypt}aF7xGm8iuzafFA7RPS8gzeKJm9qNBwtejT4hSuBKXMNlc/4NxOy1G
spring.security.user.roles=admin

Spring 安全配置 class:

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Qualifier("myUserDetailsService")
    @Autowired
    private UserDetailsService userDetailsService;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(encodePWD());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .csrf().disable()
                .authorizeRequests()
                .requestMatchers(PathRequest.toStaticResources().atCommonLocations()).permitAll()
                .antMatchers("/").permitAll()
                .antMatchers("/uzytkownik/pacjent/rejestracja").anonymous()
                .anyRequest().hasRole("admin")
                .and().formLogin().permitAll()
                ;


    }

    @Bean
    public BCryptPasswordEncoder encodePWD() {
        return new BCryptPasswordEncoder();
    }

}

没有任何配置 Spring 默认情况下,安全性从属性文件中读取用户。但是如果你添加一个 UserDetailsService 就意味着你想使用接口的方法 loadUserByUsername 来读取用户。例如可以实现此方法以从数据库中读取用户

如果您希望 application.properties 的管理员用户被视为用户,您可以在 UserDetailsService 的实现中创建它:

import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.userdetails.User;
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;

@Service
public class MyUserDetailsService implements UserDetailsService {

    @Value("${spring.security.user.name}")
    private String adminUserName;

    @Value("${spring.security.user.password}")
    private String adminPassword;

    @Value("${spring.security.user.roles}")
    private String adminRole;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        if(username.equals(adminPassword)) {
            return User.builder().username(adminUserName).password(adminPassword).roles(adminRole).build();
        }

        //return your other users from database here
        return null;
    }
}