shiro框架


title: shiro框架
date: 2021/3/5

1. Shiro简介

1.1 什么是Shiro?

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

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

img

img

1.2 从外部看shiro

img

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

Shiro SecurityManager(管理所有用户):安全管理器;即所有与安全有关的操作都会与SecurityManager交互且它管理所有Subject;可以看出它是Shiro的核心,它负责与后面介绍的其它组件进行交互,可以把它看成DispathcherServlet前端控制器

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

1.3 内部结构图

img

img

1.4 常见单词说明

img

2. shiro.ini

img

2.1 main

提供了对根对象securityManager及其依赖对象的配置

#创建对象
securityManager=org.apache.shiro.mgt.DefaultSecurityManager 

其构造器必须是public空参构造器,通过反射创建相应的实例。
1.对象名=全限定类名 相当于调用public无参构造器创建对象
2.对象名.属性名=值 相当于调用于setter方法设置常量值
3.对象名.属性名=$对象引用 相当于调用setter方法设置对象引用

2.2 users

提供了对用户/密码及其角色的配置,用户名=密码,角色1,角色2
username=password,role1,role2
  例如:配置用户名/密码及其角色,格式:“用户名=密码,角色1,角色2”,角色部分可省略。如:

[users] 
zhang=123,role1,role2 
wang=123 

2.3 roles

提供了角色及权限之间关系的配置,角色=权限1,权限2 role1 = permission1 , permission2
  例如:配置角色及权限之间的关系,格式:“角色=权限1,权限2”;如:

[roles] 
role1=user:create,user:update 
role2=*  

2.4 urls

用于web,提供了对web url拦截相关的配置,url=拦截器[参数],拦截器

/index.html = anon 
/admin/** = authc, roles[admin],perms["permission1"]

3. 使用

3.1 依赖

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

3.2 Subject

//获得当前的用户对象Subject
Subject currentUser = SecurityUtils.getSubject();
//拿到Session
Session session = currentUser.getSession();
//判断当前用户是否被认证
currentUser.isAuthenticated()
//获取当用户的认证
currentUser.getPrincipal()
//获取当前用户拥有什么角色
currentUser.hasRole("schwartz")
//获取当前用户的一些权限
currentUser.isPermitted("lightsaber:wield")
//注销
 currentUser.logout();
public class Quickstart {

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


    public static void main(String[] args) {
        
        DefaultSecurityManager securityManager = new DefaultSecurityManager();
        IniRealm iniRealm = new IniRealm("classpath:shiro.ini");
        securityManager.setRealm(iniRealm);

        SecurityUtils.setSecurityManager(securityManager);

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

        //获取当前的用户对象
        // get the currently executing user:
        Subject currentUser = SecurityUtils.getSubject();
        //通过当前用户拿到Session,并且用Session进行存值和取值
        // Do some stuff with a Session (no need for a web or EJB container!!!)
        Session session = currentUser.getSession();
        session.setAttribute("someKey", "aValue");
        String value = (String) session.getAttribute("someKey");
        if (value.equals("aValue")) {
            log.info("Subject=>session [" + value + "]");
        }

        //判断当前的用户是否被认证,通过账户和密码生产token令牌
        // 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);
    }
}

3.Shiro整合Spring boot

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

步骤1

创建realm对象,需要自定义类UserRealm,UserRealm类继承AuthorizingRealm类,并重写doGetAuthorizationInfo和doGetAuthenticationInfo两个方法,两个方法分别实现授权和认证功能

public class UserRealm extends AuthorizingRealm {

    @Autowired
    UserService userService;

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行了=>授权doGetAuthorizationInfo");

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.addStringPermission("user:add");


        return info;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("执行了=>认证doGetAuthenticationInfo");

//        //用户名认证
//        String name = "root";
//        String password = "745619";


        UsernamePasswordToken userToken = (UsernamePasswordToken) authenticationToken;

        //1.连接真实数据库
        User user = userService.queryUserByName(userToken.getUsername());

        //2.判断用户名
        if(user==null){  //没这个人
            return null;
        }

        //3.判断密码
        //参数1:获取当前用户的认证,传递的密码的对象,认证名
        return new SimpleAuthenticationInfo("",user.getPwd(),"");
    }
}

步骤2

编写ShiroConfig配置类

1.getShiroFilterFactoryBean(登录拦截操作)
2.getDefaultWebSecurityManager(绑定realm)
3.创建realm对象(用户认证)
@Configuration
public class ShiroConfig {


    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("securityManager") DefaultWebSecurityManager defaultWebSecurityManager){
        ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
        //设置安全管理器
        bean.setSecurityManager(defaultWebSecurityManager);
        //添加shiro的内置过滤器
        /*
             amon:无需认证就可以访问
             authc:必须认证了才能访问
             user:必须拥有“记住我”才能认证
             perms:拥有对某个资源的权限才能访问
             role:又有某个角色才能访问
         */

        //登录拦截操作
        Map<String, String> filterMap = new LinkedHashMap<>();
        filterMap.put("/user/add", "perms[user:add]");
        filterMap.put("/user/update", "authc");
        bean.setFilterChainDefinitionMap(filterMap);

        //设置登录的请求
        //如果拦截成功则跳转到登录页面
        bean.setLoginUrl("/toLogin");

        //设置未授权页面
        bean.setUnauthorizedUrl("/noauth");
        return bean;
    }

    //DefaultWebSecurityManager
    @Bean(name="securityManager")
    public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm){
        //固定
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        //关联UserRealm
        securityManager.setRealm(userRealm);
        return securityManager;
    }

    //创建realm对象,需要自定义类
    @Bean
    public UserRealm userRealm(){
        UserRealm userRealm = new UserRealm();
        return userRealm;
    }

    @Bean
    //整合 shiro thymeleaf
    public ShiroDialect getShiroDialect(){
        return new ShiroDialect();
    }
}

就此完成了:登录拦截(getShiroFilterFactoryBean类中完成)、登录认证(UserRealm类的doGetAuthenticationInfo方法中完成)

4. Shiro整合Mybatis

4.1 配置数据库文件

spring:
  datasource:
    username: root
    password: 745619
    url: jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
    driver-class-name: com.mysql.jdbc.Driver
    
    type: com.alibaba.druid.pool.DruidDataSource

4.2 实现UserService接口

public interface UserService {
    public User queryUserByName(String name);
}

4.3 实现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.kuang.mapper.UserMapper">
    <select id="queryUserByName" parameterType="String" resultType="User">
       select * from mybatis.user where name = #{name}
    </select>
</mapper>

4.4 实现UserServiceImpl

@Service
public class UserServiceImpl implements UserService{

    @Autowired
    UserMapper userMapper;
    @Override
    public User queryUserByName(String name) {
        return userMapper.queryUserByName(name);
    }
}

4.5 在UserRealm类的认证方法中,连接数据库

       UsernamePasswordToken userToken = (UsernamePasswordToken) authenticationToken;

        //1.连接真实数据库
        User user = userService.queryUserByName(userToken.getUsername());

        //2.判断用户名
        if(user==null){  //没这个人
            return null;
        }

        //3.判断密码
        //参数1:获取当前用户的认证,传递的密码的对象,认证名
        return new SimpleAuthenticationInfo("",user.getPwd(),"");

连接数据库后,就可以对比前端传来的数据和数据库中的数据进行对比

5. Shiro加密操作

在CredentialsMatcher接口中,有如下实现类

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-aWVD5QBA-1631612505251)(C:\Users\ZZR\AppData\Roaming\Typora\typora-user-images\image-20210908213652124.png)]

默认的是SimpleCredentialsMatcher实现类,实现简单密码,Md5CredentialsMatcher加密底层也是继承该类

6. Shiro授权

1.设置perms权限

登录成功之后,添加对该用户对某功能的拦截,perms:当前用户拥有对某个功能的权限才能访问,如果没有权限则进入未被授权页面,

//"perms[user:add]"必须是user用户且必须有add这个权限才能访问
//正常情况下,没有授权会跳到未授权页面
filterMap.put("/user/add", "perms[user:add]");
filterMap.put("/user/update", "authc");
bean.setFilterChainDefinitionMap(filterMap);

//设置登录的请求
//如果拦截成功则跳转到登录页面
bean.setLoginUrl("/toLogin");

//设置未授权页面
bean.setUnauthorizedUrl("/noauth");
return bean;

2.对当前用户执行授权功能

在UserRealm类中的doGetAuthorizationInfo授权方法中,对当前用户user的add功能进行授权,授权后,当前用户使用该功能后不会进入未被授权页面(401),而会直接进入正常页面

//授权
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
    System.out.println("执行了=>授权doGetAuthorizationInfo");

    SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
    info.addStringPermission("user:add");

    return info;
}

3.问题

当一个用户user登录成功后,在客户端使用数据库中其他用户登录也能登录成功,造成不安全性

解决:

1.在数据库中增加权限字段perms

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-gQLa4Cxl-1631612505252)(C:\Users\ZZR\AppData\Roaming\Typora\typora-user-images\image-20210908233336181.png)]

2.在实体类中增加属性perms

3.在在UserRealm类中的doGetAuthorizationInfo授权方法中,对数据库中perms进行判断授权

//授权
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
    System.out.println("执行了=>授权doGetAuthorizationInfo");

    SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
    //info.addStringPermission("user:add");

    //拿到当前登录的这个对象,通过认证中判断密码的第一个参数获取与user的联系
    Subject subject = SecurityUtils.getSubject();
    //拿到user对象
    User currentUser = (User) subject.getPrincipal();
    //设置当前用户的权限
    info.addStringPermission(currentUser.getPerms());

    return info;
}

效果:当登录张三时,能用add功能,不能用update功能

​ 当登录小明时,不能用add功能,不能用update功能

​ 当登录王五时,不能用add功能,能用update功能

SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
//info.addStringPermission("user:add");

//拿到当前登录的这个对象,通过认证中判断密码的第一个参数获取与user的联系
Subject subject = SecurityUtils.getSubject();
//拿到user对象
User currentUser = (User) subject.getPrincipal();
//设置当前用户的权限
info.addStringPermission(currentUser.getPerms());

return info;

}


效果:当登录张三时,能用add功能,不能用update功能

​           当登录小明时,不能用add功能,不能用update功能

​          当登录王五时,不能用add功能,能用update功能

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值