Shiro入门学习

486 阅读8分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路。

Shiro

什么是Shiro?

  • Apache Shiro是一个Java 的安全(权限)框架。
  • Shiro可以非常容易的开发出足够好的应用,其不仅可以用在JavaSE环境,也可以用在JavaEE环境。
  • Shiro可以完成,认证,授权,加密,会话管理,Web集成,缓存等.
  • 下载地址: shiro.apache.org/

功能

../image-20211013005127667

  • Authentication: 身份认证、登录,验证用户是不是拥有相应的身份;
  • Authorization:授权,即权限验证,验证某个已认证的用户是否拥有某个权限,即判断用户能否进行什么操作,如:验证某个用户是否拥有某个角色,或者细粒度的验证某个用户对某个资源是否具有某个权限!
  • Session Manager: 会话管理,即用户登录后就是第-次会话,在没有退出之前,它的所有信息都在会话中;会话可以是普通的JavaSE环境,也可以是Web环境;
  • Cryptography: 加密,保护数据的安全性,如密码加密存储到数据库中,而不是明文存储;
  • Web Support: Web支持,可以非常容易的集成到Web环境;
  • Caching: 缓存,比如用户登录后,其用户信息,拥有的角色、权限不必每次去查,这样可以提高效率
  • Concurrency: Shiro支持多线程应用的并发验证,即,如在-个线程中开启另-一个线程,能把权限自动的传播过去
  • Testing:提供测试支持;
  • RunAs:允许一个用户假装为另-一个用户(如果他们允许)的身份进行访问;
  • Remember Me:记住我,这个是非常常见的功能,即一-次登录后, 下次再来的话不用登录了

shiro架构(外部)

从外部来看Shiro,即从应用程序角度来观察如何使用shiro完成工作:

image-20211013005404363

  • subject: 应用代码直接交互的对象是Subject, 也就是说Shiro的对外API核心就是Subject, Subject代表了当前的用户,这个用户不-定是一个具体的人,与当前应用交互的任何东西都是Subject,如网络爬虫,机器人等,与Subject的所有交互都会委托给SecurityManager; Subject其实是一一个门面, SecurityManageer 才是 实际的执行者
  • SecurityManager: 安全管理器,即所有与安全有关的操作都会与SercurityManager交互, 并且它管理着所有的Subject,可以看出它是Shiro的核心,它负责与Shiro的其他组件进行交互,它相当于SpringMVC的DispatcherServlet的角色
  • Realm: Shiro从Realm获取安全数据 (如用户,角色,权限),就是说SecurityManager要验证用户身份,那么它需要从Realm获取相应的用户进行比较,来确定用户的身份是否合法;也需要从Realm得到用户相应的角色、权限,进行验证用户的操作是否能够进行,可以把Realm看DataSource;

Shiro架构(内部)

image-20211013005507516

  • Subject: 任何可以与应用交互的用户;
  • Security Manager:相当于SpringMVC中的DispatcherSerlet; 是Shiro的心脏, 所有具体的交互都通过Security Manager进行控制,它管理者所有的Subject, 且负责进行认证,授权,会话,及缓存的管理。
  • Authenticator:负责Subject认证, 是-一个扩展点,可以自定义实现;可以使用认证策略(Authentication Strategy),即什么情况下算用户认证通过了;
  • Authorizer:授权器,即访问控制器,用来决定主体是否有权限进行相应的操作;即控制着用户能访问应用中 的那些功能;
  • Realm: 可以有一个或者多个的realm, 可以认为是安全实体数据源,即用于获取安全实体的,可以用JDBC实现,也可以是内存实现等等,由用户提供;所以- -般在应用中都需要实现自己的realm
  • SessionManager:管理Session生 命周期的组件,而Shiro并不仅仅可以用在Web环境,也可以用在普通的JavaSE环境中
  • CacheManager: 缓存控制器,来管理如用户,角色,权限等缓存的;因为这些数据基本上很少改变,放到缓存中后可以提高访问的性能;
  • Cryptography:密码模块,Shiro 提高了一些常见的加密组件用于密码加密, 解密等

shiro入门

pom.xml文件

<dependencies>
        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-core</artifactId>
            <version>1.8.0</version>
        </dependency>
​
        <!-- configure logging -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>jcl-over-slf4j</artifactId>
            <version>1.7.21</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.7.21</version>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
</dependencies>

shiro.ini文件

#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements.  See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership.  The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License.  You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied.  See the License for the
# specific language governing permissions and limitations
# under the License.
#
# =============================================================================
# Quickstart INI Realm configuration
#
# For those that might not understand the references in this file, the
# definitions are all based on the classic Mel Brooks' film "Spaceballs". ;)
# =============================================================================# -----------------------------------------------------------------------------
# Users and their assigned roles
#
# Each line conforms to the format defined in the
# org.apache.shiro.realm.text.TextConfigurationRealm#setUserDefinitions JavaDoc
# -----------------------------------------------------------------------------
[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
​
Subject currentUser = SecurityUtils.getSubject();
Session session = currentUser.getSession();
currentUser.isAuthenticated()
currentUser.getPrincipal()
currentUser.hasRole("schwartz")
currentUser.isPermitted("lightsaber:wield")

SpringBoot中集成Shiro

  1. 导入依赖

    <dependency>
                <groupId>org.apache.shiro</groupId>
                <artifactId>shiro-spring</artifactId>
                <version>1.7.1</version>
    </dependency>
    
  2. 编写配置类

    /**
     * @author log
     * 自定义的UserRealm
     */
    public class UserRealm extends AuthorizingRealm {
    ​
        /**
         * 授权
         * @param principalCollection
         * @return
         */
        @Override
        protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
            System.out.println("执行了授权=>doGetAuthorizationInfo");
            return null;
        }
    ​
        /**
         * 认证
         * @param authenticationToken
         * @return
         * @throws AuthenticationException
         */
        @Override
        protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
            System.out.println("执行了认证=>doGetAuthenticationInfo");
            return null;
        }
    }
    ​
    
    @Configuration
    public class ShiroConfig {
    ​
        /**
         * shiroFilterFactoryBean,第三步
         * @param securityManager
         * @return
         */
        @Bean
        ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("securityManager") DefaultWebSecurityManager securityManager){
            ShiroFilterFactoryBean factoryBean = new ShiroFilterFactoryBean();
            //设置安全管理器
            factoryBean.setSecurityManager(securityManager);
            return factoryBean;
        }
    ​
        /**
         * DefaultWebSecurityManager,第二步
         * @param userRealm
         * @return
         */
        @Bean(name = "securityManager")
        DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm){
            DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
            //关联UserRealm
            securityManager.setRealm(userRealm);
            return securityManager;
        }
    ​
        /**
         * 创建realm对象,需要自定义,第一步
         * @return
         */
        @Bean
        public UserRealm userRealm(){
            return new UserRealm();
        }
    }
    ​
    

Shiro的使用

shiro实现登录拦截

  1. 在配置类中添加shiro的内置过滤器

    @Configuration
    public class ShiroConfig {
    ​
        /**
         * shiroFilterFactoryBean,第三步
         * @param securityManager
         * @return
         */
        @Bean
        ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("securityManager") DefaultWebSecurityManager securityManager){
            ShiroFilterFactoryBean factoryBean = new ShiroFilterFactoryBean();
            //设置安全管理器
            factoryBean.setSecurityManager(securityManager);
            //添加shiro的内置过滤器
            /*
                anon:无需认证就可以访问
                authc:必须认证了才能访问
                user:必须拥有“记住我”功能才能使用
                perms:拥有对某个资源的权限才能访问
                role:拥有某个角色权限才能访问
             */
            Map<String, String> filterMap = new LinkedHashMap<>();
    //        filterMap.put("/user/add","authc");
    //        filterMap.put("/user/update","authc");
            filterMap.put("/user/*","authc");
            factoryBean.setFilterChainDefinitionMap(filterMap);
            factoryBean.setLoginUrl("/toLogin");
            return factoryBean;
        }
    ​
        /**
         * DefaultWebSecurityManager,第二步
         * @param userRealm
         * @return
         */
        @Bean(name = "securityManager")
        DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm){
            DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
            //关联UserRealm
            securityManager.setRealm(userRealm);
            return securityManager;
        }
    ​
        /**
         * 创建realm对象,需要自定义,第一步
         * @return
         */
        @Bean
        public UserRealm userRealm(){
            return new UserRealm();
        }
    }
    ​
    
    @RequestMapping("/toLogin")
    public String toLogin(){
        return "login";
    }
    

shiro实现用户认证

处理登录表单提交的contoller

@RequestMapping("/login")
public String login(String username,String password,Model model){
    //获取当前的用户
    Subject subject = SecurityUtils.getSubject();
    //封装用户的登录数据
    UsernamePasswordToken token = new UsernamePasswordToken(username, password);
    //执行登录的方法,如果没有异常就成功了
    try {
        subject.login(token);
        return "index";
    }catch (UnknownAccountException e){//用户名不存在
        model.addAttribute("msg","用户名不存在!");
        return "login";
    }catch (IncorrectCredentialsException e){//密码不存在
        model.addAttribute("msg","密码错误!");
        return "login";
    }
}

UserRealm类的配置

public class UserRealm extends AuthorizingRealm {
​
    /**
     * 授权
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行了授权=>doGetAuthorizationInfo");
        return null;
    }
​
    /**
     * 认证
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("执行了认证=>doGetAuthenticationInfo");
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        //用户名,密码,数据库中获得
        String name = "root";
        String password = "123456";
        //检查用户名
        if (!token.getUsername().equals(name)){
            //自动抛出异常 UnknownAccountException
            return null;
        }
        //检查密码的工作交给shiro做
        return new SimpleAuthenticationInfo("",password,"");
    }
}

shiro整合mybatis

  1. 导入依赖

    <!--mysql驱动-->
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
            </dependency>
            <dependency>
                <groupId>log4j</groupId>
                <artifactId>log4j</artifactId>
                <version>1.2.17</version>
            </dependency>
            <dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>druid</artifactId>
                <version>1.2.6</version>
            </dependency>
            <!-- https://mvnrepository.com/artifact/org.mybatis.spring.boot/mybatis-spring-boot-starter -->
            <dependency>
                <groupId>org.mybatis.spring.boot</groupId>
                <artifactId>mybatis-spring-boot-starter</artifactId>
                <version>2.1.4</version>
            </dependency>
    
  2. 在根目录resources下创建mybatis的xml文件UserMapper.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.ywb.mapper.UserMapper">
    </mapper>
    
  3. 编写mapper和service

    @Repository
    @Mapper
    public interface UserMapper {
    ​
        public User queryUserByName(String name);
    }
    ​
    
    public interface UserService {
    ​
        User queryUserByName(String name);
    }
    ​
    @Service
    public class UserServiceImpl implements UserService{
    ​
        @Autowired
        UserMapper userMapper;
    ​
        @Override
        public User queryUserByName(String name) {
            return userMapper.queryUserByName(name);
        }
    }
    
  4. 编写UserMapper.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.ywb.mapper.UserMapper">
        <select id="queryUserByName" resultType="User" parameterType="String">
            select * from user where name = #{name}
        </select>
    </mapper>
    
  5. 编写Controller

    @RequestMapping("/login")
    public String login(String username,String password,Model model){
        //获取当前的用户
        Subject subject = SecurityUtils.getSubject();
        //封装用户的登录数据
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        //执行登录的方法,如果没有异常就成功了
        try {
            subject.login(token);
            return "index";
        }catch (UnknownAccountException e){//用户名不存在
            model.addAttribute("msg","用户名不存在!");
            return "login";
        }catch (IncorrectCredentialsException e){//密码不存在
            model.addAttribute("msg","密码错误!");
            return "login";
        }
    }
    
  6. UserRealm

    /**
         * 认证
         * @param authenticationToken
         * @return
         * @throws AuthenticationException
         */
        @Override
        protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
            System.out.println("执行了认证=>doGetAuthenticationInfo");
            UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
            //连接真实数据库
            User user = userService.queryUserByName(token.getUsername());
    ​
            //检查用户名
            if (user==null){
                //自动抛出 UnknownAccountException异常
                return null;
            }
            //检查密码的工作交给shiro做
            return new SimpleAuthenticationInfo("",user.getPwd(),"");
        }
    

shiro请求授权实现

  1. 在ShiroConfig类中配置

    filterMap.put("/user/add","perms[user:add]");

    注意:授权语句要写在拦截语句前

    @Configuration
    public class ShiroConfig {
    ​
        /**
         * shiroFilterFactoryBean,第三步
         * @param securityManager
         * @return
         */
        @Bean
        ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("securityManager") DefaultWebSecurityManager securityManager){
            ShiroFilterFactoryBean factoryBean = new ShiroFilterFactoryBean();
            //设置安全管理器
            factoryBean.setSecurityManager(securityManager);
            //添加shiro的内置过滤器
            /*
                anon:无需认证就可以访问
                authc:必须认证了才能访问
                user:必须拥有“记住我”功能才能使用
                perms:拥有对某个资源的权限才能访问
                role:拥有某个角色权限才能访问
             */
            Map<String, String> filterMap = new LinkedHashMap<>();
    ​
            //授权,正常情况下,未授权的时候会跳转到未授权页面
            filterMap.put("/user/add","perms[user:add]");
            filterMap.put("/user/update","perms[user:update]");
            
            //拦截
            filterMap.put("/user/*","authc");
    ​
            factoryBean.setFilterChainDefinitionMap(filterMap);
    ​
            //设置登录的请求
            factoryBean.setLoginUrl("/toLogin");
            //设置未授权的页面
            factoryBean.setUnauthorizedUrl("/noauth");
            return factoryBean;
        }
    ​
        /**
         * DefaultWebSecurityManager,第二步
         * @param userRealm
         * @return
         */
        @Bean(name = "securityManager")
        DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm){
            DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
            //关联UserRealm
            securityManager.setRealm(userRealm);
            return securityManager;
        }
    ​
        /**
         * 创建realm对象,需要自定义,第一步
         * @return
         */
        @Bean
        public UserRealm userRealm(){
            return new UserRealm();
        }
    }
    ​
    
  2. 在UserRealm对用户进行权限授权

    /**
     * @author log
     * 自定义的UserRealm
     */
    public class UserRealm extends AuthorizingRealm {
    ​
        @Autowired
        UserServiceImpl userService;
    ​
        /**
         * 授权
         * @param principalCollection
         * @return
         */
        @Override
        protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
            System.out.println("执行了授权=>doGetAuthorizationInfo");
            //对用户进行授权
            SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
            Subject subject = SecurityUtils.getSubject();
            User currentUser = (User) subject.getPrincipal();
            info.addStringPermission(currentUser.getPerms());
            return info;
        }
    ​
        /**
         * 认证
         * @param authenticationToken
         * @return
         * @throws AuthenticationException
         */
        @Override
        protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
            System.out.println("执行了认证=>doGetAuthenticationInfo");
            UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
            //连接真实数据库
            User user = userService.queryUserByName(token.getUsername());
    ​
            //检查用户名
            if (user==null){
                //自动抛出 UnknownAccountException异常
                return null;
            }
            //检查密码的工作交给shiro做
            return new SimpleAuthenticationInfo(user,user.getPwd(),"");
        }
    }
    ​
    
  3. 编写未授权的页面提示

    @RequestMapping("/noauth")
    @ResponseBody
    public String unauthorized(){
        return "未授权无法访问此页面";
    }
    

shiro整合Thymeleaf

  1. 导入依赖

    <!--shiro-thymeleaf整合包-->
    <!-- https://mvnrepository.com/artifact/com.github.theborakompanioni/thymeleaf-extras-shiro -->
    <dependency>
        <groupId>com.github.theborakompanioni</groupId>
        <artifactId>thymeleaf-extras-shiro</artifactId>
        <version>2.0.0</version>
    </dependency>
    
  2. 在ShiroConfig中配置ShiroDialect

    @Configuration
    public class ShiroConfig {
        /**
         * 获取ShiroDialect,用来整合Shiro和Thymeleaf
         * @return
         */
        @Bean
        public ShiroDialect getShiroDialect(){
            return new ShiroDialect();
        }
    }
    
  3. 在UserRealm中对用户进行授权

    并且在认证中对user对象进行返回

    return new SimpleAuthenticationInfo(user,user.getPwd(),"");

    在session存入登录信息,用于判定是否已经登录

    /**
     * @author log
     * 自定义的UserRealm
     */
    public class UserRealm extends AuthorizingRealm {
    ​
        @Autowired
        UserServiceImpl userService;
    ​
        /**
         * 授权
         * @param principalCollection
         * @return
         */
        @Override
        protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
            System.out.println("执行了授权=>doGetAuthorizationInfo");
            //对用户进行授权
            SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
            Subject subject = SecurityUtils.getSubject();
            User currentUser = (User) subject.getPrincipal();
            info.addStringPermission(currentUser.getPerms());
            return info;
        }
    ​
        /**
         * 认证
         * @param authenticationToken
         * @return
         * @throws AuthenticationException
         */
        @Override
        protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
            System.out.println("执行了认证=>doGetAuthenticationInfo");
            UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
            //连接真实数据库
            User user = userService.queryUserByName(token.getUsername());
    ​
            //检查用户名
            if (user==null){
                //自动抛出 UnknownAccountException异常
                return null;
            }
            //存入登录信息,用于判断是否已经登录
            Subject currentSubject = SecurityUtils.getSubject();
            Session session = currentSubject.getSession();
            session.setAttribute("loginUser",user);
            //检查密码的工作交给shiro做
            return new SimpleAuthenticationInfo(user,user.getPwd(),"");
        }
    }
    
  4. 使用thymeleaf对html页面进行改造,并导入xmlns

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

    <!DOCTYPE html>
    <html lang="en" xmlns:th="http://www.thymeleaf.org"
    xmlns:shiro="http://www.thymeleaf.org/thymeleaf-extras-shiro">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body><h1>首页</h1>
    <p th:text="${msg}"></p>
    <hr><div th:if="${session.loginUser==null}">
        <a th:href="@{/toLogin}">登录</a>
    </div><div shiro:hasPermission="user:add">
        <a th:href="@{/user/add}">add</a>
        <hr>
    </div><div shiro:hasPermission="user:update">
        <a th:href="@{/user/update}">update</a>
    </div></body>
    </html>