Spring boot 基于数据库的spring-rbac认证
我试图在spring boot中创建基于角色的授权,我对spring是全新的,我主要使用PHP 找到此链接: 一切都很好,但与数据库没有连接,还尝试了解如何使用数据库创建授权Spring boot 基于数据库的spring-rbac认证,spring-boot,Spring Boot,我试图在spring boot中创建基于角色的授权,我对spring是全新的,我主要使用PHP 找到此链接: 一切都很好,但与数据库没有连接,还尝试了解如何使用数据库创建授权 public class UserDetailsServiceImp implements UserDetailsService { private UserRepository userRepository; @Override public UserDetails loadUser
public class UserDetailsServiceImp implements UserDetailsService {
private UserRepository userRepository;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
/*Here we are using dummy data, you need to load user data from
database or other third party application*/
User user = findUserbyUername(username);
UserBuilder builder = null;
if (user != null) {
builder = org.springframework.security.core.userdetails.User.withUsername(username);
builder.password(//new BCryptPasswordEncoder().encode(user.getName())
user.getName() );
builder.roles("USER");
} else {
throw new UsernameNotFoundException("User not found.");
}
return builder.build();
}
private User findUserbyUername(String username) {
return userRepository.findByName(username);
}
}
用户存储库
public interface UserRepository extends CrudRepository<User, Integer> {
User findByName(String name);
}
在浏览器上收到“无效用户名和密码”
这里可能有什么问题,我从数据库中找到的唯一一件事就是通过名称和比较来查找用户
请帮忙!任何了解spring的人都可以在UserDetailsServiceImp类中尝试以下内容:
@Autowired
private UserRepository userRepository;
是否存在任何特定错误,如果您在此处添加错误日志将非常有用。@Atul添加的错误日志我猜它无法找到存储库,因为存在空指针异常。将UserRepositoy代码添加为well@Atul添加了userreposiroty,它也取自mysql spring教程,用户类显示用户表中的数据,我想我可以很容易地找到并返回用户数据以进行授权,而不是静态数据非常感谢,我了解了Autowired和component,我不知道这个注释初始化了私有UserRepository UserRepository;顺便说一下,@Autowired是Spring中最常用的注释。。。
@Entity // This tells Hibernate to make a table out of this class
public class User {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Integer id;
private String name;
private String email;
private String[] roles;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
@Autowired
private UserRepository userRepository;