我正在尝试制作一个非常基本的应用程序来了解 Spring Boot Security 如何与 JPA 配合使用。 这是我的配置文件:
@Configuration
public class SecurityConfig {
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests((requests) -> requests
.requestMatchers("/", "/index").permitAll()
.anyRequest().authenticated()
)
.formLogin((form) -> form
.loginPage("/login")
.permitAll()
)
.logout((logout) -> logout.permitAll());
return http.build();
}
@Bean
public UserDetailsService userDetailsService() {
return new MyDatabaseUserDetailsService();
}
@Bean
public BCryptPasswordEncoder bCryptPasswordEncoder() {
return new BCryptPasswordEncoder();
}
}
我的用户实体:
@Entity
@Table(name = "users")
public class MyUser {
@Id
@Column(name = "username")
private String username;
@Column(name = "password")
private String password;
@Column(name = "authorities")
private String authorities;
public MyUser(String username, String password, String authorities) {
this.username = username;
this.password = password;
this.authorities = authorities;
}
public MyUser() {
}
// Getters and Setters
}
我的 UserDetails 类:
public class MyUserDetails implements UserDetails {
private MyUser myUser;
public MyUserDetails(MyUser myUser) {
this.myUser = myUser;
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
SimpleGrantedAuthority authority = new SimpleGrantedAuthority(myUser.getAuthorities());
return Arrays.asList(authority);
}
@Override
public String getPassword() {
return myUser.getPassword();
}
@Override
public String getUsername() {
return myUser.getUsername();
}
}
还有我的 UserDetailsService:
public class MyDatabaseUserDetailsService implements UserDetailsService{
@Autowired
UserDaoImpl userDao;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
MyUser user = userDao.findByUsername(username);
if (user == null) {
throw new UsernameNotFoundException("Could not find user");
}
return new MyUserDetails(user);
}
}
我的问题是,当我运行应用程序时,我收到消息: 使用生成的安全密码:4f50cde6-c1ad-406e-9968-6e51b6b05bc0
此生成的密码仅供开发使用。在生产环境中运行应用程序之前,必须更新您的安全配置。
我所有的观点都得到了保障。我认为有两个问题: 1-我允许查看/索引的配置不起作用 2-我的用户(来自我的数据库)不起作用,只能使用 spring 生成的用户 user/4f50cde6-c1ad-406e-9968-6e51b6b05bc0 。
也许是我不了解安全性,但我不知道可以是什么。
非常感谢!
问题不在于安全配置。问题是,通过将所有类分成包,在启动应用程序的 App 类中,您必须指示 Spring 必须在其中查找 Bean 的所有包。即必须添加注解@ComponentScan、@EntityScan和@EnableJpaRepositories
@ComponentScan(basePackages = {"com.pgsanchez.ww2dates.controller",
"com.pgsanchez.ww2dates.dao",
"com.pgsanchez.ww2dates.securingweb",
"com.pgsanchez.ww2dates.service",
"com.pgsanchez.ww2dates"})
@EntityScan(basePackages= {"com.pgsanchez.ww2dates.model"}) //Packages donde tiene que buscar clases del modelo
@EnableJpaRepositories(basePackages= {"com.pgsanchez.ww2dates.dao"})
@SpringBootApplication
public class Ww2datesJpaApplication {
public static void main(String[] args) {
SpringApplication.run(Ww2datesJpaApplication.class, args);
}
}