Springboot整合shiro_spring boot框架介绍

Springboot整合shiro_spring boot框架介绍Shiro介绍Shiro是一款安全框架,主要的三个类Subject、SecurityManager、RealmSubject:表示当前用户SecurityManager:安全管理器,即所有与安全有关的操作都会与SecurityManager交互;且其管理着所有Subject;可以看出它是Shiro的核心,它负责与Shiro的其他组件进行交互,它相当于SpringMVC中DispatcherServlet的角色Realm:Shiro从Realm获取安全数据(如用户、角色、权限)Shiro

大家好,又见面了,我是你们的朋友全栈君。如果您正在找激活码,请点击查看最新教程,关注关注公众号 “全栈程序员社区” 获取激活教程,可能之前旧版本教程已经失效.最新Idea2022.1教程亲测有效,一键激活。

Jetbrains全系列IDE使用 1年只要46元 售后保障 童叟无欺

目录

Shiro介绍

Springboot整合Shiro

Shiro整合Thymeleaf


Shiro介绍

Shiro是一款安全框架,主要的三个类Subject、SecurityManager、Realm

  • Subject:表示当前用户
  • SecurityManager:安全管理器,即所有与安全有关的操作都会与SecurityManager交互;且其管理着所有Subject;可以看出它是Shiro的核心,它负责与Shiro的其他组件进行交互,它相当于SpringMVC中DispatcherServlet的角色
  • Realm:Shiro从Realm 获取安全数据(如用户、角色、权限)

Shiro框架结构图

Springboot整合shiro_spring boot框架介绍

Springboot整合Shiro

建项目是勾选spring web,导入依赖

<!--        thymeleaf-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
<!--        shiro-->
        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-spring</artifactId>
            <version>1.7.1</version>
        </dependency>
<!--        lombok-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
            <version>1.18.2</version>
        </dependency>
<!--        mysql-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
<!--        druid-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.0.9</version>
        </dependency>
<!--        mybatis-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.1</version>
        </dependency>
<!--        log4j-->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
<!--        thymeleaf、shiro整合包-->
        <dependency>
            <groupId>com.github.theborakompanioni</groupId>
            <artifactId>thymeleaf-extras-shiro</artifactId>
            <version>2.0.0</version>
        </dependency>

编写页面及其控制层

Springboot整合shiro_spring boot框架介绍

 转发的设置,全部编写在MVCConfig中的前端控制器中

@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("index");
        registry.addViewController("/login.html").setViewName("login");
        registry.addViewController("/user/add").setViewName("user/add");
        registry.addViewController("/user/update").setViewName("user/update");
        registry.addViewController("/loginout").setViewName("login");
    }
}

连接数据库

编写application.yml

spring:
  datasource:
    username: ***
    password: ***
    url: jdbc:mysql://localhost:3306/db_2?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
    driver-class-name: com.mysql.cj.jdbc.Driver
    type: com.alibaba.druid.pool.DruidDataSource
   
    initialSize: 5
    minIdle: 5
    maxActive: 20
    maxWait: 60000
    timeBetweenEvictionRunsMillis: 60000
    minEvictableIdleTimeMillis: 300000
    validationQuery: SELECT 1 FROM DUAL
    testWhileIdle: true
    testOnBorrow: false
    testOnReturn: false
    poolPreparedStatements: true
    filters: stat,wall,log4j
    maxPoolPreparedStatementPerConnectionSize: 20
    useGlobalDataSourceStat: true
    connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
mybatis:
  type-aliases-package: com.example.demo.pojo

编写 pojo、dao、service三层,dao层可以直接使Mybatis的注解。

需要的方法就是findByName(String username),通过表单传入的username值进行查询。

编写UserRealm 需要继承AuthorizingRealm

public class UserRealm extends AuthorizingRealm {
    @Autowired
    private IuserService iuserService;
//    授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("===>授权");
        SimpleAuthorizationInfo Info = new SimpleAuthorizationInfo();
        //        获取登录对象
        Subject subject = SecurityUtils.getSubject();
        user principal = (user) subject.getPrincipal();//拿到user
        Info.addStringPermission(principal.getPerms());
        return Info;
    }
//    认证

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("==>认证");
        UsernamePasswordToken authenticationToken1 = (UsernamePasswordToken) authenticationToken;
        user byName = iuserService.findByName(authenticationToken1.getUsername());
        if(byName==null){
            return null;//抛出用户名错误的异常
        }
        //密码认证shiro自己完成  将user对象 传递给上面的方法进行授权
        return new SimpleAuthenticationInfo(byName,byName.getPassword(),"");
    }
}

代码的分析:

认证部分:

将表单提交的数据封装成一个对象,通过username从数据库中查询返回一个对象,进行比对

最后将这个查询的对象传递给授权方法。

授权部分:

获取到用户对象,给用户对象进行相应的授权。(传递的user对象中就有权限设置)

编写ShiroConfig

@Configuration
public class ShiroConfig {
    @Bean   //创建对象
    public UserRealm userRealm(){
        return new UserRealm();
    }
    @Bean   //接管对象  @Bean 默认使用方法名称
    public DefaultWebSecurityManager securityManager(@Qualifier("userRealm") Realm realm){
        DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();
        defaultWebSecurityManager.setRealm(realm);
        return defaultWebSecurityManager;
    }
    @Bean  //交给前端处理
    public ShiroFilterFactoryBean shiroFilterFactoryBean(@Qualifier("securityManager") DefaultWebSecurityManager defaultWebSecurityManager){
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        shiroFilterFactoryBean.setSecurityManager(defaultWebSecurityManager);

        HashMap<String, String> hashMap = new HashMap<>();
//        该路径 必须通过认证 才能进行访问
        hashMap.put("/user/*","authc");
//        进行授权
        hashMap.put("/user/add","perms[add]");
        hashMap.put("/user/update","perms[update]");
//        注销
        hashMap.put("/logout","logout");
        shiroFilterFactoryBean.setFilterChainDefinitionMap(hashMap);
//        设置登录页面的路径
        shiroFilterFactoryBean.setLoginUrl("/login.html");
//        设置授权页面
        shiroFilterFactoryBean.setUnauthorizedUrl("/noLogin");
        return shiroFilterFactoryBean;
    }

//    完成整合
    @Bean
    public ShiroDialect getShiroDialect(){
        return new ShiroDialect();
    }
}

代码分析

在这个配置类中,配置的方法就是ioc注入。

ShiroFilterFactoryBean中可以配置

  • 资源路径对应的权限
  • 登陆页面
  • 权限不足 无法访问的页面路径
  • 注销

补充: 拦截的属性

  • anon: 无需认证就可以访问
  • authc: 必须认证了才能访问
  • user: 必须拥有记住我功能才能用
  • perms: 拥有对某个资源的权限才能访问
  • role: 拥有某个角色权限

编写控制层代码

@Controller
public class logincontroller {
//    执行流程 前端表单-》控制层代码-》config
    @PostMapping("/login")
    public String login(String username, String password, Model model){
//        获取一个用户
        Subject subject = SecurityUtils.getSubject();
//        封装用户登陆数据
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(username, password);
//        执行登录方法,如果失败就会抛出异常
        try{
            subject.login(usernamePasswordToken);
            return "index";
        }catch (UnknownAccountException e){
            model.addAttribute("msg","用户名错误");
            return "login";
        }catch (IncorrectCredentialsException e){
            model.addAttribute("msg","密码错误");
            return "login";
        }
    }
    @GetMapping("/noLogin")
    @ResponseBody
    public String nologin(){return "未经授权 无法访问";}

}

代码分析:

login方法:获取从表单传递的数据,封装从UsernamePasswordToken对象,调用login方法进行登录操作

Shiro整合Thymeleaf

在ShiroConfig需要整合ShiroDialect

//    完成整合
    @Bean
    public ShiroDialect getShiroDialect(){
        return new ShiroDialect();
    }

约束

xmlns:shiro="http://www.pollix.at/thymeleaf/shiro"

使用方法

shiro:notAuthenticated:没有进行登录 显示

shiro:authenticated:已经登陆 显示

shiro:hasPermission=”A”  用户存在A的权限则显示

示例代码:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org"
      xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>首页</h1>
<div shiro:notAuthenticated>
    <a th:href="@{/login.html}">登录</a>
</div>
<div shiro:authenticated>
    <a th:href="@{/logout}">注销</a>
</div>
<div shiro:hasPermission="add">
    <a th:href="@{/user/add}">ADD</a>
</div>
<div shiro:hasPermission="update">
    <a th:href="@{/user/update}">UPDATE</a>
</div>

</body>
</html>

总结

登录的流程:login表单-》loginController-》ShiroConfig-》UserRealm

效果:

点击登录,控制台会显示

Springboot整合shiro_spring boot框架介绍

 进入add/update的页面,也会打印”===>授权”,这个也证明了登录的执行流程

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/197486.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • 什么是java单例模式?[通俗易懂]

    什么是java单例模式?[通俗易懂]关于java单例模式的文章早已是非常多了,本文是对我个人过往学习java,理解及应用java单例模式的一个总结。此文内容涉及java单例模式的基本概念,以及什单例模式的优缺点,希望对大家有所帮助。什么是java单例模式?单例模式是保证类的实例是单例的一种常见设计模式。单例模式的优点:(1)首先肯定是节省内存资源,不管多频繁的通过暴露的方法创建实例,都能保证创建的对象在系统内存中是同一实例对象;(2)灵活性,由于所有实例的创建都由该类控制,所有该类可以灵活的更改实例化过程;(3)实例的

    2022年8月11日
    6
  • linux shell将字符串分割数组

    linux shell将字符串分割数组经常用将字符串分割为数组的需求。在shell中常用的方式为以下两种#!/bin/bashfunctionsplit_1(){x=”a,b,c,d”OLD_IFS=”$IFS”IFS=”,”array=($x)IFS=”$OLD_IFS”foreachin${array[*]}doecho

    2022年4月28日
    67
  • N皇后问题(c语言实现)

    N皇后问题(c语言实现)问题描述 有一个 n n 的棋盘 在这个棋盘中放 n 个皇后 使得这 n 个皇后 任意两个皇后不在同一行 同一列 同一条对角线 例如 当 n 等于 4 时 有两种摆法 输入只有一个整数 n 思路如果我们是从这个 n n 这个棋盘中选取 n 个方格放皇后 再去判断是否满足条件的话 则效率会非常低 这是一个组合数 complement nn nn atopn nn nn 当 n 等于 8 时 就要枚举次

    2025年9月1日
    2
  • vip导致的serverConnection closed by foreign host问题

    vip导致的serverConnection closed by foreign host问题问题描述:应应用需求,设计搭建了一套带tokudb存储引擎的percona数据库,使用的是常见的双主架构。具体的架构如下图所示:在172.20.32.x1上进行验证的时候出现了下面的问题:FHo

    2022年7月2日
    30
  • 什么是NP问题,什么是NP hard问题,什么是NP完全问题

    什么是NP问题,什么是NP hard问题,什么是NP完全问题先来看一个小故事:(转自:http://zhm2k.blog.163.com/blog/static/5981506820095233143571/)假如老板要你解决一个问题,你绞尽脑汁还是想不出来,叫天天不应,叫地地不灵,这时你走进老板办公室,可以采取3种策略:1)一副倒霉像,神情猥琐,可怜巴巴的说:老板,我没做出来,我想我是太蠢了……boss:蠢材!滚!(失败……)2)

    2025年6月15日
    3
  • 如何防止135端口入侵「建议收藏」

    如何防止135端口入侵「建议收藏」
    新学期到了,许多学生都要配机,新电脑的安全防卫做好了吗?能不能拒绝成为黑客的肉鸡?令人遗憾的是,很多新手都不知道或者忽视了对敏感端口的屏蔽。例如135端口,一旦黑客利用135端口进入你的电脑,就能成功地控制你的机子。我们应该如何防范通过135端口入侵呢?下面我们就为大家来揭开谜底。

      小知识:每台互联网中的计算机系统,都会同时打开多个网络端口,端口就像出入房间的门一样。因为房间的门用于方便人们的进出,而端口则为不同的网路服务提供数据交换。正如房间的门可以放进小tou一样

    2025年7月8日
    3

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号