实现用户根据角色登录不同的页面,可以按照以下步骤进行:
- 在数据库中创建用户表和角色表,并建立用户与角色之间的关联关系。
- 使用Spring Security框架来实现用户认证和授权。在Spring Boot项目中添加Spring Security依赖,配置WebSecurityConfigurerAdapter类,定义登录页面、登出页面、权限等。
- 创建多个Controller类,分别对应各个角色的页面。在Controller类中使用@PreAuthorize注解或者方法级别的@Secured注解来限制访问权限。
- 在登录成功后,根据用户所属的角色跳转到对应的Controller类处理请求。
下面是一个简单示例:
- 创建用户表和角色表
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
@EnableWebSecurity
public 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/";
}
}