如何快速理解掌握shiro

1.什么是shiro(java安全框架)

官网地址:http://shiro.apache.org/

坐标

<!-- https://mvnrepository.com/artifact/org.apache.shiro/shiro-core -->
<dependency>
    <groupId>org.apache.shiro</groupId>
    <artifactId>shiro-core</artifactId>
    <version>1.4.0</version>
</dependency>

Apache Shiro是一个强大且易用的Java安全框架,执行身份验证、授权、密码和会话管理。使用Shiro的易于理解的API,您可以快速、轻松地获得任何应用程序,从最小的移动应用程序到最大的网络和企业应用程序。

主要功能

三个核心组件:Subject, SecurityManager 和 Realms.

Subject:即“当前操作用户”。但是,在Shiro中,Subject这一概念并不仅仅指人,也可以是第三方进程、后台帐户(Daemon Account)或其他类似事物。它仅仅意味着“当前跟软件交互的东西”。
  Subject代表了当前用户的安全操作,SecurityManager则管理所有用户的安全操作。
  SecurityManager:它是Shiro框架的核心,典型的Facade模式,Shiro通过SecurityManager来管理内部组件实例,并通过它来提供安全管理的各种服务。
  Realm: Realm充当了Shiro与应用安全数据间的“桥梁”或者“连接器”。也就是说,当对用户执行认证(登录)和授权(访问控制)验证时,Shiro会从应用配置的Realm中查找用户及其权限信息。
  从这个意义上讲,Realm实质上是一个安全相关的DAO:它封装了数据源的连接细节,并在需要时将相关数据提供给Shiro。当配置Shiro时,你必须至少指定一个Realm,用于认证和(或)授权。配置多个Realm是可以的,但是至少需要一个。
  Shiro内置了可以连接大量安全数据源(又名目录)的Realm,如LDAP、关系数据库(JDBC)、类似INI的文本配置资源以及属性文件等。如果缺省的Realm不能满足需求,你还可以插入代表自定义数据源的自己的Realm实现。

2.第一个hello shiro

2.1官网的Quickstart

创建sprngboot项目

导入pom.xml坐标

 <!-- shiro -->
        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-core</artifactId>
            <version>1.4.0</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>jcl-over-slf4j</artifactId>
            <version>1.5.6</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.5.6</version>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>

向resources 中添加 shiro.ini log4j.properties

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' ("That'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

log4j.properties

log4j.rootLogger=INFO, stdout

log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m %n

# General Apache libraries
log4j.logger.org.apache=WARN

# Spring
log4j.logger.org.springframework=WARN

# Default Shiro logging
log4j.logger.org.apache.shiro=INFO

# Disable verbose logging
log4j.logger.org.apache.shiro.util.ThreadContext=WARN
log4j.logger.org.apache.shiro.cache.ehcache.EhCache=WARN

Quickstart

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
//import org.apache.shiro.ini.IniSecurityManagerFactory;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.realm.text.IniRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
//import org.apache.shiro.lang.util.Factory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class Quickstart {

    private static final transient Logger log = LoggerFactory.getLogger(Quickstart.class);


    public static void main(String[] args) {

        DefaultSecurityManager defaultSecurityManager=new DefaultSecurityManager();
        IniRealm iniRealm=new IniRealm("classpath:shiro.ini");
        defaultSecurityManager.setRealm(iniRealm);

        SecurityUtils.setSecurityManager(defaultSecurityManager);

        // Now that a simple Shiro environment is set up, let's see what you can do:

        // get the currently executing user:
        //获取当前用户对象subject
        Subject currentUser = SecurityUtils.getSubject();
        log.info("信息"+currentUser);

        // Do some stuff with a Session (no need for a web or EJB container!!!)
        //通过当前用户拿到session
        Session session = currentUser.getSession();
        session.setAttribute("someKey", "aValue");
        String value = (String) session.getAttribute("someKey");
        if (value.equals("aValue")) {
            log.info("Retrieved the correct value! [" + value + "]");
        }

        // let's login the current user so we can check against roles and permissions:
        //判断当前用户是否被认证

        if (!currentUser.isAuthenticated()) {
            UsernamePasswordToken token = new UsernamePasswordToken("lonestarr", "vespa");
            token.setRememberMe(true);
            try {
                currentUser.login(token);//执行了登陆操作
            } catch (UnknownAccountException uae) { //
                log.info("There is no user with username of " + token.getPrincipal());
            } catch (IncorrectCredentialsException ice) {
                log.info("Password for account " + token.getPrincipal() + " was incorrect!");
            } catch (LockedAccountException lae) {
                log.info("The account for username " + token.getPrincipal() + " is locked.  " +
                        "Please contact your administrator to unlock it.");
            }
            // ... catch more exceptions here (maybe custom ones specific to your application?
            catch (AuthenticationException ae) {
                //unexpected condition?  error?
            }
        }

        //say who they are:
        //print their identifying principal (in this case, a username):
        log.info("User [" + currentUser.getPrincipal() + "] logged in successfully.");

        //test a role:
        if (currentUser.hasRole("schwartz")) {
            log.info("May the Schwartz be with you!");
        } else {
            log.info("Hello, mere mortal.");
        }


        //test a typed permission (not instance-level)
        if (currentUser.isPermitted("lightsaber:wield")) {
            log.info("You may use a lightsaber ring.  Use it wisely.");
        } else {
            log.info("Sorry, lightsaber rings are for schwartz masters only.");
        }

        //a (very powerful) Instance Level permission:
        if (currentUser.isPermitted("winnebago:drive:eagle5")) {
            log.info("You are permitted to 'drive' the winnebago with license plate (id) 'eagle5'.  " +
                    "Here are the keys - have fun!");
        } else {
            log.info("Sorry, you aren't allowed to drive the 'eagle5' winnebago!");
        }

        //all done - log out!
        //注销
        currentUser.logout();

        System.exit(0);
    }
}

2.2自己配置hello shiro

导入依赖

 <!-- shiro -->
        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-core</artifactId>
            <version>1.4.0</version>
        </dependency>

配置ini

[users]
admin=123456
root=123

测试


@SpringBootTest
class ShiroApplicationTests {

    @Test
    void contextLoads() {
        //1.创建安全管理器对象
        DefaultSecurityManager securityManager = new DefaultSecurityManager();
        //2.设置realm
        securityManager.setRealm(new IniRealm("classpath:shiro.ini"));
        //3.安全工具类 给全局安全工具类设置安全管理器
        SecurityUtils.setSecurityManager(securityManager);
        //4.关连对象 拿到subject
        Subject subject = SecurityUtils.getSubject();
        //5.创建令牌
        UsernamePasswordToken token = new UsernamePasswordToken("admin","11");
        try {
            System.out.println("状态"+subject.isAuthenticated());
            subject.login(token); //用户认证
            System.out.println("状态"+subject.isAuthenticated());
        }catch (UnknownAccountException e){ //未知帐户异常 用户名异常
            e.printStackTrace();
            System.out.println("用户名不存在");
        }catch (IncorrectCredentialsException e){//不正确的凭据异常 也就是密码错误
            e.printStackTrace();
            System.out.println("密码不正确");
        }
    }
}

3.自定义Realm

创建TestRealm

package com.chen.shiro;

import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

/**
 * @author blackcats
 * @date 2020/8/4 10:21
 * 代码太难了
 */
public class TestRealm extends AuthorizingRealm {

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        return null;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //在token中获取用户名
        String principal = (String) token.getPrincipal();
        System.out.println(principal);
        if("admin".equals(principal)){
            //参数1: 返回数据中的用户名
            //参数2: 返回数据中的密码
            //参数3: 返回当前的Realm
            return new SimpleAuthenticationInfo(principal,"123456",this.getName());
        }
        return null;
    }
}

测试

package com.chen.shiro;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.subject.Subject;

/**
 * @author blackcats
 * @date 2020/8/4 10:48
 * 代码太难了
 */
public class TestRealm01 {
    public static void main(String[] args) {
        DefaultSecurityManager securityManager = new DefaultSecurityManager();
        securityManager.setRealm(new TestRealm());
        SecurityUtils.setSecurityManager(securityManager);
        Subject subject = SecurityUtils.getSubject();

        UsernamePasswordToken token = new UsernamePasswordToken("admin","1111");
        try {
            System.out.println("状态"+subject.isAuthenticated());
            subject.login(token); //用户认证
            System.out.println("状态"+subject.isAuthenticated());
        }catch (UnknownAccountException e){
            e.printStackTrace();
        }catch (IncorrectCredentialsException e){
            e.printStackTrace();
            System.out.println("密码错误");
        }
    }
}

4.MD5和Salt加密

package com.chen.shiro;

import org.apache.shiro.crypto.hash.Md5Hash;

/**
 * @author blackcats
 * @date 2020/8/4 10:58
 * 代码太难了
 */
public class ShiroMD5 {
    public static void main(String[] args) {
        //创建MD5
        Md5Hash md5Hash = new Md5Hash("123");
        System.out.println(md5Hash.toHex());
        //创建MD5+salt
        Md5Hash md5Hash1 = new Md5Hash("123","chen");
        System.out.println(md5Hash1.toHex());
        //创建MD5+salt+hash散列
        Md5Hash md5Hash2 = new Md5Hash("123","chen",1024);
        System.out.println(md5Hash2.toHex());

    }
}

创建MD5Realm

package com.chen.shiro;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

/**
 * @author blackcats
 * @date 2020/8/4 11:04
 * 代码太难了
 */
public class MD5Realm  extends AuthorizingRealm {
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //获取信息
        String principal = (String) token.getPrincipal();
        System.out.println(principal);
        //获取密码md5加密
        //Md5Hash password = new Md5Hash("123456");

        //获取密码md5+salt加密
        //Md5Hash password = new Md5Hash("123456","chen");

        //获取密码md5+salt加密+hash散列
        Md5Hash password = new Md5Hash("123456","chen",1024);
//        if("admin".equals(principal)){
//
//            return  new SimpleAuthenticationInfo(principal, password, getName());
//        }
        if("admin".equals(principal)){
            //参数1: 返回数据中的用户名
            //参数2: 返回数据中的密码 md5+随机salt 后的密码
            //参数3: 注册时的随即salt
            //参数4: realm的名字
            return  new SimpleAuthenticationInfo(principal, password, ByteSource.Util.bytes("chen"), this.getName());
        }
        return null;
    }
}

测试

package com.chen.shiro;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.subject.Subject;

/**
 * @author blackcats
 * @date 2020/8/4 11:04
 * 代码太难了
 */
public class MD5RealmTest {
    public static void main(String[] args) {
        DefaultSecurityManager securityManager = new DefaultSecurityManager();
        MD5Realm realm = new MD5Realm();
        //设置realm的hash凭证适配器
        HashedCredentialsMatcher matcher = new HashedCredentialsMatcher();
        matcher.setHashAlgorithmName("md5");
        //使用散列
        matcher.setHashIterations(1024);
        realm.setCredentialsMatcher(matcher);
        securityManager.setRealm(realm);
        SecurityUtils.setSecurityManager(securityManager);
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken("admin","123456");

        try {
            System.out.println("状态"+subject.isAuthenticated());
            subject.login(token); //用户认证
            System.out.println("状态"+subject.isAuthenticated());
        }catch (UnknownAccountException e){
            e.printStackTrace();
            System.out.println("用户名错误");
        }catch (IncorrectCredentialsException e){
            e.printStackTrace();
            System.out.println("密码错误");
        }
    }
}

5.授权

在MD5RealmTest下添加

//授权
        if(subject.isAuthenticated()){

            //基于单角色
            boolean b = subject.hasRole("aaa");
            System.out.println(b);
            //基于多角色
            boolean b1 = subject.hasAllRoles(Arrays.asList("admin", "user"));
            System.out.println(b1);
            //是否有其中一个角色
            boolean[] booleans = subject.hasRoles(Arrays.asList("admin", "user", "aaa"));
            for (boolean b3:booleans ){
                System.out.println(b3);
            }
            System.out.println("--------- 基于权限字符串的访问控制 -------------");
            //基于权限字符串的访问控制  资源标识符:操作:资源类型
            System.out.println(subject.isPermitted("user:*:*"));
            System.out.println(subject.isPermitted("user:create:*"));
            System.out.println("商品1"+subject.isPermitted("product:update"));
            System.out.println("商品2"+subject.isPermitted("product:create"));

            //同时有那些权限
            boolean permittedAll = subject.isPermittedAll("product:update:01", "product:create");
            System.out.println(permittedAll);
        }

在MD5Realm添加

//授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {

        System.out.println("进入授权---------------");
        System.out.println("用户名"+principals.getPrimaryPrincipal());
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.addRole("admin");
        info.addRole("user");
        info.addStringPermission("user:*:*");
        info.addStringPermission("product:update:01");
        info.addStringPermission("product:create");
        return info;
    }

6.整合springboot

导入依赖

<!-- shiro-springboot -->
        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-spring-boot-starter</artifactId>
            <version>1.5.3</version>
        </dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.21</version>
        </dependency>
        <!--  mybatis-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.2</version>
        </dependency>
        <!-- mysql -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>
        <!--lombok-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
        <!--thymeleaf-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
    	<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>

配置yml

server:
  port: 8888
spring:
  thymeleaf:
    cache: false
  datasource:
    username: root
    password: *****
    url: jdbc:mysql://localhost:3306/shiro?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
    driver-class-name: com.mysql.cj.jdbc.NonRegisteringDriver
    type: com.alibaba.druid.pool.DruidDataSource

编写controller

@Controller
public class MyController {

    @RequestMapping("/")
    public String index(){
        return "index";
    }
}

项目跑起来进行下一步

编写配置shiro类

package com.chen.shiroConfig;

import org.apache.shiro.realm.Realm;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;

/**
 * @author blackcats
 * @date 2020/8/4 14:59
 * 代码太难了
 */

@Configuration
public class ShiroConfig {

    //创建shiroFilter
    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(DefaultWebSecurityManager defaultWebSecurityManager){
        ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
        //设置安全管理器
        bean.setSecurityManager(defaultWebSecurityManager);
        HashMap<String, String> map = new HashMap<>();
        //配置拦截资源
       map.put("/","authc"); //authc 需要认证和授权
        //配置公共资源
        bean.setFilterChainDefinitionMap(map);
        //登陆页面设置
        bean.setLoginUrl("/toLogin");
        return bean;
    }
    //创建安全管理器
    @Bean
    public DefaultWebSecurityManager defaultWebSecurityManager(Realm userRealm){
        DefaultWebSecurityManager manager = new DefaultWebSecurityManager();
        manager.setRealm(userRealm);
        return manager ;
    }
    //创建自定义Realm
    @Bean
    public Realm userRealm(){
        return  new UserRealm();
    }
}

shiro的常见过滤器

在这里插入图片描述

编写页面:

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<h1>菜单</h1>
<h2><a href="/toLogin">登录</a></h2>
<div th:text="${name}"></div>
<a href="/user/logout">退出登录</a>
<table>
    <tr>
        <td><a href="">用户管理</a></td>
        <td><a href="">订单管理</a></td>
        <td><a href="">商品管理</a></td>
    </tr>
</table>

</body>
</html>

login.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>登录</h1>
<h3 th:text="${message}"></h3>
<form action="/user/login">
    用户名:<input type="text" name="name">
    密码:<input type="text" name="pwd">
    <input type="submit" value="登录">
</form>

</body>
</html>

编写controller

package com.chen.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * @author blackcats
 * @date 2020/8/4 15:28
 * 代码太难了
 */
@Controller
@RequestMapping("/user")
public class UserController {

    @RequestMapping("/login")
    public String login(String name, String pwd,Model model){
        //获取subject
        Subject subject = SecurityUtils.getSubject();
        try {
            //执行登录
            subject.login(new UsernamePasswordToken(name,pwd));
            model.addAttribute("name",name);
            return "index";
        }catch (UnknownAccountException e){
            System.out.println("用户名错误");
            return "redirect:/toLogin";
        }catch (IncorrectCredentialsException e){
            System.out.println("密码错误");
            return "redirect:/toLogin";
        }

    }
    //退出登录
    @RequestMapping("/logout")
    public String loginout(){
        SecurityUtils.getSubject().logout();
        return "redirect:/toLogin";

    }
}

在ShiroConfig 添加拦截

7.整合数据库MD5+salt加密

编写数据库

drop table if exists user;
create table user(
id int PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(50),
pwd VARCHAR(100),
salt VARCHAR(20)

);
select * from user;

编写实体类

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
    private int id;
    private String name;
    private String pwd;
    private String salt;
}

编写mapper

@Component
@Mapper
public interface UserMapper {

    @Insert("insert into user(name,pwd,salt) values (#{name},#{pwd},#{salt})")
    int add(User user);
}

service

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public int add(User user) {
        Md5Hash md5Hash = new Md5Hash(user.getPwd(),"chen",1024);
        user.setPwd(md5Hash.toHex());
        user.setSalt("chen");
        return userMapper.add(user);
    }
}

controller

//注册
    @RequestMapping("/reg")
    public String userReg(User user){
        System.out.println("进入add");
        try {
            userService.add(user);
            System.out.println("注册成功");
            return "redirect:/user/toLogin";
        }catch (Exception e){
            e.printStackTrace();
            System.out.println("进入异常");
            return "redirect:/user/toreg";
        }
    }

8.shiro认证

在UserRealm中添加

  @Autowired
    private UserServiceImpl userService;
@Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String principal = (String) token.getPrincipal();
        User user = userService.selectByUserName(principal);
        System.out.println(user);
        if(user!=null){
            return  new SimpleAuthenticationInfo(user.getName(),user.getPwd(), ByteSource.Util.bytes(user.getSalt()),this.getName());
        }
        return null;
    }

向mapper添加


    @Select("select * from user where name=#{name}")
    User selectByUserName(String name);

修改shiroConfig中的自定义realm 校验器算法

 UserRealm realm = new UserRealm();
        //修改凭证校验匹配器
        HashedCredentialsMatcher matcher = new HashedCredentialsMatcher();
        //设置算法
        matcher.setHashAlgorithmName("md5");
        //设置散列次数
        matcher.setHashIterations(1024);
        realm.setCredentialsMatcher(matcher);
        return realm;

测试登录成功

9.整合thymeleaf

添加依赖

<!--thymeleaf和shiro整合包-->
<dependency>
    <groupId>com.github.theborakompanioni</groupId>
    <artifactId>thymeleaf-extras-shiro</artifactId>
    <version>2.0.0</version>
</dependency>

添加数据库表


-- 角色
drop table if exists role;
create table role(
id int PRIMARY KEY AUTO_INCREMENT,
name  VARCHAR(50)
);
insert into role(name) VALUES ("admin");
insert into role(name) VALUES ("user");
-- 角色
drop table if exists pres;
create table pres(
id int PRIMARY KEY AUTO_INCREMENT,
name  VARCHAR(50),
url VARCHAR(100)
);
insert into pres(name) values ("add");
insert into pres(name) values ("update");

-- 关系
drop table if exists context;
create table context(
id int PRIMARY KEY AUTO_INCREMENT,
userid int,
roleid int,
presid int
); 
insert into context(userid,roleid,presid) VALUES (1,1,1);
insert into context(userid,roleid,presid) VALUES (2,2,2);

添加数据相应字段

这里就写个user的

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
    private int id;
    private String name;
    private String pwd;
    private String salt;
    //角色集合
    private List<Role> roles;
    //操作集合
    private List<Pres> pres;
}

编写mapper

//通过id拿到角色
    List<User> selectByUserId(int id);
    //通过id拿到草错
    List<User> selectByUserIdPres(int id);

编写xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.chen.mapper.UserMapper">

    <select id="selectByUserId" resultMap="UserAndRoles">
     select u.id,u.name,r.id as rid ,r.name as rname
    from user u left join context c
    on u.id=c.userid LEFT join role r
    on r.id=c.roleid where c.userid=#{id}
    </select>
    <select id="selectByUserIdPres" resultMap="UserAndRoles">
        select u.id,u.name,p.id as pid,p.name as pname
        from user u left join context c
        on u.id=c.userid LEFT join pres p
        on p.id=c.presid where c.userid=#{id}
    </select>
    <resultMap id="UserAndRoles" type="user">
        <id property="id" column="id"/>
        <result property="content" column="content"/>
        <result property="name" column="name"/>
        <collection property="roles" ofType="role">
            <id property="id" column="rid"/>
            <result property="name" column="rname"/>
        </collection>
        <collection property="pres" ofType="pres">
            <id property="id" column="pid"/>
            <result property="name" column="pname"/>
        </collection>
    </resultMap>
</mapper>

在UserRealm添加相关配置

//获取身份信息
        String principal = (String) principals.getPrimaryPrincipal();
        List<User> users = userService.selectByUserId(userService.selectByUserName(principal).getId());
        if(!CollectionUtils.isEmpty(users)){
            SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
            users.forEach(user->{
                user.getRoles().forEach(
                        role -> {
                            info.addRole(role.getName());
                            //添加操作权限
                            List<User> userList = userService.selectByUserIdPres(userService.selectByUserName(principal).getId());
                            if(!CollectionUtils.isEmpty(userList)){
                                for (User user1 : userList) {
                                    user1.getPres().forEach(
                                            pres -> {
                                                info.addStringPermission(pres.getName());
                                                System.out.println(pres);
                                            }
                                    );
                                }
                            }
                        }
                );
            });
            return  info;
        }

编写前台页面

首先导入约束

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

编写测试页面

  <!-- 验证当前用户是否具有该 admin 角色,若拥有,则显示 a 标签的内容 -->
   <span> <a shiro:hasRole="admin" href="#">是否为admin用户</a></span>
<!--授权角色-->
   <span> <a shiro:hasRole="user" href="#">是否为user用户</a></span>
    <span shiro:principal="">
        获取身份信息
    </span>
<!-- 认证后展示-->
    <span shiro:authenticated="">
        认证后展示
    </span>
    <!-- 认证没通过展示-->
    <span shiro:notAuthenticated="">
        认证没通过展示
    </span>
    <span shiro:hasPermission="add">
        具有用户add权限
    </span>

总结:

其实shiro并不难,难的就是逻辑,逻辑通了,写起来就很快
入门很快,精通难,多结合项目跑起来就很容易理解了
点击跳转gitee

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值