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)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • Qt-4.8.7交叉编译平台的搭建、移植详解( aarch32、aarch64 、mips64)「建议收藏」

    Qt-4.8.7交叉编译平台的搭建、移植详解( aarch32、aarch64 、mips64)「建议收藏」由于项目需要,需要在国产系统(银河麒麟系统–飞腾cpu-arm64)上用firefox加载一个npapi插件,而firefox是一个32位的浏览器,而银河麒麟系统不支持编译32位的动态库,因此只能用交叉编译环境来编译arm32的动态库。整了一个星期的Qt移植,今天终于弄出来了。网上的移植教程很多,可没有一篇能够完整编译出自己需要的版本,因此记录一下学习过程以及编译…

    2022年10月9日
    0
  • 基于ADS500MHZ带通滤波器「建议收藏」

    基于ADS500MHZ带通滤波器「建议收藏」《高频电子线路》专题实践报告题目:500Mhz带通滤波器设计500Mhz带通滤波器设计专题相关理论基础及对应ADS仿真要点2.1设计目的2.1.1了解巴特沃斯型滤波器、切比雪夫型滤波器、椭圆函数滤波器各自特性;2.1.2掌握运用ADS软件进行500MHZ带通滤波器优化设计;…

    2022年5月9日
    200
  • mysql语句怎么拼接字符串_MySQL执行拼接字符串语句实例[通俗易懂]

    mysql语句怎么拼接字符串_MySQL执行拼接字符串语句实例[通俗易懂]–以下是一个MySQL执行拼接字符串语句实例:–为需要拼接的变量赋值SET@VARNAME=–以下是一个MySQL执行拼接字符串语句实例:–为需要拼接的变量赋值SET@VARNAME=’李’;–拼接字符串,其中?是执行拼接字符串语句的参数,@TestName是结果值SET@SQLStr0=CONCAT(‘SELECTTestNameINTO@TestNameFRO…

    2022年9月30日
    0
  • java8 常用的流操作 stream collect map filter flatMap max min reduce

    java8 常用的流操作 stream collect map filter flatMap max min reducejava8常用的流操作streamcollectmapfilterflatMapmaxminreduce1 collect(toList())collect(toList())方法由Stream里的值生成一个列表,是一个及早求值操作。//Stream的of方法使用一组初始值生成新的StreamList<String&g…

    2022年5月4日
    37
  • QT之二级菜单

    QT之二级菜单QT之二级菜单QT之二级菜单开场白效果图上代码可参考文章下代码结尾开场白今天我们一起来了解下,在我们QT中,二级菜单是如何实现的,在上篇我们学习了QT之系统托盘,QT之自定义菜单,QT之样式styleSheet。今天我们在这基础上,增加二级菜单的功能。效果图大家注意下这里箭头,不是用的默认效果哦,还是自定义的好看哈!O(∩_∩)下面这张图示是默认的。上代码voi

    2022年5月4日
    143
  • Java 在IDEA社区版中配置Tomcat并使用

    Java 在IDEA社区版中配置Tomcat并使用目录1.下载插件SmartTomcat2.在IDEA中配置Tomcat前言配置之前必须先配置好了Tomcat,这是在已经配置好Tomcat的前提下进行的,如果没有配置Tomcat下面有怎么配置Tomcat和Maven的链接配置Tomcat:https://blog.csdn.net/weixin_44953227/article/details/111575409配置Maven:https://blog.csdn.net/weixin_44953227/ar

    2022年9月22日
    0

发表回复

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

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