programing

사용자 지정 사용자 세부 정보 서비스를 사용한 봄 부팅

linuxpc 2023. 6. 30. 22:08
반응형

사용자 지정 사용자 세부 정보 서비스를 사용한 봄 부팅

사용자 세부 정보 서비스(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도움이 될 경우: https://github.com/scratches/jpa-method-security-sample

또한 이 블로그를 따라 사용자 세부 정보 서비스를 구현할 수 있습니다.

이 예는 주입을 위해 사용자 세부 정보 서비스로 빈을 전송하는 방법을 보여줍니다.

  1. WebSecurityConfigurer에서 리포지토리 자동 배선
  2. 매개 변수화된 생성자가 이 빈을 사용자 세부 정보 서비스에 매개 변수로 보냅니다.
  3. 개인 구성원을 할당하고 데이터베이스에서 사용자를 로드하는 데 사용합니다.

언급URL : https://stackoverflow.com/questions/24723201/spring-boot-with-custom-userdetailsservice

반응형