shiro权限

什么是shiro

Shiro是apache旗下一个开源框架,它将软件系统的安全认证相关的功能抽取出来,实现用户身份认证,权限授权、加密、会话管理等功能,组成了一个通用的安全认证框架。

shiro架构

在这里插入图片描述

Subject

Subject即主体,外部应用与subject进行交互,subject记录了当前操作用户,将用户的概念理解为当前操作的主体,可能是一个通过浏览器请求的用户,也可能是一个运行的程序。

Subject在shiro中是一个接口,接口中定义了很多认证授权相关的方法,外部程序通过subject进行认证授权而subject是通过SecurityManager安全管理器进行认证授权。

Security Manager

SecurityManager即安全管理器,对全部的subject进行安全管理,它是shiro的核心,负责对所有的subject进行安全管理。通过SecurityManager可以完成subject的认证、授权等,实质上SecurityManager是通过Authenticator进行认证,通过Authorizer进行授权,通过SessionManager进行会话管理等。

SecurityManager是一个接口,继承了Authenticator, Authorizer, SessionManager这三个接口。

Authenticator

Authenticator即认证器,对用户身份进行认证,Authenticator是一个接口,shiro提供ModularRealmAuthenticator实现类,通过ModularRealmAuthenticator基本上可以满足大多数需求,用户也可以自定义认证器。

Authorizer

Authorizer即授权器,用户通过认证器认证通过,在访问功能时需要通过授权器判断用户是否有此功能的操作权限。

Realm

Realm即领域,相当于datasource数据源,securityManager进行安全认证需要通过Realm获取用户权限数据,比如:如果用户身份数据在数据库那么realm就需要从数据库获取用户身份信息。

注意:不要把realm理解成只是从数据源取数据,在realm中还有认证授权校验的相关的代码。

sessionManager

sessionManager即会话管理,shiro框架定义了一套会话管理,它不依赖web容器的session,所以shiro可以使用在非web应用上,也可以将分布式应用的会话集中在一点管理,此特性可使它实现单点登录。

sessionDao

SessionDAO即会话dao,是对session会话操作的一套接口,比如要将session存储到数据库,可以通过jdbc将会话存储到数据库。

CacheManager

CacheManager即缓存管理,将用户权限数据存储在缓存,这样可以提高性能。

Cryptography

Cryptography即密码管理,shiro提供了一套加密/解密的组件,方便开发。比如提供常用的散列、加/解密等功能。

shiro相关依赖

在这里插入图片描述

引入所有shiro依赖

在这里插入图片描述

散列示例

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

/**
 * @豆豆 2021/5/3 14:39
 */
public class TestHash {
    @Test
    public void testMd5(){
        String s1=new Md5Hash("123").toString();
        System.out.println(s1+"散列一次,未加盐");
        String s2=new Md5Hash("123","aaa").toString();
        System.out.println(s2+"散列一次,加盐aaa");
        String s3=new Md5Hash("123","aaa",2).toString();
        System.out.println(s3+"散列2次,加盐aaa");
    }
    
}

1、创建一个maven项目

在这里插入图片描述

1.1设置utf-8编码

在这里插入图片描述

1.2设置maven仓库

在这里插入图片描述

2、编写pom.xml文件

2.1添加shiro依赖

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

测试依赖

<dependency>
   <groupId>junit</groupId>
   <artifactId>junit</artifactId>
   <version>4.13</version>
   <scope>test</scope>
</dependency>

3、编写ini配置文件

[main]
#定义凭证匹配器
a=org.apache.shiro.authc.credential.HashedCredentialsMatcher
#散列算法
a.hashAlgorithmName=md5
#散列次数0
a.hashIterations=1

myrealm=com.zy.util.MyRealm
securityManager.realms=$myrealm
myrealm.credentialsMatcher=$a
    
    
  --------------------------------------------------------------------------  
    
[users]
#用户zhang,密码123,拥有role1和role2两个角色
zhangsan=123,role1,role2
lisi=123,role1
[roles]
#角色role1对资源user拥有create和update权限
role1=user:create,user:update
role2=user:create,user:delete

4、自定义Realm类

package com.zy.util;

import com.zy.dao.UserDao;
import com.zy.pojo.User;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import java.time.LocalDate;

/**
 * @豆豆 2021/5/1 16:26
 */
//自定义realm
public class MyRealm extends AuthorizingRealm {
    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }
    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //获取用户身份信息(如: 用户名/邮箱账户/手机号)
        String principal = (String) token.getPrincipal();

        //查询user
        UserDao userDao = new UserDao();
        User user =userDao.getUserByName(principal);
        if (user.getEndTime().compareTo(LocalDate.now())<0){
            throw new ExpiredCredentialsException();
        }
        if (user==null){

        }
        //返回认证信息由父类AuthenticatingRealm进行认证  (身份信息,数据库密码,当前realm)
        return new SimpleAuthenticationInfo(principal,user.getPassword(),getName());
    }
}

5、模拟数据库

package com.zy.dao;

import com.zy.pojo.User;

import java.time.LocalDate;
import java.util.HashMap;
import java.util.Map;

/**
 * @豆豆 2021/5/1 16:26
 */
public class UserDao {
    //模拟数据库
    public static Map<String,Object> map = new HashMap<>();
    static{
        map.put("zhangsan",new User(10,"zhangsan","123", LocalDate.parse("2021-05-10")));
        map.put("lisi",new User(20,"李四","123",LocalDate.parse("2020-05-10")));
    }
    //根据用户名查询用户
    public User getUserByName(String username){

        return (User) map.get(username);
    }
}

6、封装实体类,有参无参

package com.zy.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.time.LocalDate;

/**
 * @豆豆 2021/5/1 16:28
 */
@Data
@AllArgsConstructor//有参
@NoArgsConstructor//无参
public class User {
    private Integer id;
    private String username;
    private String password;
    private LocalDate endTime;
}

7、测试类

public class TestShiro {
    @Test
    public void testshiro(){
        //创建securitymanager 环境
        //构建SecurityManager工厂
        Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
        //创建securitymanager
        SecurityManager securityManager = factory.getInstance();
        //把securityManager设置到运行环境中
        SecurityUtils.setSecurityManager(securityManager);

        //创建subject主体
        Subject subject = SecurityUtils.getSubject();
        //创建token令牌
        UsernamePasswordToken token = new UsernamePasswordToken("zhangsan","123");
        try{
            //提交认证
            subject.login(token);
            System.out.println("登录成功,欢迎:"+subject.getPrincipal());
        }catch(UnknownAccountException e){
            e.printStackTrace();
            System.out.println("账户错误");
        }catch(IncorrectCredentialsException e){
            e.printStackTrace();
            System.out.println("密码错误");
        }catch(ExpiredCredentialsException e){
            e.printStackTrace();
            System.out.println("凭证过期");
        }

        //用户认证的状态
        System.out.println("state:" + subject.isAuthenticated());

        //退出
        subject.logout();
        System.out.println("用户退出---");
        System.out.println("state:" + subject.isAuthenticated());
    }
}

springboot+shiro整合

1.1、导包

        <!--shiro+spring-->
        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-spring</artifactId>
            <version>1.3.2</version>
        </dependency>

1.2、配置类

Config层

ShiroConfig
package com.zy.config;

import com.zy.service.UserService;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.mgt.SecurityManager;
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 javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * @豆豆 2021/5/3  14:43
 */
@Configuration
public class ShiroConfig {
    @Resource
    private UserService userService;
    //过滤链配置  ,入口类
    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(){
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        shiroFilterFactoryBean.setSecurityManager(securityManager());

        //过滤器链配置
        Map<String,String> filterchains = new HashMap<>();
        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterchains);
        filterchains.put("/logout1","logout");
        filterchains.put("/**","authc");
        filterchains.put("/common/**","anon");
        filterchains.put("/css/**","anon");
        filterchains.put("/webjars/**","anon");
        filterchains.put("/login","anon");

        // 默认/, 现在设置为/login
        shiroFilterFactoryBean.setLoginUrl("/login");
        return shiroFilterFactoryBean;
    }
    //安全管理器
    @Bean
    public SecurityManager securityManager(){
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setRealm(smbmsRealm());
        return securityManager;
    }
    //自定义realm
    @Bean
    public SmbmsRealm smbmsRealm(){
        SmbmsRealm smbmsRealm = new SmbmsRealm();
        smbmsRealm.setCredentialsMatcher(credentialsMatcher());
        smbmsRealm.setUserService(userService);
        return smbmsRealm;
    }
    //凭证匹配器
    @Bean
    public HashedCredentialsMatcher credentialsMatcher(){
        HashedCredentialsMatcher credentialsMatcher = new HashedCredentialsMatcher();
        credentialsMatcher.setHashAlgorithmName("md5");
        credentialsMatcher.setHashIterations(1);
        return credentialsMatcher;
    }
}
自定义类SmbmsRealm
package com.zy.config;


import com.zy.pojo.User;
import com.zy.service.UserService;
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.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import javax.annotation.Resource;

/**
 * 自定义realm
 * @豆豆 2021/5/3  14:44
 */
public class SmbmsRealm extends AuthorizingRealm {
    private UserService userService;

    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }
    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String prin= (String) token.getPrincipal();
        //数据查询
        User user = userService.getUserByUserCode(prin);
        if (user==null){
            return null;
        }
        //加盐
        SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(prin,user.getPassword(), ByteSource.Util.bytes(user.getSalt()),getName());
        //认证信息
        return simpleAuthenticationInfo;
    }
}

1.3、登录 jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>登录页面</title>
    <%@include file="/common/header.jsp"%>
</head>
<body>
    <div id="root">
        <card style="width: 30%;margin: 100px auto">
            <p slot="title">
                用户登录
            </p>
            <i-form style="width: 60%;margin: 20px auto;" action="${pageContext.request.contextPath}/login" method="post">
                <%--<c:if test="${not empty loginErr}">--%>
                    <%--<alert type="error" show-icon>${loginErr}</alert>--%>
                <%--</c:if>--%>
                <form-item>                         <%--用户编码--%>
                    <i-input prefix="ios-contact" name="userCode" placeholder="请输入用户名" size="large"></i-input>
                </form-item>
                <form-item>                         <%--密码--%>
                    <i-input prefix="ios-lock" name="password" type="password" placeholder="请输入密码" size="large"></i-input>
                </form-item>
                <form-item>         <%--点击登录这是发送按钮--%>
                    <i-button html-type="submit" type="primary" style="margin-left: 100px">登录</i-button>
                </form-item>
            </i-form>
        </card>
    </div>
</body>
<script>
    new Vue({
        el:"#root"
    })
</script>
</html>

登录成功

在这里插入图片描述

授权

1、异常处理

@ExceptionHandler({RuntimeException.class})
    public void handlerException(RuntimeException ex, Model model){
        String msg="";
        if (ex instanceof UnknownAccountException){
            msg="账户或者密码输入错误";
        }else if(ex instanceof IncorrectCredentialsException){
            msg="账户或者密码输入错误";
        }else{
            msg="其他....";
        }
        model.addAttribute("loginErr",msg);
    }

2、授权认证

2.1、授权

@Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String prin= (String) token.getPrincipal();
        //数据查询
        User user = userService.getUserByUserCode(prin);
        if (user==null){
            return null;
        }
        SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(user,user.getPassword(), ByteSource.Util.bytes(user.getSalt()),getName());
        //认证信息
        return simpleAuthenticationInfo;
    }

2.2、认证

@Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        User user = (User) principalCollection.getPrimaryPrincipal();
        //从数据库查询permCodes
        List<String> permCodes =permissionService.getPermcodes(user.getId());
        //授权信息
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        simpleAuthorizationInfo.addStringPermissions(permCodes);
        return simpleAuthorizationInfo;
    }

2.3、Service

 //查询一级/二级菜单
   public List<Permission> getMenus();

2.4、impl

@Override
    public List<Permission> getMenus() {
        Subject subject = SecurityUtils.getSubject();
        //一级菜单
        List<Permission> menus01 = this.getMenuList(null);
        menus01 = menus01.stream().filter(permission ->subject.isPermitted(permission.getPermCode())).collect(Collectors.toList());
        for (Permission per01:menus01
             ) {
            //二级菜单
            List<Permission> menus02 = this.getMenuList(per01.getId());
            menus02 = menus02.stream().filter(permission2 ->subject.isPermitted(permission2.getPermCode())).collect(Collectors.toList());
            per01.setChildren(menus02);
        }
        return menus01;
    }
//特有的查询一级菜单/二级菜单方法
    public List<Permission> getMenuList(Integer pid){
        QueryWrapper queryWrapper = new QueryWrapper();
        if (pid==null){
            queryWrapper.isNull("parent_id");
        }else{
            queryWrapper.eq("parent_id",pid);
        }
        List<Permission> permissions = super.list(queryWrapper);
        return permissions;
    }

2.5、jsp

<c:forEach items="${menusList}" var="per01" varStatus="status01">
  <Submenu name="${status01.count}">    
    <template slot="title">        
      <Icon type="${per01.icon}"></Icon>        
      ${per01.name}    
    </template>    
    <c:forEach items="${per01.children}" var="per02" varStatus="status02">    
      <Menu-Item name="${status01.count-status02.count}">        
        <a href="${per02.url}" target="main">${per02.name}</a>    
      </Menu-Item>    
    </c:forEach></Submenu></c:forEach>

3、链接权限

shiro的权限授权是通过继承 AuthorizingRealm 抽象类,重载 doGetAuthorizationInfo();
当访问到页面的时候,链接配置了相应的权限或者shiro标签才会执行此方法否则不会执行,所以如果只是简单的身份认证没有权限的控制的话,那么这个方法可以不进行实现,直接返回null即可。
在这个方法中主要是使用类:SimpleAuthorizationInfo 进行角色的添加和权限的添加。

@Override 
protectedAuthorizationInfodoGetAuthorizationInfo
    (PrincipalCollectionprincipals){
    System.out.println("权限配置‐‐>MyShiroRealm.doGetAuthorizationInfo()"); 		SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo(); 	   UserInfo userInfo = (UserInfo)principals.getPrimaryPrincipal(); 
    for(SysRole role:userInfo.getRoleList()){
        authorizationInfo.addRole(role.getRole());
        for(SysPermission p:role.getPermissions()){ 
            authorizationInfo.addStringPermission(p.getPermission()); 
        } 
    } 
    return authorizationInfo; 
}

Stream使用一种类似用SQL语句从数据库查询数据的直观方式来提供一种对Java集合运算和表达的高阶抽象

操作

在这里插入图片描述

4、jsp标签

没有权限隐藏按钮

<%@taglib prefix="shrio" uri="http://shiro.apache.org/tags" %>

<shrio:hasPermission name="role:add">
        <i-button type="info" @click="add()">添加角色</i-button>
        </shrio:hasPermission>

5、注解式

5、1、启动类加注解

@EnableAspectJAutoProxy(proxyTargetClass=true)

5、2、ShiroConfig中开启shiro注解支持

//开启shiro注解支持
    @Bean
    public AuthorizationAttributeSourceAdvisor advisor(){
        AuthorizationAttributeSourceAdvisor advisor = new AuthorizationAttributeSourceAdvisor();
        advisor.setSecurityManager(securityManager());
        return advisor;
    }
开启注解后可以在controller中使用注解

在这里插入图片描述

6、授权的缓存处理

引入依赖

<!--ehcache-->
<dependency>
  <groupId>net.sf.ehcache</groupId>
  <artifactId>ehcache</artifactId>
  <version>2.10.4</version>
</dependency>
<dependency>
  <groupId>org.apache.shiro</groupId>
  <artifactId>shiro-ehcache</artifactId>
  <version>1.5.3</version>
</dependency>

shiroConfig

//缓存管理器
    @Bean
    public EhCacheManager ehCacheManager(){
        EhCacheManager ehCacheManager = new EhCacheManager();
        ehCacheManager.setCacheManagerConfigFile("classpath:shiro-ehcache.xml");
        return ehCacheManager;
    }

shiro-ehcache.xml

<ehcache>
    <!--diskStore:缓存数据持久化的目录 地址  -->
    <diskStore path="d:\ehcache" />
    <defaultCache
            maxElementsInMemory="1000"
            maxElementsOnDisk="10000000"
            eternal="false"
            overflowToDisk="false"
            diskPersistent="false"
            timeToIdleSeconds="120"
            timeToLiveSeconds="120"
            diskExpiryThreadIntervalSeconds="120"
            memoryStoreEvictionPolicy="LRU">
    </defaultCache>
</ehcache>

Stream使用一种类似用SQL语句从数据库查询数据的直观方式来提供一种对Java集合运算和表达的高阶抽象

5、1、启动类加注解

@EnableAspectJAutoProxy(proxyTargetClass=true)

5、2、ShiroConfig中开启shiro注解支持

//开启shiro注解支持
    @Bean
    public AuthorizationAttributeSourceAdvisor advisor(){
        AuthorizationAttributeSourceAdvisor advisor = new AuthorizationAttributeSourceAdvisor();
        advisor.setSecurityManager(securityManager());
        return advisor;
    }
开启注解后可以在controller中使用注解

6、授权的缓存处理

引入依赖

<!--ehcache-->
<dependency>
  <groupId>net.sf.ehcache</groupId>
  <artifactId>ehcache</artifactId>
  <version>2.10.4</version>
</dependency>
<dependency>
  <groupId>org.apache.shiro</groupId>
  <artifactId>shiro-ehcache</artifactId>
  <version>1.5.3</version>
</dependency>

shiroConfig

//缓存管理器
    @Bean
    public EhCacheManager ehCacheManager(){
        EhCacheManager ehCacheManager = new EhCacheManager();
        ehCacheManager.setCacheManagerConfigFile("classpath:shiro-ehcache.xml");
        return ehCacheManager;
    }

shiro-ehcache.xml

<ehcache>
    <!--diskStore:缓存数据持久化的目录 地址  -->
    <diskStore path="d:\ehcache" />
    <defaultCache
            maxElementsInMemory="1000"
            maxElementsOnDisk="10000000"
            eternal="false"
            overflowToDisk="false"
            diskPersistent="false"
            timeToIdleSeconds="120"
            timeToLiveSeconds="120"
            diskExpiryThreadIntervalSeconds="120"
            memoryStoreEvictionPolicy="LRU">
    </defaultCache>
</ehcache>
  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

筱筱龙

你的支持是我创作的最大动力

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

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

打赏作者

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

抵扣说明:

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

余额充值