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
}
_
取得したアプリビーコンを開始できません(ここで完全な例外 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)
_
ApplicationSecurity
をauth.jdbcAuthentication().dataSource(dataSource).usersByUsernameQuery("...).authoritiesByUsernameQuery("...")
で構成すると、JPAおよびSpring Dataリポジトリを含むすべてが機能します。
あなたのアプリは私にとってはうまくいくようです(一度追加したら@Configuration
からAuthenticationSecurity
へ)。 JPA UserDetailsService
を使用した簡単なアプリのもう1つの実用的なサンプルを以下に示します。 https://github.com/scratches/jpa-method-security-sample
このブログ に従って、カスタムユーザー詳細サービスを実装することもできます。
この例は、注入のためにBeanをuserdetailsサービスに送信する方法を示しています。