用户可以根据角色登录不同的页面,并遵循以下步骤:
- 在数据库中创建用户表和角色表,并建立用户与角色之间的关系。
- 使用Spring 实现用户认证和授权的Security框架。 在Boot项目中添加Spring 依赖Security,配置websecurityconfigureradapter类,定义登录页面、登录页面、权限等。
- 创建多个Controller类别,对应每个角色的页面。在Controler类别中,使用@Preauthorize注释或方法级别的@Secured注释来限制访问权限。
- 登录成功后,根据用户所属角色跳转到相应的Controler类处理请求。
以下是一个简单的例子:
- 创建用户表和角色表
CREATE TABLE `user` ( `id` int(11) NOT NULL AUTO_INCREMENT, `username` varchar(50) NOT NULL, `password` varchar(100) NOT NULL, PRIMARY KEY (`id`));CREATE TABLE `role` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(50) NOT NULL, PRIMARY KEY (`id`));CREATE TABLE `user_role` ( `user_id` int(11) NOT NULL, `role_id` int(11) NOT NULL, PRIMARY KEY (`user_id`,`role_id`), CONSTRAINT `fk_user_role_user_id` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT `fk_user_role_role_id` FOREIGN KEY (`role_id`) REFERENCES `role` (`id`) ON DELETE CASCADE ON UPDATE CASCADE);
- 添加Spring 依赖Security,配置WebSecurityconfigureradapter类
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId></dependency>
@Configuration@EnableWebSecuritypublic class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private UserDetailsService userDetailsService; @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/admin/**").hasRole("ADMIN") .antMatchers("/user/**").hasAnyRole("USER", "ADMIN") .anyRequest().authenticated() .and() .formLogin().loginPage("/login").permitAll() .and() .logout().permitAll(); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder()); } @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); }}
- 创建多个Controller类,对应每个角色的页面
@Controller@RequestMapping("/admin")@PreAuthorize("hasRole('ADMIN')")public class AdminController { @GetMapping("/") public String index() { return "admin/index"; }}@Controller@RequestMapping("/user")public class UserController { @GetMapping("/") public String index() { return "user/index"; }}
- 登录成功后,根据用户所属角色跳转到相应的Controller处理请求
@GetMapping("/")public String index(Model model, Authentication authentication) { UserDetails userDetails = (UserDetails) authentication.getPrincipal(); Set<String> roles = AuthorityUtils.authorityListToSet(userDetails.getAuthorities()); if (roles.contains("ROLE_ADMIN")) { return "redirect:/admin/"; } else { return "redirect:/user/"; }}
