Springboot整合Shiro实现登录与权限校验详细解读

2022-07-15,,,,

springboot-cli 开发脚手架系列

springboot优雅的整合shiro进行登录校验权限认证(附源码下载)

简介

springboo配置shiro进行登录校验,权限认证,附demo演示。

前言

我们致力于让开发者快速搭建基础环境并让应用跑起来,提供使用示例供使用者参考,让初学者快速上手。

本博客项目源码地址:

项目源码github地址

项目源码国内gitee地址

1. 环境

依赖

     <!-- shiro核心框架 -->
        <dependency>
            <groupid>org.apache.shiro</groupid>
            <artifactid>shiro-core</artifactid>
            <version>1.9.0</version>
        </dependency>
        <!-- shiro使用spring框架 -->
        <dependency>
            <groupid>org.apache.shiro</groupid>
            <artifactid>shiro-spring</artifactid>
            <version>1.9.0</version>
        </dependency>
        <!-- thymeleaf中使用shiro标签 -->
        <dependency>
            <groupid>com.github.theborakompanioni</groupid>
            <artifactid>thymeleaf-extras-shiro</artifactid>
            <version>2.1.0</version>
        </dependency>
        <dependency>
            <groupid>org.springframework.boot</groupid>
            <artifactid>spring-boot-starter-thymeleaf</artifactid>
        </dependency>

yml配置

server:
  port: 9999
  servlet:
    session:
      # 让tomcat只能从cookie中获取会话信息,这样,当没有cookie时,url也就不会被自动添加上 ;jsessionid=… 了。
      tracking-modes: cookie

spring:
  thymeleaf:
    # 关闭页面缓存,便于开发环境测试
    cache: false
    # 静态资源路径
    prefix: classpath:/templates/
    # 网页资源默认.html结尾
    mode: html
 

2. 简介

shiro三大功能模块

  • subject

认证主体,通常指用户(把操做交给securitymanager)。

  • securitymanager

安全管理器,安全管理器,管理全部subject,能够配合内部安全组件(关联realm)

  • realm

域对象,用于进行权限信息的验证,shiro连接数据的桥梁,如我们的登录校验,权限校验就在realm进行定义。

3. realm配置

定义用户实体user ,可根据自己的业务自行定义

@data
@accessors(chain = true)
public class user {
    /**
     * 用户id
     */
    private long userid;
    /**
     * 用户名
     */
    private string username;
    /**
     * 密码
     */
    private string password;
    /**
     * 用户别称
     */
    private string name;
}

重写authorizingrealm 中登录校验dogetauthenticationinfo及授权dogetauthorizationinfo方法,编写我们自定义的校验逻辑。

/**
 * 自定义登录授权
 *
 * @author ding
 */
public class userrealm extends authorizingrealm {
    /**
     * 授权
     * 此处权限授予
     */
    @override
    protected authorizationinfo dogetauthorizationinfo(principalcollection principalcollection) {
        simpleauthorizationinfo info = new simpleauthorizationinfo();
        // 在这里为每一个用户添加vip权限
        info.addstringpermission("vip");
        return info;
    }
    /**
     * 认证
     * 此处实现我们的登录逻辑,如账号密码验证
     */
    @override
    protected authenticationinfo dogetauthenticationinfo(authenticationtoken authenticationtoken) throws authenticationexception {
        // 获取到token
        usernamepasswordtoken token = (usernamepasswordtoken) authenticationtoken;
        // 从token中获取到用户名和密码
        string username = token.getusername();
        string password = string.valueof(token.getpassword());
        // 为了方便,这里模拟获取用户
        user user = this.getuser();
        if (!user.getusername().equals(username)) {
            throw new unknownaccountexception("用户不存在");
        } else if (!user.getpassword().equals(password)) {
            throw new incorrectcredentialsexception("密码错误");
        }
        // 校验完成后,此处我们把用户信息返回,便于后面我们通过subject获取用户的登录信息
        return new simpleauthenticationinfo(user, password, getname());
    }
    /**
     * 此处模拟用户数据
     * 实际开发中,换成数据库查询获取即可
     */
    private user getuser() {
        return new user()
                .setname("admin")
                .setuserid(1l)
                .setusername("admin")
                .setpassword("123456");
    }
}

4. 核心配置

shiroconfig.java

/**

* shiro内置过滤器,能够实现拦截器相关的拦截器

* 经常使用的过滤器:

* anon:无需认证(登陆)能够访问

* authc:必须认证才能够访问

* user:若是使用rememberme的功能能够直接访问

* perms:该资源必须获得资源权限才能够访问,格式 perms[权限1,权限2]

* role:该资源必须获得角色权限才能够访问

**/

/**
 * shiro核心管理器
 *
 * @author ding
 */
@configuration
public class shiroconfig {
    /**
     * 无需认证就可以访问
     */
    private final static string anon = "anon";
    /**
     * 必须认证了才能访问
     */
    private final static string authc = "authc";
    /**
     * 拥有对某个资源的权限才能访问
     */
    private final static string perms = "perms";
    /**
     * 创建realm,这里返回我们上一把定义的userrealm 
     */
    @bean(name = "userrealm")
    public userrealm userrealm() {
        return new userrealm();
    }
    /**
     * 创建安全管理器
     */
    @bean(name = "securitymanager")
    public defaultwebsecuritymanager getdefaultwebsecuritymanager(@qualifier("userrealm") userrealm userrealm) {
        defaultwebsecuritymanager securitymanager = new defaultwebsecuritymanager();
        //绑定realm对象
        securitymanager.setrealm(userrealm);
        return securitymanager;
    }
    /**
     * 授权过滤器
     */
    @bean
    public shirofilterfactorybean getshirofilterfactorybean(@qualifier("securitymanager") defaultwebsecuritymanager defaultwebsecuritymanager) {
        shirofilterfactorybean bean = new shirofilterfactorybean();
        // 设置安全管理器
        bean.setsecuritymanager(defaultwebsecuritymanager);
        // 添加shiro的内置过滤器
        map<string, string> filtermap = new linkedhashmap<>();
        filtermap.put("/index", anon);
        filtermap.put("/userinfo", perms + "[vip]");
        filtermap.put("/table2", authc);
        filtermap.put("/table3", perms + "[vip2]");
        bean.setfilterchaindefinitionmap(filtermap);
        // 设置跳转登陆页
        bean.setloginurl("/login");
        // 无权限跳转
        bean.setunauthorizedurl("/unauth");
        return bean;
    }
    /**
     * thymeleaf中使用shiro标签
     */
    @bean
    public shirodialect shirodialect() {
        return new shirodialect();
    }
}

5. 接口编写

indexcontroller.java

/**
 * @author ding
 */
@controller
public class indexcontroller {
    @requestmapping({"/", "/index"})
    public string index(model model) {
        model.addattribute("msg", "hello,shiro");
        return "/index";
    }
    @requestmapping("/userinfo")
    public string table1(model model) {
        return "userinfo";
    }
    @requestmapping("/table")
    public string table(model model) {
        return "table";
    }
    @getmapping("/login")
    public string login() {
        return "login";
    }
    @postmapping(value = "/dologin")
    public string dologin(@requestparam("username") string username, @requestparam("password") string password, model model) {
        //获取当前的用户
        subject subject = securityutils.getsubject();
        //用来存放错误信息
        string msg = "";
        //如果未认证
        if (!subject.isauthenticated()) {
            //将用户名和密码封装到shiro中
            usernamepasswordtoken token = new usernamepasswordtoken(username, password);
            try {
                // 执行登陆方法
                subject.login(token);
            } catch (exception e) {
                e.printstacktrace();
                msg = "账号或密码错误";
            }
            //如果msg为空,说明没有异常,就返回到主页
            if (msg.isempty()) {
                return "redirect:/index";
            } else {
                model.addattribute("errormsg", msg);
                return "login";
            }
        }
        return "/login";
    }
    @getmapping("/logout")
    public string logout() {
        securityutils.getsubject().logout();
        return "index";
    }
    @getmapping("/unauth")
    public string unauth() {
        return "unauth";
    }
}

6. 网页资源

在resources中创建templates文件夹存放页面资源

index.html

<!doctype html>
<html xmlns:th="http://www.thymeleaf.org">
<html xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head>
    <meta charset="utf-8">
    <title>title</title>
</head>
<body>
<h1>首页</h1>
<!-- 使用shiro标签 -->
<shiro:authenticated>
    <p>用户已登录</p> <a th:href="@{/logout}" rel="external nofollow" >退出登录</a>
</shiro:authenticated>
<shiro:notauthenticated>
    <p>用户未登录</p>  
</shiro:notauthenticated>
<br/>
<a th:href="@{/userinfo}" rel="external nofollow" >用户信息</a>
<a th:href="@{/table}" rel="external nofollow" >table</a>
</body>
</html>

login.html

<!doctype html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="utf-8">
    <title>登陆页</title>
</head>
<body>
<div>
    <p th:text="${errormsg}"></p>
    <form action="/dologin" method="post">
        <h2>登陆页</h2>
        <h6>账号:admin,密码:123456</h6>
        <input type="text" id="username"  name="username" placeholder="admin">
        <input type="password" id="password" name="password"  placeholder="123456">
        <button type="submit">登陆</button>
    </form>
</div>
</body>
</html>

userinfo.html

<!doctype html>
<html lang="en" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head>
    <meta charset="utf-8">
    <title>table1</title>
</head>
<body>
<h1>用户信息</h1>
<!-- 利用shiro获取用户信息 -->
用户名:<shiro:principal property="username"/>
<br/>
用户完整信息: <shiro:principal/>
</body>
</html>

table.hetml

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>table</title>
</head>
<body>
<h1>table</h1>
</body>
</html>

7. 效果演示

启动项目浏览器输入127.0.0.1:9999

当我们点击用户信息和table时会自动跳转登录页面

登录成功后

获取用户信息

此处获取的就是我们就是我们前面dogetauthenticationinfo方法返回的用户信息,这里为了演示就全部返回了,实际生产中密码是不能返回的。

8. 源码分享

本项目已收录

springboot-cli开发脚手架,集合各种常用框架使用案例,完善的文档,致力于让开发者快速搭建基础环境并让应用跑起来,并提供丰富的使用示例供使用者参考,帮助初学者快速上手。

项目源码github地址

项目源码国内gitee地址

到此这篇关于springboot整合shiro实现登录与权限校验详细分解的文章就介绍到这了,更多相关springboot shiro登陆校验内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

《Springboot整合Shiro实现登录与权限校验详细解读.doc》

下载本文的Word格式文档,以方便收藏与打印。