Java 带有自定义 UserDetailsService 的 Spring Boot
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24723201/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Spring Boot with custom UserDetailsService
提问by igo
What is the correct way to add my custom implementation of UserDetailsService (which uses Spring Data JPA) to Spring Boot app?
将我的 UserDetailsService(使用 Spring Data JPA)的自定义实现添加到 Spring Boot 应用程序的正确方法是什么?
public class DatabaseUserDetailsService implements UserDetailsService {
@Inject
private UserAccountService userAccountService;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = userAccountService.getUserByEmail(username);
return new MyUserDetails(user);
}
}
public interface UserRepository extends JpaRepository<User, Long>, JpaSpecificationExecutor<User> {
public User findByEmail(String email);
}
@Service
public class UserAccountService {
@Inject
protected UserRepository userRepository;
public User getUserByEmail(String email) {
return userRepository.findByEmail(email);
}
}
@Configuration
@ComponentScan
@EnableAutoConfiguration
@EnableGlobalMethodSecurity(prePostEnabled = true)
@EnableTransactionManagement
@EnableJpaRepositories(basePackages = "com.sample")
@EntityScan(basePackages = { "com.sample" })
@EnableJpaAuditing(auditorAwareRef = "auditorProvider")
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
...
@Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
protected static class ApplicationSecurity extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/").hasRole("USER")
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll();
}
}
@Order(Ordered.HIGHEST_PRECEDENCE + 10)
protected static class AuthenticationSecurity extends GlobalAuthenticationConfigurerAdapter {
@Inject
private UserAccountService userAccountService;
@Override
public void init(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService());
}
@Bean
public UserDetailsService userDetailsService() {
return new DatabaseUserDetailsService();
}
}
}
@Entity
public class User extends AbstractPersistable<Long> {
@ManyToMany
private List<Role> roles = new ArrayList<Role>();
// getter, setter
}
@Entity
public class Role extends AbstractPersistable<Long> {
@Column(nullable = false)
private String authority;
// getter, setter
}
I cannot start app beacouse I get (full exception here http://pastebin.com/gM804mvQ)
我无法启动应用程序,因为我得到了(这里完全例外http://pastebin.com/gM804mvQ)
Caused by: org.hibernate.AnnotationException: Use of @OneToMany or @ManyToMany targeting an unmapped class: com.sample.model.User.roles[com.sample.model.Role]
at org.hibernate.cfg.annotations.CollectionBinder.bindManyToManySecondPass(CollectionBinder.java:1134)
When I configure my ApplicationSecurity
with auth.jdbcAuthentication().dataSource(dataSource).usersByUsernameQuery("...).authoritiesByUsernameQuery("...")
everything is working including JPA and Spring Data repositories.
当我配置我ApplicationSecurity
的auth.jdbcAuthentication().dataSource(dataSource).usersByUsernameQuery("...).authoritiesByUsernameQuery("...")
一切时,包括 JPA 和 Spring Data 存储库。
采纳答案by Dave Syer
Your app seems to work for me (once I added @Configuration
to the AuthenticationSecurity
). Here's another working sample of a simple app with JPA UserDetailsService
in case it helps: https://github.com/scratches/jpa-method-security-sample
您的应用程序似乎对我有用(一旦我添加@Configuration
到AuthenticationSecurity
)。这是使用 JPA 的简单应用程序的另一个工作示例,UserDetailsService
以防万一:https: //github.com/scratches/jpa-method-security-sample
回答by Ekansh Rastogi
You can also follow this blogto implement custom user details service.
您也可以关注此博客来实现自定义用户详细信息服务。
This example shows how you can send bean to userdetails service for injection.
此示例展示了如何将 bean 发送到 userdetails 服务进行注入。
- Autowire the Repository in the WebSecurityConfigurer
- Send this bean as a parameter to the user details service by a parameterized constructor.
- assign this a private member and use to load users from database.
- 在 WebSecurityConfigurer 中自动装配存储库
- 通过参数化构造函数将此 bean 作为参数发送到用户详细信息服务。
- 为其分配一个私有成员并用于从数据库加载用户。