Shiro:与SpringBoot,Mybatis,Theymeleaf整合

1. 快速体验

1.1 创建一个普通的maven项目

1.2 导入依赖


    org.apache.shiroshiro-core
    1.4.1



    org.s1f4j
    jc1-over-s1f4j
    1.7.21


    org.s1f4j
    s1f4j-1og4j12
    1.7.21


    1og4j
    log4j
    1.2.17

1.3 新建log4j.properties

1og4j.rootLogger=INFO, stdout
10g4j.appender.stdout=org.apache.1og4j.ConsoleAppender
1og4j.appender.stdout.layout=org.apache.1og4j.PatternLayout
1og4j.appender.stdout.1ayout.ConversionPattern=%d %p [%c] - %m %n
# General Apache Libraries
1og4j.logger.org.apache=WARN
# Spring
1og4j.logger.org.springframework=WARN
# Defoult Shiro Logging
10g4j.logger.org.apache.shiro=INFO
# Disable verbose Logging
1og4j.logger.org.apache.shiro.util.ThreadContext=WARN
1og4j.logger.org.apache.shiro.cache.ehcache.EhCache=MARN

1.4 新建shiro.ini文件

[users]
# user 'root' with password 'secret' and the 'admin'
role root=secret, admin
# user 'guest' with the password 'guest' and the 'guest' 
role guest=guest, guest
# user 'presidentskroob' with password '12345'("Thot's the same combination on
# my luggage!!!";)), and role 'president'
presidentskroob=12345, president
# user' darkhelmet' with password' ludicrousspeed' and roles 'darklord' and 'schwartz'
darkhelmet=ludicrousspeed, darklord, schwartz
# user 'lonestarr' with password 'vespa' and roles 'goodguy' and 'schwartz'
lonestarr=vespa, goodguy, schwartz
# Roles with assigned permissions
# Each Line conforms to the format defined in the
# org.apache.shiro.realm.text.TextConfigurationRealm# setRoleDefinitions JavaDoc
[ roles]
# 'admin' role has all permissions, indicated by the wildcard'*"
admin=*
# The 'schwartz' role can do anything(*) with any Lightsaber:
schwartz=lightsaber:*
# The 'goodguy' role is allowed to 'drive'(action) the winnebago (type) with
# license plate 'eagle5'(instance specific id)
goodguy =winnebago:drive:eagle5

1.5 新建Quickstart类

public class Quickstart {
    public static void main(String[] args) {
        // 获取例子配置文件
        Factory factory = new IniSecurityManagerFactory("classpath:shiro.ini");
        SecurityManager securityManager = factory.getInstance();

        SecurityUtils.setSecurityManager(securityManager);

        // 获取当前得到 Subject 调用SecurityUtils.getSubject()方法。
        Subject currentUser = SecurityUtils.getSubject();

        // 测试使用Session
        // 获取Session 调用subject的getSession()方法
        Session session = currentUser.getSession();
        session.setAttribute("someKey", "aValue");
        String value = (String) session.getAttribute("someKey");
        if (value.equals("aValue")) {
            System.out.println("==================>>>>>>>>>>>Retrieved the correct value! [" + value + "]");
        }

        // 测试当前的用户已经被认证,既用户是否登录,调用 subject的isAuthenticated()。
        if (!currentUser.isAuthenticated()) {
            // 把用户名和密码封装为UsernamePasswordToken对象
            UsernamePasswordToken token = new UsernamePasswordToken("lonestarr", "vespa");
            // RememberMe
            token.setRememberMe(true);
            try {
                // 执行登录
                currentUser.login(token);
            } catch (UnknownAccountException uae) {
                // 没有指定用户,shiro 抛出UnknownAccountException
                System.out.println("==================>>>>>>>>>>>There is no user with username of " + token.getPrincipal());
            } catch (IncorrectCredentialsException ice) {
                // 密码不对,shiro 抛出IncorrectCredentialsException
                System.out.println("==================>>>>>>>>>>>Password for account " + token.getPrincipal() + " was incorrect!");
            } catch (LockedAccountException lae) {
                // 用户被锁定。shiro抛出LockedAccountException
                System.out.println("==================>>>>>>>>>>>The account for username " + token.getPrincipal() + " is locked.Please contact your administrator to unlock it.");
            } catch (AuthenticationException ae) {
                // 所有认证是异常的总类
            }
        }
        System.out.println("==================>>>>>>>>>>>User [" + currentUser.getPrincipal() + "] logged in successfully.");

        // 测试使用有这个角色
        if (currentUser.hasRole("schwartz")) {
            System.out.println("==================>>>>>>>>>>>May the Schwartz be with you!");
        } else {
            System.out.println("==================>>>>>>>>>>>Hello, mere mortal.");
        }

        // 测试用户是否具备某个行为(权限)
        if (currentUser.isPermitted("lightsaber:weild")) {
            System.out.println("==================>>>>>>>>>>>You may use a lightsaber ring.  Use it wisely.");
        } else {
            System.out.println("==================>>>>>>>>>>>Sorry, lightsaber rings are for schwartz masters only.");
        }

        // 测试用户是否具备某个行为(这个比较具体)
        if (currentUser.isPermitted("winnebago:drive:eagle5")) {
            System.out.println("==================>>>>>>>>>>>You are permitted to 'drive' the winnebago with license plate (id) 'eagle5'.Here are the keys - have fun!");
        } else {
            System.out.println("==================>>>>>>>>>>>Sorry, you aren't allowed to drive the 'eagle5' winnebago!");
        }

        // 执行登出,调用subject的logout()
        currentUser.logout();

        System.exit(0);
    }
}

1.6 核心方法和对象

2. Shiro和SpringBoot整合

2.1 基本配置

SpringBoot版本2.2.1 + Web

导入依赖



    org.thymeleaf
    thymeleaf-spring5


    org.thymeleaf.extras
    thymeleaf-extras-java8time



    org.apache.shiro
    shiro-spring
    1.4.1

2.2 编写Shiro的两个核心配置

2.3 添加测试页面

2.4 Controller添加跳转链接

2.5 首页增加跳转链接

2.6 ShiroConfig中添加内置过滤器

加入上面的配置后,页面跳转失败

2.7 新增登陆页面

a.在Controller中增加跳转

b. 设置登陆的请求

c. 支持通配符

d. 登陆请求

e. Controller处理登陆请求

f. 登陆页面接收错误信息

2.8 认证操作

3. Shiro和Mybatis整合

3.1 导入依赖

在与SpringBoot整合的基础上


    mysq1
    mysql-connector-java



    1og4j
    log4j
    1.2.17



    com.alibabadruid
    1.1.12



    org.mybatis.spring.boot
    mybatis-spring-boot-starter
    2.1.0

3.2 编写配置文件application.yml

3.3 编写配置文件application.properties

建立mapper文件夹

a 导入lombok依赖


    org.projectlombok
    lombok
    1.16.10

b. 建立实体类

c. 建立mapper接口

d. 建立mapper.xml

e. 建立service层

3.4 连接真实数据库

在UserRealm中配置

3.5 授权操作

a. 报错提示

正常情况下,没有授权会跳转到未授权页面

b. 未授权跳转Controller

c. 在ShiroConfig中配置

d. 给用户赋予权限

UserRealm中配置

e. 从数据库中获取权限

赋予用户权限字段

在UserRealm中配置

在ShiroConfig中配置去add和update的权限

4. Shiro和Thymeleaf整合

4.1 导入依赖



    com.github.theborakompanioni
    thymeleaf-extras-shiro
    2.0.0

4.2 ShiroDialect放入Bean

在ShiroConfig中配置

4.3 index页面动态显示菜单

a. 导入命名空间

xmlns:shiro="http://www.thymeleaf.org/thymeleaf-extras-shiro"

4.4 登陆后首页不显示登陆按钮

a. 存放session

在UserRealm中设置session

在页面进行判断

参考B栈狂神java

你可能感兴趣的:(Shiro:与SpringBoot,Mybatis,Theymeleaf整合)