用户权限管理一般是对用户页面、按钮的访问权限管理。Shiro框架是一个强大且易用的Java安全框架,执行身份验证、授权、密码和会话管理,对于Shiro的介绍这里就不多说。本篇博客主要是了解Shiro的基础使用方法,在权限管理系统中集成Shiro实现登录、url和页面按钮的访问控制。

一、引入依赖

使用SpringBoot集成Shiro时,在pom.xml中可以引入shiro-spring-boot-web-starter。由于使用的是thymeleaf框架,thymeleaf与Shiro结合需要 引入thymeleaf-extras-shiro。

<!-- https://mvnrepository.com/artifact/org.apache.shiro/shiro-spring-boot-web-starter -->
  <dependency>
    <groupId>org.apache.shiro</groupId>
    <artifactId>shiro-spring-boot-web-starter</artifactId>
    <version></version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.github.theborakompanioni/thymeleaf-extras-shiro -->
<dependency>
    <groupId>com.github.theborakompanioni</groupId>
    <artifactId>thymeleaf-extras-shiro</artifactId>
    <version></version>
</dependency>

二、增加Shiro配置

有哪些url是需要拦截的,哪些是不需要拦截的,登录页面、登录成功页面的url、自定义的Realm等这些信息需要设置到Shiro中,所以创建Configuration文件ShiroConfig。

package com.example.config;

@Configuration
public class ShiroConfig {
    @Bean("shiroFilterFactoryBean")
    public ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityManager securityManager) {
        System.out.println("ShiroConfiguration.shirFilter()");
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        shiroFilterFactoryBean.setSecurityManager(securityManager);
        //拦截器.
        Map<String,String> filterChainDefinitionMap = new LinkedHashMap<String,String>();
        // 配置不会被拦截的链接 顺序判断
        filterChainDefinitionMap.put("/static/**", "anon");
        //配置退出 过滤器,其中的具体的退出代码Shiro已经替我们实现了
        filterChainDefinitionMap.put("/logout", "logout");
        //<!-- 过滤链定义,从上向下顺序执行,一般将/**放在最为下边 -->:这是一个坑呢,一不小心代码就不好使了;
        //<!-- authc:所有url都必须认证通过才可以访问; anon:所有url都都可以匿名访问-->
        filterChainDefinitionMap.put("/**", "authc");
        // 如果不设置默认会自动寻找Web工程根目录下的"/login.jsp"页面
        shiroFilterFactoryBean.setLoginUrl("/login");
        // 登录成功后要跳转的链接
        shiroFilterFactoryBean.setSuccessUrl("/index");

        //未授权界面;
        shiroFilterFactoryBean.setUnauthorizedUrl("/403");
        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
        return shiroFilterFactoryBean;
    }

    @Bean(name="defaultWebSecurityManager")    //创建DefaultWebSecurityManager
    public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm")MyShiroRealm userRealm){
        DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();
        defaultWebSecurityManager.setRealm(userRealm);
        return defaultWebSecurityManager;

    }
    //创建Realm
    @Bean(name="userRealm")
    public MyShiroRealm getUserRealm(){
        return new MyShiroRealm();
    }

    @Bean
    public ShiroDialect shiroDialect() {
        return new ShiroDialect();
    }
}

ShiroDialect这个bean对象是在thymeleaf与Shiro结合,前端html访问Shiro时使用。

三、自定义Realm

在自定义的Realm中继承了AuthorizingRealm抽象类,重写了两个方法:doGetAuthorizationInfo和doGetAuthenticationInfo。doGetAuthorizationInfo主要是用来处理权限配置,doGetAuthenticationInfo主要处理身份认证。这里在doGetAuthorizationInfo中,将role表的id和permission表的code分别设置到SimpleAuthorizationInfo对象中的role和permission中。还有一个地方需要注意:@Component("authorizer"),刚开始我没设置,但报错提示需要一个authorizer的bean,查看AuthorizingRealm可以发现它implements了Authorizer,所以在自定义的realm上添加@Component("authorizer")就可以了。

package com.example.config;

@Component("authorizer")
public class MyShiroRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        System.out.println("权限配置-->MyShiroRealm.doGetAuthorizationInfo()");
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        User user = (User)principals.getPrimaryPrincipal();
        System.out.println("User:"+user.toString()+" roles count:"+user.getRoles().size());
        for(Role role:user.getRoles()){
            authorizationInfo.addRole(role.getId());
            role=roleService.getRoleById(role.getId());
            System.out.println("Role:"+role.toString());
            for(Permission p:role.getPermissions()){
                System.out.println("Permission:"+p.toString());
                authorizationInfo.addStringPermission(p.getCode());
            }
        }
        System.out.println("权限配置-->authorizationInfo"+authorizationInfo.toString());
        return authorizationInfo;
    }

    /*主要是用来进行身份认证的,也就是说验证用户输入的账号和密码是否正确。*/
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token)
            throws AuthenticationException {
        System.out.println("MyShiroRealm.doGetAuthenticationInfo()");
          //获取用户的输入的账号.
        String username = (String)token.getPrincipal();
        System.out.println(token.getCredentials());
          //通过username从数据库中查找 User对象,如果找到,没找到.
          //实际项目中,这里可以根据实际情况做缓存,如果不做,Shiro自己也是有时间间隔机制,2分钟内不会重复执行该方法
        User user = userService.getUserById(username);
        System.out.println("----->>userInfo="+user);
        if(user == null){
            return null;
        }
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
                user, //用户名
                ", //密码
                getName() //realm name
        );
        return authenticationInfo;
    }

四、登录认证

1.登录页面

这里做了一个非常丑的登录页面,主要是自己懒,不想在网上复制粘贴找登录页面了。

<!DOCTYPE html>
<head>
    <meta charset="utf-8">
    <title></title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <meta name="apple-mobile-web-app-status-bar-style" content="black">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="format-detection" content="telephone=no">
</head>

<form action="/login" method="post">
      <label>用户名:</label><input type="text" name="id"   id="id" ><br>
      <label >密码:</label><input type="text" name="pwd"  id="pwd" ><br>
      <button type="submit">登录</button><button type="reset">取消</button>
</form>
</body>
</html>

2.处理登录请求

在LoginController中通过登录名、密码获取到token实现登录。

package com.example.controller;

@Controller
public class LoginController {

    //退出的时候是get请求,主要是用于退出
    @RequestMapping(value = "/login",method = RequestMethod.GET)
    public String login(){
        return "login";
    }

    //post登录
    @RequestMapping(value = "/login",method = RequestMethod.POST)
    public String login(Model model,String id,String pwd){
        //添加用户认证信息
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(
                id,
                ");
        try {
                subject.login(usernamePasswordToken);
                return "home";
            }
        catch (UnknownAccountException e) {
            //用户名不存在
            model.addAttribute("msg","用户名不存在");
            return "login";
            }catch (IncorrectCredentialsException e) {
                //密码错误
                model.addAttribute("msg","密码错误");
                return "login";
                }
    }
    @RequestMapping(value = "/index")
    public String index(){
        return "home";
    }
}

五、Controller层访问控制

1.首先来数据库的数据,两张图是用户角色、和角色权限的数据。

2.设置权限

这里在用户页面点击编辑按钮时设置需要有id=002的角色,在点击选择角色按钮时需要有code=002的权限。

    @RequestMapping(value = "/edit",method = RequestMethod.GET)
    @RequiresRoles(")//权限管理;
    public String editGet(Model model,@RequestParam(value="id") String id) {
        model.addAttribute("id", id);
        return "/user/edit";
    }

    @RequestMapping(value = "/selrole",method = RequestMethod.GET)
    @RequiresPermissions(")//权限管理;
    public String selctRole(Model model,@RequestParam("id") String id,@RequestParam("type") Integer type) {
        model.addAttribute("id",id);
        model.addAttribute("type", type);
        return "/user/selrole";
    }

当使用用户001登录时,点击编辑,弹出框如下,提示没有002的角色

点击选择角色按钮时提示没有002的权限。

当使用用户002登录时,点击编辑按钮,显示正常,点击选择角色也是提示没002的权限,因为权限只有001。

六、前端页面层访问控制

有时为了不想像上面那样弹出错误页面,需要在按钮显示上进行不可见,这样用户也不会点击到。前面已经引入了依赖并配置了bean,这里测试下在html中使用shiro。

1.首先设置html标签引入shiro

<html xmlns:th="http://www.thymeleaf.org"
      xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">

2.控制按钮可见

这里使用shiro:hasAnyRoles="002,003"判断用户角色是否是002或003,是则显示不是则不显示。

    <div class="layui-inline">
        <a shiro:hasAnyRoles="002,003" class="layui-btn layui-btn-normal newsAdd_btn" onclick="addUser('')">添加用户</a>
    </div>
    <div class="layui-inline">
        <a shiro:hasAnyRoles="002,003" class="layui-btn layui-btn-danger batchDel" onclick="getDatas();">批量删除</a>
    </div>

当001用户登录时,添加用户、批量删除按钮都不显示,只显示查询按钮。

当002用户登录时,添加用户、批量删除按钮都显示

推荐博客

  程序员写代码之外,如何再赚一份工资?

七、小结

这里只是实现了Shiro的简单的功能,Shiro还有很多很强大的功能,比如session管理等,而且目前权限管理模块还有很多需要优化的功能,左侧导航栏的动态加载和权限控制、Shiro与Redis结合实现session共享、Shiro与Cas结合实现单点登录等。

如何实现登录、URL和页面按钮的访问控制?的更多相关文章

  1. 权限管理系统之集成Shiro实现登录、url和页面按钮的访问控制

    用户权限管理一般是对用户页面.按钮的访问权限管理.Shiro框架是一个强大且易用的Java安全框架,执行身份验证.授权.密码和会话管理,对于Shiro的介绍这里就不多说.本篇博客主要是了解Shiro的 ...

  2. yii2获取登录前的页面url地址--电脑和微信浏览器上的实现以及yii2相关源码的学习

    对于一个有登录限制(权限限制)的网站,用户输入身份验证信息以后,验证成功后跳转到登录前的页面是一项很人性化的功能.那么获取登录前的页面地址就很关键,今天在做一个yii2项目的登录调试时发现了一些很有意 ...

  3. 四、angularjs 如何在页面没有登录的情况下阻止用户通过更改url进入页面--$stateChangeStart

    有时候用户没有登录或者在某些情况下你是不希望用户进入页面,但是angular的路由机制可以让用户直接通过更改Url进入页面,如何处理这一问题呢? ——监控路由转换机制 $stateChangeStar ...

  4. 基于puppeteer模拟登录抓取页面

    关于热图 在网站分析行业中,网站热图能够很好的反应用户在网站的操作行为,具体分析用户的喜好,对网站进行针对性的优化,一个热图的例子(来源于ptengine) 上图中能很清晰的看到用户关注点在那,我们不 ...

  5. selenium+python自动化84-chrome手机wap模式(登录淘宝页面)

    前言 chrome手机wap模式登录淘宝页面,点击验证码无效问题解决. 切换到wap模式,使用TouchActions模块用tap方法触摸 我的环境 chrome 62 chromedriver 2. ...

  6. 深入浅出经典面试题:从浏览器中输入URL到页面加载发生了什么 - Part 3

    备注: 因为文章太长,所以将它分为三部分,本文是第三部分. 第一部分:深入浅出经典面试题:从浏览器中输入URL到页面加载发生了什么 - Part 1 第二部分:深入浅出经典面试题:从浏览器中输入URL ...

  7. Python爬虫教程-13-爬虫使用cookie爬取登录后的页面(人人网)(下)

    Python爬虫教程-13-爬虫使用cookie爬取登录后的页面(下) 自动使用cookie的方法,告别手动拷贝cookie http模块包含一些关于cookie的模块,通过他们我们可以自动的使用co ...

  8. Python爬虫教程-12-爬虫使用cookie爬取登录后的页面(人人网)(上)

    Python爬虫教程-12-爬虫使用cookie(上) 爬虫关于cookie和session,由于http协议无记忆性,比如说登录淘宝网站的浏览记录,下次打开是不能直接记忆下来的,后来就有了cooki ...

  9. 前后端分离, 前端如何防止直接输入URL进入页面?

    转自:https://blog.csdn.net/weixin_41829196/article/details/80444870 前后端分离,如何防止用户直接在地址栏输入url进入页面,也就是判断用 ...

随机推荐

  1. Codeforces 1144F Graph Without Long Directed Paths (DFS染色+构造)

    <题目链接> 题目大意:给定一个无向图,该无向图不含自环,且无重边.现在要你将这个无向图定向,使得不存在任何一条路径长度大于等于2.然后根输入边的顺序,输出构造的有向图.如果构造的边与输入 ...

  2. Ubuntu 18.04 系统配置 NPM环境和mysql数据库问题解决

    Node.js 是一个基于 Chrome V8 引擎的 JavaScript 运行环境. Node.js 使用了一个事件驱动.非阻塞式 I/O 的模型,使其轻量又高效. 今天我就为大家 使用 Ubun ...

  3. iOS开发之图片压缩实现

    使用下面两个方法,先按尺寸重绘图片,然后再降低品质上传图片data #pragma mark 裁剪照片 -(UIImage *)scaleToSize:(UIImage *)image size:(C ...

  4. It is difficult to the point of impossiblity for sb to image a time when ...

    对sb而言很难想象一段..的时光.

  5. select2使用小结

    做项目考虑到使用的便捷,要用到select2,就研究了一下,做个小结,防止忘记.本文内容是建立在NFine框架上的,使用的MVC三层架构.本人很少写文章,学习的知识也过少,不知道能不能表达准确,如有错 ...

  6. 再回首数据结构—数组(Golang实现)

    数组为线性数据结构,通常编程语言都有自带了数组数据类型结构,数组存放的是有个相同数据类型的数据集: 为什么称数组为线性数据结构:因为数组在内存中是连续存储的数据结构,数组中每个元素最多只有左右两个方向 ...

  7. vue-cli跳转到新页面的顶部

    我这里有两种方法都是可以用的 1,利用vue-router的默认模式hash,可以记录上一页的位置,如果需要点话,如果没有记录,在进入新页面的时候是返回到新页面的最顶部的 scrollBehavior ...

  8. java课程之团队开发冲刺阶段1.2

    一.总结昨天进度 1.三个任务都已经实现 2.使用时间:四个小时左右 二.遇到的困难 1.对Android原生的侧拉任务栏不了解,导致使用的时候出现了一部分问题 三.今天任务规划 1.对之前的程序重新 ...

  9. For each...in / For...in / For...of 的解释与例子

    1.For each...in for each...in 语句在对象属性的所有值上迭代指定的变量.对于每个不同的属性,执行一个指定的语句. 语法: for each (variable in obj ...

  10. linux常见命令实践.

    ls -la : 给出当前目录下所有文件的一个长列表,包括以句点开头的“隐藏”文件 ls -a . .. 1 online_tools online_tools_0803 ll: 竖列显示所有文件 l ...