谈谈Shiro的那点事儿

shiro

Apache Shiro是一个强大且易用的Java安全框架,执行身份验证、授权、密码和会话管理。

简介

Apache Shiro 是 Java 的一个安全框架。目前,使用 Apache Shiro 的人越来越多,因为它相当简单,对比 Spring Security,可能没有 Spring Security 做的功能强大,但是在实际工作时可能并不需要那么复杂的东西,所以使用小而简单的 Shiro 就足够了。对于它俩到底哪个好,这个不必纠结,能更简单的解决项目问题就好了。

本教程只介绍基本的 Shiro 使用,不会过多分析源码等,重在使用。

Shiro 可以非常容易的开发出足够好的应用,其不仅可以用在 JavaSE 环境,也可以用在 JavaEE 环境。Shiro 可以帮助我们完成:认证、授权、加密、会话管理、与 Web 集成、缓存等。这不就是我们想要的嘛,而且 Shiro 的 API 也是非常简单;其基本功能点如下图所示:
在这里插入图片描述
Authentication:身份认证 / 登录,验证用户是不是拥有相应的身份;

Authorization:授权,即权限验证,验证某个已认证的用户是否拥有某个权限;即判断用户是否能做事情,常见的如:验证某个用户是否拥有某个角色。或者细粒度的验证某个用户对某个资源是否具有某个权限;

Session Management:会话管理,即用户登录后就是一次会话,在没有退出之前,它的所有信息都在会话中;会话可以是普通 JavaSE 环境的,也可以是如 Web 环境的;

Cryptography:加密,保护数据的安全性,如密码加密存储到数据库,而不是明文存储;

Web Support:Web 支持,可以非常容易的集成到 Web 环境;

Caching:缓存,比如用户登录后,其用户信息、拥有的角色 / 权限不必每次去查,这样可以提高效率;

Concurrency:shiro 支持多线程应用的并发验证,即如在一个线程中开启另一个线程,能把权限自动传播过去;

Testing:提供测试支持;

Run As:允许一个用户假装为另一个用户(如果他们允许)的身份进行访问;

Remember Me:记住我,这个是非常常见的功能,即一次登录后,下次再来的话不用登录了。

记住一点,Shiro 不会去维护用户、维护权限;这些需要我们自己去设计 / 提供;然后通过相应的接口注入给 Shiro 即可。

接下来我们分别从外部和内部来看看 Shiro 的架构,对于一个好的框架,从外部来看应该具有非常简单易于使用的 API,且 API 契约明确;从内部来看的话,其应该有一个可扩展的架构,即非常容易插入用户自定义实现,因为任何框架都不能满足所有需求。

首先,我们从外部来看 Shiro 吧,即从应用程序角度的来观察如何使用 Shiro 完成工作。如下图:
在这里插入图片描述
可以看到:应用代码直接交互的对象是 Subject,也就是说 Shiro 的对外 API 核心就是 Subject;其每个 API 的含义:

Subject:主体,代表了当前 “用户”,这个用户不一定是一个具体的人,与当前应用交互的任何东西都是 Subject,如网络爬虫,机器人等;即一个抽象概念;所有 Subject 都绑定到 SecurityManager,与 Subject 的所有交互都会委托给 SecurityManager;可以把 Subject 认为是一个门面;SecurityManager 才是实际的执行者;

SecurityManager:安全管理器;即所有与安全有关的操作都会与 SecurityManager 交互;且它管理着所有 Subject;可以看出它是 Shiro 的核心,它负责与后边介绍的其他组件进行交互,如果学习过 SpringMVC,你可以把它看成 DispatcherServlet 前端控制器;

Realm:域,Shiro 从从 Realm 获取安全数据(如用户、角色、权限),就是说 SecurityManager 要验证用户身份,那么它需要从 Realm 获取相应的用户进行比较以确定用户身份是否合法;也需要从 Realm 得到用户相应的角色 / 权限进行验证用户是否能进行操作;可以把 Realm 看成 DataSource,即安全数据源。

也就是说对于我们而言,最简单的一个 Shiro 应用:

  1. 应用代码通过 Subject 来进行认证和授权,而 Subject 又委托给 SecurityManager;
  2. 我们需要给 Shiro 的 SecurityManager 注入 Realm,从而让 SecurityManager 能得到合法的用户及其权限进行判断。

从以上也可以看出,Shiro 不提供维护用户 / 权限,而是通过 Realm 让开发人员自己注入。

接下来我们来从 Shiro 内部来看下 Shiro 的架构,如下图所示:
在这里插入图片描述
Subject**:主体,可以看到主体可以是任何可以与应用交互的 “用户”;

SecurityManager:相当于 SpringMVC 中的 DispatcherServlet 或者 Struts2 中的 FilterDispatcher;是 Shiro 的心脏;所有具体的交互都通过 SecurityManager 进行控制;它管理着所有 Subject、且负责进行认证和授权、及会话、缓存的管理。

Authenticator:认证器,负责主体认证的,这是一个扩展点,如果用户觉得 Shiro 默认的不好,可以自定义实现;其需要认证策略(Authentication Strategy),即什么情况下算用户认证通过了;

Authrizer:授权器,或者访问控制器,用来决定主体是否有权限进行相应的操作;即控制着用户能访问应用中的哪些功能;

Realm:可以有 1 个或多个 Realm,可以认为是安全实体数据源,即用于获取安全实体的;可以是 JDBC 实现,也可以是 LDAP 实现,或者内存实现等等;由用户提供;注意:Shiro 不知道你的用户 / 权限存储在哪及以何种格式存储;所以我们一般在应用中都需要实现自己的 Realm;

SessionManager:如果写过 Servlet 就应该知道 Session 的概念,Session 呢需要有人去管理它的生命周期,这个组件就是 SessionManager;而 Shiro 并不仅仅可以用在 Web 环境,也可以用在如普通的 JavaSE 环境、EJB 等环境;所以呢,Shiro 就抽象了一个自己的 Session 来管理主体与应用之间交互的数据;这样的话,比如我们在 Web 环境用,刚开始是一台 Web 服务器;接着又上了台 EJB 服务器;这时想把两台服务器的会话数据放到一个地方,这个时候就可以实现自己的分布式会话(如把数据放到 Memcached 服务器);

SessionDAO:DAO 大家都用过,数据访问对象,用于会话的 CRUD,比如我们想把 Session 保存到数据库,那么可以实现自己的 SessionDAO,通过如 JDBC 写到数据库;比如想把 Session 放到 Memcached 中,可以实现自己的 Memcached SessionDAO;另外 SessionDAO 中可以使用 Cache 进行缓存,以提高性能;

CacheManager:缓存控制器,来管理如用户、角色、权限等的缓存的;因为这些数据基本上很少去改变,放到缓存中后可以提高访问的性能

Cryptography:密码模块,Shiro 提供了一些常见的加密组件用于如密码加密 / 解密的。

到此 Shiro 架构及其组件就认识完了,接下来挨着学习 Shiro 的组件吧。

三个核心组件

三个核心组件: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是可以的,但是至少需要一个。

使用

使用步骤如下:

1、收集实体/凭据信息

    UsernamePasswordToken token =   new UsernamePasswordToken(username, password);
    token.setRememberMe(true);

2、提交实体/凭据信息

    Subject currentUser = SecurityUtils.getSubject();   
    currentUser.login(token);

3、认证

如果我们自定义Realm实现,比如我后面的例子中,自定义了ShiroDbRealm类,当执行currentUser.login(token)时,会先执行ShiroDbRealm.doGetAuthorizationInfo()进行认证

/**       * 验证当前登录的Subject       
* @see经测试:本例中该方法的调用时机为  
* LoginController.login()方法中执行Subject.login()时      
*/ 
   protected AuthenticationInfo   doGetAuthenticationInfo(AuthenticationTokenauthcToken)  throws AuthenticationException {
    
    
    //获取基于用户名和密码的令牌 
    //实际上这个authcToken是从LoginController里面 currentUser.login(token)传过来的
    UsernamePasswordToken token =  (UsernamePasswordToken) authcToken;
    //从数据库中查询用户用信息
    Useruser = userService.getByAccount(token.getUsername());
   if(user != null) {
    
    
    //此处无需比对,比对的逻辑Shiro会做,
   //我们只需返回一个和令牌相关的正确的验证信息
     returnnew SimpleAuthenticationInfo(  user.getAccount(),
                                  user.getPassword(),getName());
    }else {
    
    
    //没有返回登录用户名对应的SimpleAuthenticationInfo对象时,
    // 就会在LoginController中抛出UnknownAccountException异常
       return null; 
   }
}

4、认证处理

try {
    
    
         currentUser.login(token);
} catch ( UnknownAccountException uae ) {
    
    
      ...
} catch ( IncorrectCredentialsException ice ) {
    
     
      ...   
} catch ( LockedAccountException lae ) {
    
    
      ...   
} catch ( ExcessiveAttemptsException eae ) {
    
    
     ...    } ... catch your own ...     
} catch ( AuthenticationException ae) {
    
    
        //unexpected error?     } 

5、登出操作

登出操作可以通过调用subject.logout()来删除你的登录信息,如:

 currentUser.logout(); 

慕课课程笔记

什么是shiro

  • Apache的强大的灵活的开源安全框架
  • 认证、授权、企业会话管理、安全加密

非常快捷方便的完成项目中 【权限管理模块】的开发

shiro与spring security之间的比较

shiro

  • 简单灵活
  • 可脱离spring
  • 粒度较粗

spring security

  • 复杂笨重
  • 不可脱离Spring
  • 粒度更细

shiro整体架构

在这里插入图片描述

shiro认证

  • 创建SecurityManager
  • 主题提交认证
  • SecurityManager认证
  • Authenticator认证
  • Realm认证

shiro授权

  • 创建SecuritiyManager
  • 主题授权
  • SecurityManager授权
  • Authorizer授权
  • Realm获取角色权限数据

shiro自定义Realm

内置Realm
  • IniRealm
  • JdbcRealm

Demo

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.realm.SimpleAccountRealm;
import org.apache.shiro.subject.Subject;
import org.junit.Before;
import org.junit.Test;

public class test {
    
    
    SimpleAccountRealm simpleAccountRealm = new SimpleAccountRealm();
    @Before
    public void addUser(){
    
    
        simpleAccountRealm.addAccount("mark","123456");
    }
    @Test
    public void testshiro(){
    
    
        //构建SecurityManager环境
        DefaultSecurityManager defaultSecurityManager = new DefaultSecurityManager();
        defaultSecurityManager.setRealm(simpleAccountRealm);
        //主体提交认证请求
        SecurityUtils.setSecurityManager(defaultSecurityManager);
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken("mark","123456");
        subject.login(token);
        System.out.println(" subject.isAuthenticated(): " +  subject.isAuthenticated());
    }
}

JdbcRealmDemo

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.realm.jdbc.JdbcRealm;
import org.apache.shiro.subject.Subject;
import org.junit.Test;

public class JDBCRealmTest {
    
    
    //设置数据源
    DruidDataSource dataSource = new DruidDataSource();
    {
    
    
        dataSource.setUrl("jdbc:mysql://localhost:3306/test");
        dataSource.setUsername("root");
        dataSource.setPassword("aaaaaa");
    }
    @Test
    public void testshiro(){
    
    
        JdbcRealm jdbcRealm = new JdbcRealm();
        jdbcRealm.setDataSource(dataSource);
        //jdbcRealm在查询权限相关的时候需要开启,默认是不开启的
        jdbcRealm.setPermissionsLookupEnabled(true);
        //构建SecurityManager环境
        DefaultSecurityManager defaultSecurityManager = new DefaultSecurityManager();
        defaultSecurityManager.setRealm(jdbcRealm);
        //主体提交认证请求
        SecurityUtils.setSecurityManager(defaultSecurityManager);
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken("mark","123456");
        subject.login(token);
        System.out.println("subject.isAuthenticated():" + subject.isAuthenticated());
        subject.checkRole("admin");
        subject.checkPermission("user:update");
    }
}

其中表结构如下
在这里插入图片描述
注意:在jdbcrealm的权限查询需要开启

其中JDBCRealm中有默认的查询语句,表结构就如上图所示

当然我们也可以自定义

      //自定义表,查询
        String sql = "select password from test_user where username = ?";
        jdbcRealm.setAuthenticationQuery(sql);

自定义Realm

我们先翻看一下JdbcRealm,发现它是继承了 AuthorizingRealm,因此我们在自定义realm也需要继承这个类

package realm;

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.realm.SimpleAccountRealm;
import org.apache.shiro.subject.PrincipalCollection;

import java.util.HashMap;
import java.util.Map;

public class CustomRealm extends AuthorizingRealm {
    
    
    Map<String,String> userMap = new HashMap<String, String>();
    {
    
    
        userMap.put("mark","123456");
        super.setName("customReal");
    }
    //做授权处理
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
    
    
        return null;
    }
    //做认证处理
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
    
    
        //首先通过 主体传过来的认证信息中获取用户名
        String username = (String)token.getPrincipal();
        //通过用户名获取到数据库中的凭证
        String passsword = GetPasswordByUsername(username);
        if (passsword == null){
    
    
            return null;
        }
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo("mask",passsword,"customrealm");
        return authenticationInfo;
    }

    /** 
    * @Description: 模拟数据库获取数据
    * @Param:  username 输入参数 传入的username信息
    * @return:  
    * @Author: Liuzhiliang
    * @Date:  
    */ 
    private String GetPasswordByUsername(String username){
    
    
        return userMap.get(username);
    }
}

shiro的加密

shiro的散列配置
  • HashedCredentialsMatcher
  • 自定义Realm中使用散列
  • 加盐

针对于上面做的自定义Realm,进行加盐加密

//做认证处理
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
    
    
    //首先通过 主体传过来的认证信息中获取用户名
    String username = (String)token.getPrincipal();
    //通过用户名获取到数据库中的凭证
    String passsword = GetPasswordByUsername(username);
    if (passsword == null){
    
    
        return null;
    }
    SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo("mask",passsword,"customrealm");
    //加盐解析
    authenticationInfo.setCredentialsSalt(ByteSource.Util.bytes("mark"));
    return authenticationInfo;
}

测试用例代码:

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.realm.jdbc.JdbcRealm;
import org.apache.shiro.subject.Subject;
import org.junit.Test;
import realm.CustomRealm;

/**
 * @program: testmaven
 * @description: 测试自定义Realm
 * @author: LiuZhiliang
 * @create: 2021-04-08 11:22
 **/
public class CustomRealmTest {
    
    
    @Test
    public void testshiro(){
    
    
        CustomRealm customRealm = new CustomRealm();
        //构建SecurityManager环境
        DefaultSecurityManager defaultSecurityManager = new DefaultSecurityManager();
        defaultSecurityManager.setRealm(customRealm);


    /*--------------------------------------------
    |             加密处理             |
    ============================================*/
    //1、先创建 HashedCredentialsMatcher
        HashedCredentialsMatcher matcher = new HashedCredentialsMatcher();
    //2、设置加密算法的名称、加密的次数
        matcher.setHashAlgorithmName("md5");
        matcher.setHashIterations(1);
    //3、设置加密对象
        customRealm.setCredentialsMatcher(matcher);

        //主体提交认证请求
        SecurityUtils.setSecurityManager(defaultSecurityManager);
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken("mark","123456");
        subject.login(token);
        System.out.println("subject.isAuthenticated():" + subject.isAuthenticated());
    }
}

加密使用步骤如下:

1、创建 HashedCredentialsMatcher

 HashedCredentialsMatcher matcher = new HashedCredentialsMatcher();

2、设置加密算法名称、加密次数

 matcher.setHashAlgorithmName("md5");
 matcher.setHashIterations(1);

3、设置加密对象

 customRealm.setCredentialsMatcher(matcher);

在自定义的Realm中需要对 【盐】 进行解析

authenticationInfo.setCredentialsSalt(ByteSource.Util.bytes(“mark”));

这里的 “ mark ” 为加盐的字符,理论上是随机字符,存放在数据库中

整合实例(SpringBoot + shiro)

pojo
User
package com.rongwei.boot01web01.pojos;

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

import java.util.Set;

/**
 * @program: boot-01-web-01
 * @description: 用户实体
 * @author: LiuZhiliang
 * @create: 2021-04-09 09:19
 **/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class user {
    
    
    public Integer id;
    public String username;
    public String password;
    private Set<roles> rolesSet;
}
Roles
package com.rongwei.boot01web01.pojos;

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

import java.util.Set;

/**
 * @program: boot-01-web-01
 * @description: 角色实体类
 * @author: LiuZhiliang
 * @create: 2021-04-09 09:21
 **/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class roles {
    
    
    private Integer id;
    private String rolename;
    private Set<Permissions> permissions;
}
Permissions
package com.rongwei.boot01web01.pojos;

import lombok.AllArgsConstructor;
import lombok.Data;

/**
 * @program: boot-01-web-01
 * @description: 权限实体类
 * @author: LiuZhiliang
 * @create: 2021-04-09 09:23
 **/
@Data
@AllArgsConstructor
public class Permissions {
    
    
    private String id;
    private String permissionName;
}
service
LoginService
package com.rongwei.boot01web01.service;

import com.rongwei.boot01web01.pojos.user;

public interface LoginService {
    
    
    public user getUserByName(String username);
}
LoginServiceImpl
package com.rongwei.boot01web01.service.serviceImpl;

import com.rongwei.boot01web01.pojos.Permissions;
import com.rongwei.boot01web01.pojos.roles;
import com.rongwei.boot01web01.pojos.user;
import com.rongwei.boot01web01.service.LoginService;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * @program: boot-01-web-01
 * @description: LoginService实现类
 * @author: LiuZhiliang
 * @create: 2021-04-09 09:25
 **/
@Service
public class LoginServiceImpl implements LoginService {
    
    
    /** 
    * @Description: 模拟数据库数据 
    * @Param:
    * @return:  
    * @Author: Liuzhiliang
    * @Date:  
    */ 
    @Override
    public user getUserByName(String username) {
    
    
        Permissions permissions1 = new Permissions("1","add");
        Permissions permissions2 = new Permissions("2","query");
        Set<Permissions> permissionsSet = new HashSet<>();
        permissionsSet.add(permissions1);
        permissionsSet.add(permissions2);
        roles role = new roles(1,"admin",permissionsSet);
        Set<roles> rolesSet = new HashSet<>();
        rolesSet.add(role);
        user user = new user(1,"mark","73bea81c6c06bacab41a995495239545",rolesSet);
        Map<String,user> usermap = new HashMap<>();
        usermap.put(user.getUsername(),user);

        return usermap.get(username);
    }

    public static void main(String[] args) {
    
    
        Md5Hash md5Hash = new Md5Hash("123456","mark");
        System.out.println(md5Hash.toString());
    }
}
controller
LoginController
package com.rongwei.boot01web01.controller;

import com.rongwei.boot01web01.pojos.user;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @program: boot-01-web-01
 * @description: 登录控制器
 * @author: LiuZhiliang
 * @create: 2021-04-09 10:02
 **/
@RestController
public class LoginController {
    
    
    @GetMapping("/login")
    public String login(user user){
    
    
        System.out.println("User" + user);
        if (!StringUtils.hasLength(user.getUsername())||!StringUtils.hasLength(user.getPassword())){
    
    
            return "请输入用户名密码!";
        }
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(),user.getPassword());
        try {
    
    
            subject.login(token);
        } catch (AuthenticationException e) {
    
    
            return "登录出错";
        }
        return "登录成功";
    }

    @RequiresRoles("admin")
    @GetMapping("/admin")
    public String admin(){
    
    
        return "admin success";
    }

    @RequiresPermissions("dd")
    @GetMapping("/index")
    public String index(){
    
    
        return "index success";
    }

}
config
ShiroConfig
package com.rongwei.boot01web01.config;

import com.rongwei.boot01web01.shiro.MyShiro;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.mgt.AuthenticatingSecurityManager;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.realm.jdbc.JdbcRealm;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
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;
import java.util.Map;

/**
 * @program: boot-01-web-01
 * @description: shiro配置类,将SecurityManager以及Realm都注入到Spring容器中
 * @author: LiuZhiliang
 * @create: 2021-04-09 08:57
 **/
@Configuration
public class ShiroConfig {
    
    
    /** 
    * @Description: Filter工厂,设置对应的过滤条件和跳转条件
    * @Param:
    * @return:
    * @Author: Liuzhiliang
    * @Date:
    */ 
    @Bean
    public ShiroFilterFactoryBean shiroFilter(DefaultSecurityManager securityManager){
    
    
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        shiroFilterFactoryBean.setSecurityManager(securityManager);
        Map<String,String> maps = new HashMap<>();
        maps.put("/logout","logout");
        maps.put("/**","authc");
        shiroFilterFactoryBean.setLoginUrl("/login");
        shiroFilterFactoryBean.setUnauthorizedUrl("/403.html");
        shiroFilterFactoryBean.setSuccessUrl("/index");
        shiroFilterFactoryBean.setFilterChainDefinitionMap(maps);
        return shiroFilterFactoryBean;
    }

    @Bean
    public MyShiro myShiro(){
    
    
        HashedCredentialsMatcher matcher = new HashedCredentialsMatcher();
        //加密
        matcher.setHashAlgorithmName("md5");
        matcher.setHashIterations(1);
        MyShiro myShiro = new MyShiro();
        myShiro.setCredentialsMatcher(matcher);
        return myShiro;
    }

    @Bean
    public DefaultWebSecurityManager securityManager(){
    
    
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setRealm(myShiro());
        return securityManager;
    }
    @Bean
    public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(DefaultWebSecurityManager securityManager) {
    
    
        AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
        authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
        return authorizationAttributeSourceAdvisor;
    }
}
myrealm
package com.rongwei.boot01web01.shiro;

import com.rongwei.boot01web01.pojos.Permissions;
import com.rongwei.boot01web01.pojos.roles;
import com.rongwei.boot01web01.pojos.user;
import com.rongwei.boot01web01.service.LoginService;
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.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @program: boot-01-web-01
 * @description: Shiro实例
 * @author: LiuZhiliang
 * @create: 2021-04-09 10:25
 **/
public class MyShiro extends AuthorizingRealm {
    
    

    @Autowired
    LoginService loginService;

    /**
    * @Description: 权限配置
    * @Param:
    * @return:
    * @Author: Liuzhiliang
    * @Date:
    */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
    
    
        String username = (String) principals.getPrimaryPrincipal();
        user user = loginService.getUserByName(username);
        //添加角色权限
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        for (roles role : user.getRolesSet()){
    
    
            simpleAuthorizationInfo.addRole(role.getRolename());
            //添加权限信息
            for (Permissions permissions : role.getPermissions()){
    
    
                simpleAuthorizationInfo.addStringPermission(permissions.getPermissionName());
            }
        }
        return simpleAuthorizationInfo;
    }

    /**
    * @Description: 认证配置
    * @Param:
    * @return:
    * @Author: Liuzhiliang
    * @Date:
    */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
    
    
        String username = token.getPrincipal().toString();
        user user = loginService.getUserByName(username);
        if (user == null){
    
    
            return null;
        }else {
    
    
            SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(username,user.getPassword(),getName());
            //加盐的解析
            simpleAuthenticationInfo.setCredentialsSalt(ByteSource.Util.bytes("mark"));
            return simpleAuthenticationInfo;
        }
    }
}

猜你喜欢

转载自blog.csdn.net/lzl980111/article/details/115524782