springboot + shiro + thymeleaf 实现按钮级权限控制 解决按钮的显示

1:第一步创建 权限拦截策略类

import com.example.demo.entity.PageData;
import com.example.demo.service.IBuserService;
import com.example.demo.service.MenuService;
import com.example.demo.util.SpringContextUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.PathMatchingFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.util.List;

/**
 *  权限 拦截策略
 */
public class MyAccessControlFilter  extends PathMatchingFilter  {
    private Logger logger =  LoggerFactory.getLogger(this.getClass());  

       //相关service
    @Autowired
    private IBuserService userService;

        //相关service
    @Autowired
    private MenuService menuService;

       //自定义Realm类
    @Autowired
    private CustomRealm customRealm;
    @Override
    protected boolean onPreHandle(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {

        //注意这个不能省略,否则注入可能为空  SpringContextUtil.工具类可以复制第四

        if (userService==null){
            userService= SpringContextUtil.getBean(IBuserService.class);
        }
        if (menuService==null){
            menuService= SpringContextUtil.getBean(MenuService.class);
        }
        
        if (customRealm==null){
            customRealm= SpringContextUtil.getBean(CustomRealm.class);
        }
        //请求的url
        String requestURL = getPathWithinApplication(request);
        System.out.println("请求的url :"+requestURL);

        //判断是否登录
        Subject subject = SecurityUtils.getSubject();
        if (!subject.isAuthenticated()){
            // 如果没有登录, 直接返回true 进入登录流程
            request.getRequestDispatcher("/login.html").forward(request, response);
            return  true;
        }

        //获取账户
        String account = (String)subject.getPrincipal();

        //此处pageData只是个通用实体类
        PageData accountData= userService.getAccount(account);

        //用户id
        Long userId = (Long)accountData.get("user_id");

       // 获取所有权限  
        List<PageData> permissions =(List<PageData>)menuService.queryAllPerms(userId);


        for (PageData pd : permissions) {
            //根据菜单id查询路径
            PageData menu = menuService.getMenuById(pd);
              if (menu.getString("path").equals(requestURL)){

                //获取访菜单id
                Integer  menu_id=(Integer)menu.get("id");

                //通过方法调用再次调用自定义CustomRealm 的doGetAuthorizationInfo
                AuthorizationInfo info =       customRealm.getInfo(SecurityUtils.getSubject().getPrincipals(),menu_id) ;

            hasPermission=true;
                  break;
              }

         hasPermission=true;
        }
        
           

 if (hasPermission){
            return true;
        }else {
            UnauthorizedException ex = new UnauthorizedException("当前用户没有访问路径" + requestURL + "的权限");
            subject.getSession().setAttribute("ex",ex);
            WebUtils.issueRedirect(request, response,

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Spring BootShiro 都是非常流行的Java开发框架。其中,Spring Boot是一个快速开发框架,能够快速地搭建一个Web应用程序;而Shiro是一个强大的安全框架,提供了认证、授权、加密、会话管理等安全相关的功能。 下面是实现Spring BootShiro权限管理的步骤: 1. 引入依赖 在pom.xml文件中引入Spring BootShiro的依赖。 ``` <!-- Spring Boot --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- Shiro --> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-spring</artifactId> <version>1.7.0</version> </dependency> ``` 2. 编写Shiro配置类 编写一个Shiro配置类,用于配置Shiro的安全管理器、Realm、过滤器等。 ``` @Configuration public class ShiroConfig { @Bean public ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityManager securityManager) { ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean(); shiroFilterFactoryBean.setSecurityManager(securityManager); // 设置过滤器链 Map<String, String> filterChainDefinitionMap = new LinkedHashMap<>(); filterChainDefinitionMap.put("/login", "anon"); filterChainDefinitionMap.put("/logout", "logout"); filterChainDefinitionMap.put("/**", "authc"); shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap); // 登录页面 shiroFilterFactoryBean.setLoginUrl("/login"); // 认证成功后跳转页面 shiroFilterFactoryBean.setSuccessUrl("/index"); // 未授权页面 shiroFilterFactoryBean.setUnauthorizedUrl("/unauthorized"); return shiroFilterFactoryBean; } @Bean public SecurityManager securityManager() { DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager(); securityManager.setRealm(realm()); return securityManager; } @Bean public Realm realm() { return new MyRealm(); } } ``` 3. 编写Realm 编写一个Realm类,用于进行认证和授权。 ``` public class MyRealm extends AuthorizingRealm { @Autowired private UserService userService; // 认证 @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException { UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken; String username = token.getUsername(); User user = userService.getUserByUsername(username); if (user == null) { throw new UnknownAccountException("用户不存在"); } return new SimpleAuthenticationInfo(user.getUsername(), user.getPassword(), getName()); } // 授权 @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) { String username = (String) principalCollection.getPrimaryPrincipal(); User user = userService.getUserByUsername(username); SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo(); authorizationInfo.addRoles(user.getRoles()); authorizationInfo.addStringPermissions(user.getPermissions()); return authorizationInfo; } } ``` 4. 编写Controller 编写一个Controller类,用于处理用户登录、登出等请求。 ``` @Controller public class LoginController { @GetMapping("/login") public String login() { return "login"; } @PostMapping("/login") public String doLogin(String username, String password, boolean rememberMe) { Subject subject = SecurityUtils.getSubject(); UsernamePasswordToken token = new UsernamePasswordToken(username, password); token.setRememberMe(rememberMe); try { subject.login(token); return "redirect:/index"; } catch (AuthenticationException e) { return "login"; } } @GetMapping("/logout") public String logout() { Subject subject = SecurityUtils.getSubject(); subject.logout(); return "redirect:/login"; } @GetMapping("/index") public String index() { return "index"; } @GetMapping("/unauthorized") public String unauthorized() { return "unauthorized"; } } ``` 5. 编写页面 编写登录页面、首页、未授权页面等页面。 ``` <!-- 登录页面 --> <form method="post" action="/login"> <input type="text" name="username" placeholder="用户名" required> <input type="password" name="password" placeholder="密码" required> <div> <input type="checkbox" name="rememberMe" id="rememberMe"> <label for="rememberMe">记住我</label> </div> <button type="submit">登录</button> </form> <!-- 首页 --> <h1>欢迎访问首页</h1> <!-- 未授权页面 --> <h1>您有访问该页面的权限</h1> ``` 以上就是Spring BootShiro权限管理的实现步骤。通过配置Shiro的安全管理器、Realm、过滤器等,可以实现用户认证和授权。同时,通过在Controller中处理用户登录、登出等请求,可以实现用户的登录和退出功能。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

删除偶的记忆

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值