【发布时间】:2020-12-09 02:31:45
【问题描述】:
我有一个带有 Spring Security 的 Spring Boot 应用程序,我在其中扩展了 org.springframework.security.core.userdetails.User 类以创建自定义用户对象。我是硬编码用户,因为我只需要一些来测试一些功能。我该如何查询并根据其用户 ID 或电子邮件 ID 获取某个用户,这是我添加的自定义变量?有没有办法在不转向 jdbc 身份验证等的情况下做到这一点,因为我觉得它可能会过于复杂?
我的自定义用户类:
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
import java.util.Collection;
import java.util.List;
public class Guest extends User {
public Guest(String username, String password, boolean enabled, boolean accountNonExpired,
boolean credentialsNonExpired, boolean accountNonLocked,
Collection<? extends GrantedAuthority> authorities) {
super(username, password, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, authorities);
}
private long id;
private String firstName;
private String lastName;
private String emailAddress;
private String phoneNumber;
//some getters and setters
public Guest(long id, String firstName, String lastName, String emailAddress, String phoneNumber, String username, String password, List<GrantedAuthority> authorities,
boolean enabled, boolean accountNonExpired, boolean credentialsNonExpired, boolean accountNonLocked) {
super(username, password, enabled, accountNonExpired, credentialsNonExpired,
accountNonLocked, authorities) ;
this.id=id;
this.firstName=firstName;
this.lastName=lastName;
this.emailAddress=emailAddress;
this.phoneNumber=phoneNumber;
}
}
我的新 userdetailsService 类:
@Service("userDetailsService")
public class MyUserDetailsService implements UserDetailsService {
private static List<Guest> users = new ArrayList();
public MyUserDetailsService() {
//hard-coding users
}
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
//building user here
}
SecurityConfig.java
@Configuration
@EnableWebSecurity
public class ApplicationSecurityConfiguration extends WebSecurityConfigurerAdapter{
@Autowired
@Qualifier("userDetailsService")
private UserDetailsService userDetailsService;
@Bean
public BCryptPasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
};
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
}
@Override
protected void configure(HttpSecurity http) throws Exception {
//authorization logic here
}
}
【问题讨论】:
-
系统常量变量中的硬编码方式?
-
是的,我通过调用带有一些值的构造函数创建了一些虚拟用户。我的项目中没有外部数据源。
标签: java spring spring-boot spring-security