简体   繁体   English

使用自定义UserDetailsS​​ervice进行Spring Boot

[英]Spring Boot with custom UserDetailsService

What is the correct way to add my custom implementation of UserDetailsService (which uses Spring Data JPA) to Spring Boot app? 将我自己的UserDetailsS​​ervice(使用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 ) 我无法启动app beacouse我得到(完全例外这里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. 当我使用auth.jdbcAuthentication().dataSource(dataSource).usersByUsernameQuery("...).authoritiesByUsernameQuery("...")配置我的ApplicationSecurity ,一切正常,包括JPA和Spring Data存储库。

Your app seems to work for me (once I added @Configuration to the AuthenticationSecurity ). 您的应用似乎对我@Configuration (一旦我将@Configuration添加到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 这是JPA UserDetailsService的一个简单应用程序的另一个工作示例,以防它有用: https//github.com/scratches/jpa-method-security-sample

You can also follow this blog to implement custom user details service. 您还可以关注此博客以实现自定义用户详细信息服务。

This example shows how you can send bean to userdetails service for injection. 此示例显示如何将bean发送到userdetails服务以进行注入。

  1. Autowire the Repository in the WebSecurityConfigurer 在WebSecurityConfigurer中自动装配存储库
  2. Send this bean as a parameter to the user details service by a parameterized constructor. 通过参数化构造函数将此bean作为参数发送到用户详细信息服务。
  3. assign this a private member and use to load users from database. 为此分配一个私有成员并用于从数据库加载用户。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 spring-boot 未调用自定义 UserDetailsService - Custom UserDetailsService is not called by spring-boot Spring Boot:使用自定义UserDetailsS​​ervice配置AuthenticationManager - Spring Boot: Configuring AuthenticationManager with custom UserDetailsService Autowire不适用于Spring Boot中的自定义UserDetailsS​​ervice - Autowire doesn't work for custom UserDetailsService in Spring Boot Spring Boot OAuth2具有基本身份验证和自定义UserDetailsS​​ervice - Spring Boot OAuth2 with basic authentication and custom UserDetailsService 春季启动:在自定义UserDetailsS​​ervice中自动装配authenticationManager时,委托构建器不能为null - Spring boot : delegateBuilder cannot be null on autowiring authenticationManager in custom UserDetailsService Spring 引导表单登录自定义用户详细信息服务授权不起作用 - Spring Boot Form Login Custom UserDetailsService authorisation not working 未调用自定义 Spring UserDetailsS​​ervice - Custom Spring UserDetailsService not called 如何使用自定义UserDetailsS​​ervice和密码验证来配置Spring Boot OAuth2.0服务器? - How to configure Spring Boot OAuth2.0 server with custom UserDetailsService and password validation? 永远不会调用UserDetailsS​​ervice(Spring启动安全性) - UserDetailsService is never called(Spring boot security) @EJB注入到Custom UserdetailsS​​ervice中(实现Spring Security UserDetailsS​​ervice) - @EJB injection in a Custom UserdetailsService (implementing Spring Security UserDetailsService)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM