0

我想将 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)只能接受用户名。还有其他方法可以实现代码吗?

4

2 回答 2

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 会处理它。

于 2018-09-08T17:26:47.910 回答
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/

于 2018-09-07T17:37:03.907 回答