繁体   English   中英

如何使用Spring Security验证两种不同类型的用户?

[英]How to use spring security to authenticate two different types of users?

在我的spring boot应用程序中,我将有两种不同类型的用户,即

  1. 管理员用户
  2. 顾客

这些用户将存储在两个不同的表中。 这两个表仅具有共同的电子邮件ID。 其他一切都会有所不同。

另外,没有。 的客户将是巨大的,如1-5百万客户。 另一方面,管理员用户很少,少于10个。因此,存在两个不同的表。

我想要两个不同的登录页面。 对于所有客户,一个在/ customer / login上,对于所有管理员,一个在/ admin / login上。 登录详细信息应使用其各自的表进行身份验证。 登录时,客户应转到/ customer / home,管理员应转到/ admin / home。

注销时,应将客户重定向到/ customer / login,将admin重定向到/ admin / login

我正在为春季安全使用Java配置。 在Spring Security中如何做到这一点?

以下是我的单用户配置,可以正常工作。

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private AccessDecisionManager accessDecisionManager;

    @Autowired
    private ApplicationProperties applicationProperties;

    @Bean
    public Integer applicationSessionTimeout(){
        return applicationProperties.getSecurity().getSessionTimeout();
    }

    @Bean
    @Autowired
    public AccessDecisionManager accessDecisionManager(AccessDecisionVoterImpl accessDecisionVoter) {
        List<AccessDecisionVoter<?>> accessDecisionVoters = new ArrayList<AccessDecisionVoter<?>>();
        accessDecisionVoters.add(new WebExpressionVoter());
        accessDecisionVoters.add(new AuthenticatedVoter());
        accessDecisionVoters.add(accessDecisionVoter);
        UnanimousBased accessDecisionManager = new UnanimousBased(accessDecisionVoters);
        return accessDecisionManager;
    }

    @Override
    @Autowired
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
    }

    @Bean
    public PasswordEncoder passwordEncoder(){
        PasswordEncoder passwordEncoder = new PasswordEncoder();
        passwordEncoder.setStringDigester(stringDigester());
        return passwordEncoder;
    }

    @Bean
    public PooledStringDigester stringDigester() {
        PooledStringDigester psd = new PooledStringDigester();

        psd.setPoolSize(2);
        psd.setAlgorithm("SHA-256");
        psd.setIterations(1000);
        psd.setSaltSizeBytes(16);
        psd.setSaltGenerator(randomSaltGenerator());

        return psd;
    }

    @Bean
    public RandomSaltGenerator randomSaltGenerator() {
        RandomSaltGenerator randomSaltGenerator = new RandomSaltGenerator();
        return randomSaltGenerator;
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring()
                .antMatchers("/static/**")
                .antMatchers("/i18n/**");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .exceptionHandling().
                accessDeniedPage("/accessDenied")
                .and()
            .authorizeRequests()
                .accessDecisionManager(accessDecisionManager)
                .antMatchers("/login**").permitAll()
                .antMatchers("/error**").permitAll()
                .antMatchers("/checkLogin**").permitAll()
                .anyRequest().fullyAuthenticated()
                .and()
            .formLogin()
                .loginPage("/login")
                .loginProcessingUrl("/checkLogin")
                .defaultSuccessUrl("/home?menu=homeMenuOption")
                .failureUrl("/login?login_error=1")
                .usernameParameter("username")
                .passwordParameter("password")
                .permitAll()
                .and()
            .logout()
                .logoutUrl("/logout")
                .logoutSuccessHandler(new LogoutSuccessHandlerImpl())
                .deleteCookies("JSESSIONID")
                .invalidateHttpSession(true)
                .permitAll()
                .and()
            .headers()
                .frameOptions()
                .disable()
            .and()
                .sessionManagement()
                .maximumSessions(1);
    }

}

下面是我的UserDetailsS​​ervice,它在db中检查正确的身份验证。

@Service("userDetailsService")
public class UserDetailsService implements org.springframework.security.core.userdetails.UserDetailsService {

    private static final Logger log = LoggerFactory.getLogger(UserDetailsService.class);

    @Autowired
    private UserService userService;

    @Autowired
    private ModuleService moduleService;

    @Override
    public UserDetails loadUserByUsername(final String userName) throws UsernameNotFoundException, DataAccessException {
        log.debug("Authenticating : {}", userName);

        SecurityUser securityUser = null;

        try {

            User user = userService.findUserByEmail(userName);

            if (user != null) {
                log.debug("User with the username {} FOUND ", userName);
                securityUser = new SecurityUser(user.getEmail(), user.getPassword(), true, true, true, true, getGrantedAuthorities(user.getRole().getId()));
                securityUser.setUser(user);
            } else {
                log.debug("User with the username {}  NOT FOUND", userName);
                throw new UsernameNotFoundException("Username not found.");
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }

        return securityUser;
    }

    private List<GrantedAuthority> getGrantedAuthorities(Long roleId) {
        log.debug("Populating user authorities");

        List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
        List<Module> allModules = moduleService.findAllModules();
        Map<Long, Module> moduleMap = new HashMap<Long, Module>();

        for(Module module : allModules){
            moduleMap.put(module.getModuleId(), module);
        }

        List<ModuleOperation> moduleOperationList = moduleService.findModuleOperationsByRoleId(roleId);

        for (ModuleOperation moduleOperation : moduleOperationList) {
            moduleOperation.setModuleName(moduleMap.get(moduleOperation.getModuleId()).getModuleName());
            authorities.add(moduleOperation);
        }

        return authorities;
    }
}

对于Spring安全性,拥有不同的登录页面确实是一个坏主意,因为这不是它设计的目的。 您将难以定义要使用的身份验证入口点,并且将需要很多沸腾的盘子。 根据您的其他要求,我建议您采取以下方式:

  • 使用一个登录页面和一个AuthenticationManager (默认的ProviderManager会很好)
  • 使用两个不同的AuthenticationProvider对其进行配置,这两个都是DaoAuthenticationProvider ,每个都指向您2个用户表之一
  • 配置这些提供程序以自动设置不同的角色,ROLE_ADMIN为前者处理管理员,ROLE_USER为后者

这样,您就可以完全依靠SpringSecurity基础结构,并进行尽可能少的修改以满足您的需求。

但是您还应该怀疑您是否真的需要其他数据库。 至少对于主要提供程序(Oracle,PostgreSQL,MariaDB等)而言,在记录中包含许多空列没有什么害处。 恕我直言,您应该进行认真的分析以比较这两种方式,一个表(对于Spring Security而言,它更容易设置)或两个表。

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM