Java 如何使用spring安全性对两种不同类型的用户进行身份验证?
在我的spring boot应用程序中,我将有两种不同类型的用户,即Java 如何使用spring安全性对两种不同类型的用户进行身份验证?,java,spring,spring-mvc,spring-security,Java,Spring,Spring Mvc,Spring Security,在我的spring boot应用程序中,我将有两种不同类型的用户,即 管理员用户 顾客 这些用户将存储在两个不同的表中。 这两个表只有共同的电子邮件id。其他一切都将不同 此外,客户数量将非常庞大,大约有100万到500万客户。而另一方面,管理员用户将非常少,比如少于10个。因此,两个不同的表 我想有两个不同的登录页面。一个at/customer/login代表所有客户,另一个at/admin/login代表所有管理员。登录详细信息应使用各自的表进行身份验证。登录时,客户应转到/customer
@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);
}
}
@配置
@启用Web安全性
@EnableGlobalMethodSecurity(Prespenabled=true,securedEnabled=true)
公共类WebSecurityConfig扩展了WebSecurityConfigureAdapter{
@自动连线
私有用户详细信息服务用户详细信息服务;
@自动连线
私人访问决策管理器访问决策管理器;
@自动连线
私有应用程序属性应用程序属性;
@豆子
公共整数应用程序会话超时(){
返回applicationProperties.getSecurity().getSessionTimeout();
}
@豆子
@自动连线
公共访问决策管理器访问决策管理器(AccessDecisionVoterImpl accessDecisionVoter){
列表>();
accessDecisionVorters.add(新WebExpressionVorter());
accessDecisionVorters.add(新的AuthenticatedVorter());
accessDecisionVorters.add(accessDecisionVorter);
UnanimousBased accessDecisionManager=新的UnanimousBased(accessdecisionvotters);
返回访问决策管理器;
}
@凌驾
@自动连线
受保护的无效配置(AuthenticationManagerBuilder auth)引发异常{
auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
}
@豆子
公共密码编码器PasswordEncoder(){
PasswordEncoder PasswordEncoder=新的PasswordEncoder();
passwordEncoder.setStringDigester(stringDigester());
返回密码编码器;
}
@豆子
公共池stringDigester stringDigester(){
PooledStringDigester psd=新的PooledStringDigester();
psd.setPoolSize(2);
psd.SET算法(“SHA-256”);
私营部门司(1000);
psd.setSaltSizeBytes(16);
psd.setSaltGenerator(randomSaltGenerator());
返回psd;
}
@豆子
公共随机SaltGenerator随机SaltGenerator(){
RandomSaltGenerator RandomSaltGenerator=新的RandomSaltGenerator();
返回随机数发生器;
}
@凌驾
public void configure(WebSecurity web)引发异常{
忽略
.antMatchers(“/static/**”)
.antMatchers(“/i18n/**”);
}
@凌驾
受保护的无效配置(HttpSecurity http)引发异常{
http
.异常处理()。
accessDeniedPage(“/accessDeniedPage”)
.及()
.授权请求()
.accessDecisionManager(accessDecisionManager)
.antMatchers(“/login**”).permitAll()
.antMatchers(“/error**”).permitAll()
.antMatchers(“/checkLogin**”).permitAll()
.anyRequest().fullyAuthenticated()
.及()
.formLogin()
.login页面(“/login”)
.loginProcessingUrl(“/checkLogin”)
.defaultSuccessUrl(“/home?menu=homeMenuOption”)
.failureUrl(“/login?login\u error=1”)
.usernameParameter(“用户名”)
.passwordParameter(“密码”)
.permitAll()
.及()
.logout()
.logoutUrl(“/logout”)
.logoutSuccessHandler(新的LogoutSuccessHandlerImpl())
.deleteCookies(“JSSessionID”)
.invalidateHttpSession(真)
.permitAll()
.及()
.headers()
.frameOptions()
.disable()
.及()
.会议管理()
.最多会议(1);
}
}
下面是我的UserDetailsService,它检查数据库中的身份验证是否正确
@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;
}
}
@Service(“userdetailssservice”)
公共类UserDetailsService实现org.springframework.security.core.userdetails.UserDetailsService{
私有静态最终记录器log=LoggerFactory.getLogger(UserDetailsService.class);
@自动连线
私人用户服务;
@自动连线
专用模块服务模块服务;
@凌驾
public UserDetails loadUserByUsername(最终字符串用户名)抛出UsernameNotFoundException、DataAccessException{
调试(“身份验证:{}”,用户名);
SecurityUser SecurityUser=null;
试一试{
User=userService.findUserByEmail(用户名);
如果(用户!=null){
debug(“用户名为{}的用户”,用户名);
securityUser=newsecurityuser(user.getEmail(),user.getPassword(),true,true,true,getgrantedAuthories(user.getRole().getId());
securityUser.setUser(用户);
}否则{
debug(“未找到用户名为{}的用户”,用户名);
抛出新的UsernameNotFoundException(“找不到用户名”);
}
}捕获(例外e){
log.error(e.getMessage(),e);
}
返回securityUser;
}
私有列表GetGrantedAuthories(长角色ID){
log.debug(“Populatin