当前位置:   article > 正文

青锋开源架构-springboot2.6.x+vue3-antdesign-vite之springsecurity实现访问权限控制_vue带有权限的框架开源

vue带有权限的框架开源

框架开源地址:

青锋开源架构-springboot2.6.x+vue3-antdesign-vite: 青锋-springboot2.6.x+vue3-antdesign-vite开源架构,实现了系统管理模块、权限控制模块(菜单权限、功能按钮权限、数据权限)、代码生成器(单表、树表)、quartz动态定时器等功能。

权限访问控制讲解

GrantedAuthority接口

Spring Security中有一些概念和实现,例如GrantedAuthority用于获得授权来授权/控制访问权限的接口。

我希望对允许的操作(例如userList或user:del)进行允许,这些操作将允许管理员(具有role ROLE_ADMIN)使用。

通过查看org.springframework.security.core.userdetails.UserDetails了身份验证提供程序引用的DAO中使用的接口,该接口消耗了User(请注意最后的GrantedAuthority):

  1. public User(String username,
  2. String password,
  3. boolean enabled,
  4. boolean accountNonExpired,
  5. boolean credentialsNonExpired,
  6. boolean accountNonLocked,
  7. Collection<? extends GrantedAuthority> authorities)

当用户执行登录验证之后,查询对应的权限集合authorities,将权限集合返回到User对象中。

获取用户权限集合

我们可以通过userDetailsService.loadUserByUsername("admin").getAuthorities()获取用户的权限信息,这里的权限信息就是上面讲解的authorities设置的权限信息。

userDetailsService.loadUserByUsername("admin").getAuthorities()

项目中如何使用?

配置权限身份认证

我们在SecurityConfigure中设置权限的身份认证,如下:

  1. @Override
  2. protected void configure(AuthenticationManagerBuilder auth) throws Exception {
  3. auth.userDetailsService(userDetailService).passwordEncoder(passwordEncoder);
  4. }

加载用户权限

我们通过查询当前登录用户的权限信息,并将权限信息返回到User中。

  1. List<GrantedAuthority> grantedAuthorityList = AuthorityUtils.commaSeparatedStringToAuthorityList(permissions);
  2. AuthUser authUser = new AuthUser(uPd.get("login_name").toString()+":"+uPd.get("id").toString()+":"+organize_id, uPd.get("login_password").toString(), true, true, true, notLocked,
  3. grantedAuthorityList);

AuthUser继承了User接口,我们通过查看User构造方法如下:

详细代码如下:

  1. @Override
  2. public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
  3. PageData pd = new PageData();
  4. if(username.contains(":")){
  5. pd.put("login_name",username.split(":")[0]);
  6. }else{
  7. pd.put("login_name",username);
  8. }
  9. PageData uPd = userManager.findUserInfo(pd);
  10. System.out.println(uPd);
  11. if(Verify.verifyIsNotNull(uPd)){
  12. System.out.println(uPd.get("status"));
  13. if(uPd.get("status").equals("2")){
  14. throw new UsernameNotFoundException("账号已休眠,请联系管理员");
  15. }else{
  16. if(uPd.get("status").equals("0")){
  17. //查询当前用户组织
  18. pd.put("user_id",uPd.get("id"));
  19. PageData orgPd = userManager.findUserOrganizeInfo(pd);
  20. String organize_id = "";
  21. if(Verify.verifyIsNotNull(orgPd)){
  22. organize_id = orgPd.get("organize_id")+"";
  23. }
  24. //登录成功
  25. pd.put("user_id",uPd.get("id"));
  26. String permissions = userManager.findUserPermissions(pd);
  27. // System.out.println("===================================查询出来数据权限==============================");
  28. // System.out.println(permissions);
  29. boolean notLocked = false;
  30. if (StringUtils.equals("0", uPd.get("status").toString()))
  31. notLocked = true;
  32. List<GrantedAuthority> grantedAuthorityList = AuthorityUtils.commaSeparatedStringToAuthorityList(permissions);
  33. AuthUser authUser = new AuthUser(uPd.get("login_name").toString()+":"+uPd.get("id").toString()+":"+organize_id, uPd.get("login_password").toString(), true, true, true, notLocked,
  34. grantedAuthorityList);
  35. return transToAuthUser(authUser,uPd);
  36. }else if(uPd.getString("status").equals("1")){
  37. throw new UsernameNotFoundException("账号已禁用,请联系管理员");
  38. }else if(uPd.getString("status").equals("2")){
  39. throw new UsernameNotFoundException("账号已休眠,请联系管理员");
  40. }
  41. }
  42. return null;
  43. }else{
  44. throw new UsernameNotFoundException("登录名称不存在,请重新输入。");
  45. }
  46. }

权限SQL数据

通过SQL可以看到,数据权限perms的权限是通过父节点菜单的权限标识符:按钮功能权限标识符,比如用户的查看、新增、编辑、删除方法:

  1. user:info
  2. user:add
  3. user:edit
  4. user:del

请求方法增加权限控制

请求方法中,通过增加注解:@PreAuthorize("hasAnyAuthority('xxx:xxx')")进行权限控制:

@PreAuthorize("hasAnyAuthority('xxx:xxx')")

下面以系统用户权限控制方法进行讲解:

  1. /**
  2. * @title listPage
  3. * @description 查询数据分页列表
  4. * @author Administrator
  5. * @updateTime 2022/1/19 0019 23:41
  6. */
  7. @GetMapping("/listPage")
  8. @PreAuthorize("hasAnyAuthority('user:info')")
  9. public MyResponse listPage(QueryRequest queryRequest, Area area) {
  10. String userParams = SecurityContextHolder.getContext().getAuthentication().getName();
  11. return new MyResponse().data(dataTable);
  12. }
  13. /**
  14. * @title save
  15. * @description 保存数据
  16. * @author Administrator
  17. * @updateTime 2022/1/19 0019 23:41
  18. */
  19. @PostMapping
  20. @PreAuthorize("hasAnyAuthority('user:add')")
  21. public void save(@Valid @RequestBody Area area,HttpServletResponse response) throws Exception {
  22. this.writeJson(response,json);
  23. }
  24. /**
  25. * @title update
  26. * @description 更新数据
  27. * @author Administrator
  28. * @updateTime 2022/1/19 0019 23:41
  29. */
  30. @PutMapping
  31. @PreAuthorize("hasAnyAuthority('user:edit')")
  32. public void update(@Valid @RequestBody Area area,HttpServletResponse response) throws Exception {
  33. Json json = new Json();
  34. this.writeJson(response,json);
  35. }
  36. /**
  37. * @title delete
  38. * @description 删除数据
  39. * @author Administrator
  40. * @updateTime 2022/1/19 0019 23:41
  41. */
  42. @DeleteMapping("/{ids}")
  43. @PreAuthorize("hasAnyAuthority('user:del')")
  44. public void delete(@NotBlank(message = "{required}") @PathVariable String ids,HttpServletResponse response) throws Exception {
  45. Json json = new Json();
  46. this.writeJson(response,json);
  47. }
  48. /**
  49. * @title updateStatus
  50. * @description 更新状态
  51. * @author Administrator
  52. * @updateTime 2022/1/19 0019 23:41
  53. */
  54. @PostMapping("/updateStatus")
  55. @PreAuthorize("hasAnyAuthority('user:status')")
  56. public void updateStatus(@Valid @RequestBody Area area,HttpServletResponse response) throws Exception {
  57. Json json = new Json();
  58. this.writeJson(response,json);
  59. }

菜单和按钮权限标识设置

看到这里,大家可能会有疑问,上面提到的user:add,用户菜单user和添加按钮add在哪里设置的呢?

本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号