配置Spring以使用数据库进行身份验证

时间:2018-09-07 15:07:35

标签: java spring spring-boot spring-security spring-security-rest

我想配置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;
        }
    }

我有2个问题:

  1. 如何使用Merchant对象,但是Spring接受Object UserDetails。如何实现此功能?

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

2 个答案:

答案 0 :(得分:0)

您必须返回User类对象,该对象本身是UserDetails接口的实现。获得身份验证后,您将获得Merchants对象。您必须从中获取用户凭据以及角色。还有一个建议,尝试使类名保持单数。

public UserDetails loadUserByUsername(String username) {
 Merchants user = merchantsService.getCredentials(username, pwd);

        Set<GrantedAuthority> grantedAuthorities = new HashSet<>();
        for (Role role : user.getRoles()){
            grantedAuthorities.add(new SimpleGrantedAuthority(role.getName()));
        }

        return new User(user.getUsername(), user.getPassword(), grantedAuthorities);
}

您不需要自己进行密码匹配,Spring Security可以使用PasswordEncoder自己进行密码匹配。

有关更多详细信息,请访问以下链接。 https://hellokoding.com/registration-and-login-example-with-spring-security-spring-boot-spring-data-jpa-hsql-jsp/

答案 1 :(得分:0)

使用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可以提供密码。