企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
实现权限控制步骤如下: **1. 配置访问权限** ```java @Configuration public class SecurityConfig extends WebSecurityConfigurerAdapter { @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } @Override protected void configure(HttpSecurity http) throws Exception { http.formLogin() .loginPage("/to/login") .loginProcessingUrl("/login") .successForwardUrl("/success") .failureForwardUrl("/fail"); http.authorizeRequests() .antMatchers("/layui/**", "/to/login") .permitAll() //当用户有admin权限时才能访问/account/list01 .antMatchers("/account/list01").hasAuthority("admin") //当用户有admin02,或admin03权限时才能访问/account/list02 .antMatchers("/account/list02").hasAnyAuthority("admin02", "admin03") //当用户属于role角色时才能访问/account/list03,否则出现403页面 .antMatchers("/account/list03").hasRole("role") //当用户属于role02,或role03角色时才能访问 .antMatchers("/account/list04").hasAnyRole("role02", "role03") .anyRequest() .authenticated(); http.csrf().disable(); } } ``` **2. 在用户登录时加载当前用户所有的权限与角色** ```java @Service @RequiredArgsConstructor public class LoginServiceImpl implements UserDetailsService { final AccountService accountService; final MenuMapper menuMapper; final RoleMapper roleMapper; @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { Account account = accountService.findByUsername(username); if (account == null) { throw new UsernameNotFoundException("用户名不存在!"); } //从数据库中查询当前用户的权限与角色 List<Menu> menuList = menuMapper.findByAccountId(account.getId()); List<Role> roleList = roleMapper.findByAccountId(account.getId()); //存储权限与角色的集合 List<GrantedAuthority> authorities = new ArrayList<>(1); //处理权限 for (Menu menu : menuList) { authorities.add(new SimpleGrantedAuthority(menu.getPermission())); } //处理角色 for (Role role : roleList) { //角色必须以 ROLE_ 字符串为前缀 authorities.add(new SimpleGrantedAuthority("ROLE_" + role.getName())); } return new User(username, account.getPassword(), authorities); } } ``` **3. 测试** 登录之后,有权限访问的则正常访问,没有权限访问的返回403页面。 ``` Whitelabel Error Page This application has no explicit mapping for /error, so you are seeing this as a fallback. Fri Jun 10 20:21:37 CST 2022 There was an unexpected error (type=Forbidden, status=403). Forbidden ```