首页 > 解决方案 > 配置 Spring 以使用数据库进行身份验证

问题描述

我想将 Spring Security 配置为使用数据库来处理 Rest api 请求。我试过这个:

    @Configuration
    @EnableWebSecurity
    @Import(value= {Application.class, ContextDatasource.class})
    @ComponentScan(basePackages= {"org.rest.api.server.*"})
    public class ApplicationSecurityConfig extends WebSecurityConfigurerAdapter {

        @Autowired 
        private RestAuthEntryPoint authenticationEntryPoint;

        @Autowired
        MyUserDetailsService myUserDetailsService;

        @Autowired
        public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
    //      auth
    //      .inMemoryAuthentication()
    //      .withUser("test")
    //      .password(passwordEncoder().encode("testpwd"))
    //      .authorities("ROLE_USER");
            auth.userDetailsService(myUserDetailsService);
            auth.authenticationProvider(authenticationProvider());
        }
        @Bean
        public DaoAuthenticationProvider authenticationProvider() {
            DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider();
            authenticationProvider.setUserDetailsService(myUserDetailsService);
            authenticationProvider.setPasswordEncoder(passwordEncoder());
            return authenticationProvider;
        }
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http
            .authorizeRequests()
            .antMatchers("/securityNone")
            .permitAll()
            .anyRequest()
            .authenticated()
            .and()
            .httpBasic()
            .authenticationEntryPoint(authenticationEntryPoint);
        }
        @Bean
        public PasswordEncoder passwordEncoder() {
            return NoOpPasswordEncoder.getInstance();
        }
    }

服务:

    public interface MerchantsService {

        public Merchants getCredentials(String login, String pwd) throws Exception;
    }

服务实施

@Service
@Qualifier("merchantsService")
@Transactional
public class MerchantsServiceImpl implements MerchantsService {

    @Autowired
    private EntityManager entityManager;

    @Override
    public Merchants getCredentials(String login, String pwd) throws Exception {
        String hql = "select e from " + Merchants.class.getName() + " e where e.login = ? and e.pwd = ?";

        Query query = entityManager.createQuery(hql).setParameter(0, login).setParameter(1, pwd);
        Merchants merchants = (Merchants) query.getSingleResult();

        return merchants;
    }
}



    @Service
    public class MyUserDetailsService implements UserDetailsService {

        @Autowired
        private MerchantsService merchantsService;

        @Override
        public Merchants loadUserByUsername(String username) {
            Merchants user = merchantsService.getCredentials(username, pwd);
            if (user == null) {
                throw new UsernameNotFoundException(username);
            }
            return user;
        }
    }

我有两个问题:

  1. 我如何使用 Merchant 对象但 Spring 接受 Object UserDetails。我怎样才能实现这个功能?

  2. 如何使用用户名和密码验证请求。我看到public UserDetails loadUserByUsername(String username)只能接受用户名。还有其他方法可以实现代码吗?

标签: javaspringspring-bootspring-securityspring-security-rest

解决方案


当您使用 Spring Security 时,您必须实现一个实现UserDetailsS​​ervice的服务以及返回 UserDetails 的相应 loadUserByUsername 方法。这是一个示例方法:

@Override
  public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    User user = this.getUserByUsername(username); // getting the user from the database with our own method
    return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), new ArrayList<>());
  }

您不必担心验证密码,因为 Spring Security 会处理它。


推荐阅读