2016-11-23 732 views
0

在我的春天啓動的應用程序,我將有兩種不同類型的用戶,即如何使用spring security來認證兩種不同類型的用戶?

  1. 管理員用戶
  2. 客戶

這些用戶將被存儲在兩個不同的表。 這兩個表格將只有電子郵件ID相同。其他一切都會有所不同。

另外,的客戶將會像1到5百萬個客戶那樣龐大。而另一方面,管理員用戶將少於10人。因此,這兩個不同的表。

我想要兩個不同的登錄頁面。一個在所有客戶的/客戶/登錄處,另一個在所有管理員的/ admin /登錄處。登錄詳細信息應使用各自的表進行驗證。在登錄時,客戶應該去/ customer/home,管理員應該去/ admin/home。

在註銷客戶應該被重定向到/客戶/用戶名和管理員/管理/登入

我用java配置爲春季安全。如何在春季安全中做到這一點?

下面是我的單用戶配置工作正常。

@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; 
    } 
} 
+0

@ J.West我一般只使用角色。但是,由於這些用戶完全不同,我們不希望將它們放在一起。最大管理員將有5列,客戶最少將有20-30列。所以,你看到那裏的差異。 – ashishjmeshram

+0

我不知道你會用什麼數據庫,但是對於主要提供者(Oracle,PostgreSQL,MariaDB)來說,AFAIK在記錄中有很多NULL列是沒有害處的。 –

+1

@ashishjmeshram下面的答案是我會建議的。就像他所說的,如果您將管理員用戶保留在同一個表中,並將所有多餘的列留爲「空」,則這沒有什麼不同。多個登錄頁面的另一個問題是,無法阻止某人訪問任何一個URI,並且如果用戶不是管理員,則無法登錄,但如果有人登錄該網頁,則仍然會令人困惑能夠登錄。 –

回答

2

爲Spring安全設置不同的登錄頁面是一個壞主意,因爲它不是它的設計方式。您將陷入麻煩,定義要使用的身份驗證入口點,並且需要大量沸騰盤。根據您的其他要求,我建議您通過以下方式:

  • 使用一個單一的AuthenticationManager一個單一的登錄頁面(默認ProviderManager將被罰款)
  • 有兩個不同的AuthenticationProvider•組態它,均爲DaoAuthenticationProvider,就你一個指向每個用戶2個表
  • 配置這些提供商自動設置不同的角色,ROLE_ADMIN對於前者將處理管理員,ROLE_USER後者

這樣,您完全依賴SpringSecurity基礎結構,儘可能少地修改以滿足您的要求。

但是你應該想知道你是否真的需要不同的數據庫。至少對於主要的提供者(Oracle,PostgreSQL,MariaDB等)來說,記錄中有許多空列是沒有害處的。恕我直言,你應該做一個認真的分析比較兩種方式,無論是單一的表(更簡單的設置爲春季安全)或兩個表。

+0

現在需求略有變化。客戶將使用其客戶ID登錄,而管理員用戶將使用電子郵件ID登錄。現在有什麼更好的方法? – ashishjmeshram

+0

@ashishjmeshram:恕我直言,它應該沒關係。登錄表單將接收一個id和一個密碼,2個'AuthenticationProvider'將嘗試處理它們,每個採取一個。您可以爲管理員提供有用評論的輔助表單,但只有一個應爲認證入口點,並且都應接受管理員或客戶憑證。 –

相關問題