Shiro框架基本使用

一、创建maven项目,引入依赖

  <dependencies>
        <dependency>
            <groupId>org.apache.directory.studio</groupId>
            <artifactId>org.apache.commons.codec</artifactId>
            <version>1.8</version>
        </dependency>
        <!-- 自动依赖导入 shiro-core 和 shiro-web -->
        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-spring-boot-starter</artifactId>
            <version>1.5.3</version>
        </dependency>
        <!-- configure logging -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>jcl-over-slf4j</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>com.auth0</groupId>
            <artifactId>java-jwt</artifactId>
            <version>3.11.0</version>
        </dependency>
        <dependency>
            <groupId>io.jsonwebtoken</groupId>
            <artifactId>jjwt</artifactId>
            <version>0.9.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
        <!--配置mybatis依赖-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.2</version>
        </dependency>
        <!--缺少此jar包,导致@Mapper注解无效-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <!--版本1.2.0否则无效-->
            <version>2.1.1</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
            <version>5.1.46</version>
        </dependency>
    </dependencies>

<!--还需要加点东西,便于springBoot识别后续用到的mapper文件和html资源-->
    <build>
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.*</include>
                </includes>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.*</include>
                </includes>
            </resource>
        </resources>

        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

        这些依赖包括MySQL、mybatis和logf4j依赖,之后都会用到 

        这是最基础的 application.properties 配置

spring.main.allow-bean-definition-overriding= true
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/syslog?characterEncoding=utf8&serverTimezone=Asia/Shanghai&useSSL=false
spring.datasource.username=root
spring.datasource.password=root
mybatis.configuration.mapUnderscoreToCamelCase=true

二、前期准备

        shrio登录的时候会用到用户的账号密码做登录判断需要创建数据库和实体映射文件,之所以不用shiro.ini是因为更好的理解shrio框架的使用,而不是为了糊弄。

        1、创建数据库用户表

create table sys_user(id varchar(255),user_name varchar(255),password varchar(255),phone varchar(255),avatar varchar(255));

        2、创建实体类

package com.example.shiro_sys.entity;

import com.example.shiro_sys.util.BaseEntity;
import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
public class UserInfo{
    private String userName;
    private String password;
    private String phone;
}

        3、创建mapper和对应mybatis.xml文件

package com.example.shiro_sys.mapper;

import com.example.shiro_sys.entity.UserInfo;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;

@Mapper
@Repository
public interface UserMapper {
    public void insert ();
    public UserInfo selectUserName (UserInfo userInfo);
}
<?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.example.shiro_sys.mapper.UserMapper">

    <insert id="insert" useGeneratedKeys="true" keyProperty="id">
        insert into sys_user(user_name)
        values (#{username})
    </insert>

    <select id="selectUserName" resultType="com.example.shiro_sys.entity.UserInfo">
        select * from sys_user where user_name=#{userName}
    </select>
</mapper>

        在spring启动类中添加注解扫描mapper.xml文件 

        @MapperScan("com.example.shiro_sys.mapper")

package com.example.shiro_sys;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.mybatis.spring.annotation.MapperScan;

@SpringBootApplication
@MapperScan("com.example.shiro_sys.mapper")
public class ShiroSysApplication {

    public static void main(String[] args) {
        SpringApplication.run(ShiroSysApplication.class, args);
    }

}

三、创建Shiro配置文件

        这是我的文件目录有config配置类,controller控制层,mapper和service层,最后还有些页面静态资源。

         1、创建配置类SpringShiroConfig,此类主要将访问请求拦截和放行请求。

package com.example.shiro_sys.config;

import org.apache.shiro.realm.Realm;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

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


@Configuration
public class SpringShiroConfig {
    //1.创建自定义realm
    @Bean
    public Realm getRealm() {
        CustomRealm customerRealm = new CustomRealm();
        return customerRealm;
    }

    //2.创建shiroFilter  //负责拦截所有请求
    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(DefaultWebSecurityManager defaultWebSecurityManager) {
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        //给filter设置安全管理器
        shiroFilterFactoryBean.setSecurityManager(defaultWebSecurityManager);
        //配置系统受限资源
        //配置系统公共资源
        Map<String, String> map = new HashMap<String, String>();
        map.put("/user/login", "anon");  // anon 设置为公共资源,放行要注意anon和authc的顺序
        map.put("/**", "authc");  //authc 请求这个资源需要认证和授权

        //默认认证界面路径
        shiroFilterFactoryBean.setLoginUrl("/login.html");
        shiroFilterFactoryBean.setFilterChainDefinitionMap(map);
        return shiroFilterFactoryBean;
    }

    //3.创建安全管理器
    @Bean
    public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("getRealm") Realm realm) {
        DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();
        //给安全管理器设置
        defaultWebSecurityManager.setRealm(realm);
        return defaultWebSecurityManager;
    }

}

         2、创建自定义Realm类,此类主要是创建凭证用于登录判断。

package com.example.shiro_sys.config;

import com.example.shiro_sys.entity.UserInfo;
import com.example.shiro_sys.mapper.UserMapper;
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.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class CustomRealm extends AuthorizingRealm {
    @Autowired
    private UserMapper userMapper;

    // 授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        return null;
    }

    // 认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        // 获取当前登录的主体
        String principal = (String) token.getPrincipal();
        UserInfo userInfo = new UserInfo();
        userInfo.setUserName(principal);
        UserInfo user = userMapper.selectUserName(userInfo);

        // 模拟数据库返回的数据
        // 目前用户名为唯一标识
        if (user.getUserName().equals(principal)) {
            //用户名匹配成功后,将数据库查询到的用户密码存入上下文中,在调用subject.login(new UsernamePasswordToken(username,password));
            //时会将存入上下文中的密码作比对,这里用的密码凭证是密码,也可以存放动态验证码
            return new SimpleAuthenticationInfo(principal, user.getPassword(), this.getName());
        }
        return null;

    }

}

四、测试

        1、创建controller和静态访问页面

package com.example.shiro_sys.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("user")
public class UserController {
    /**
     * 用户登录
     * @param username
     * @param password
     * @return
     */
    @RequestMapping("login")
    public String login(String username,String password){
        System.out.println("~~~~~~login~~~~~");
        // 获取当前登录用户
        Subject subject = SecurityUtils.getSubject();

        try {
            // 执行登录操作
            subject.login(new UsernamePasswordToken(username,password));
            // 认证通过后直接跳转到index.jsp
            return "redirect:/index.html";
        } catch (UnknownAccountException e) {
            e.printStackTrace();
            System.out.println("用户名错误");
        } catch (IncorrectCredentialsException e) {
            e.printStackTrace();
            System.out.println("密码错误");
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 如果认证失败仍然回到登录页面
        return "redirect:/login.html";
    }

    @RequestMapping("logout")
    public String logout(){
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        // 退出后仍然会到登录页面
        return "redirect:/login.html";
    }

    public static void main(String[] args) {
        Md5Hash md5Hash03 = new Md5Hash("1234567","1q2w3e",1024);
        System.out.println(md5Hash03.toHex());
    }

}
<!DOCTYPE html>
<html lang="en" xmlns:th="https://www.thymeleaf.org"
      xmlns:shiro="https://www.thymeleaf.org/thymeleaf-extras-shiro">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<p>登录</p>
<form action="/user/login" method="post">
    用户名:<input type="text" name="username" > <br/>
    密码  : <input type="text" name="password"> <br>
    <input type="submit" value="登录">
</form>

</body>
</html>
<!DOCTYPE html>
<html lang="en" xmlns:th="https://www.thymeleaf.org"
      xmlns:shiro="https://www.thymeleaf.org/thymeleaf-extras-shiro">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>
<h1>首页</h1>

<a href="/user/logout">退出用户</a>

</body>
</html>

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/55704.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

【Redis深度专题】「核心技术提升」探究Redis服务启动的过程机制的技术原理和流程分析的指南(集群指令分析—上篇)

探究Redis服务启动的过程机制的技术原理和流程分析的指南&#xff08;Redis集群管理&#xff09; Redis集群管理查看集群中各个节点状态集群(cluster)cluster info的执行效果指令结果分析 cluster nodes的执行效果指令结果分析 节点(node)CLUSTER MEETCLUSTER FORGETCLUSTER RE…

Excel透视表与python实现

目录 一、Excel透视表 1、源数据 2、数据总分析 3、数据top分析 二、python实现 1、第一张表演示 2、第二张表演示 一、Excel透视表 1、源数据 1&#xff09;四个类目&#xff0c;每类50条数据 2&#xff09;数据内容 2、数据总分析 1&#xff09;选择要分析的字段&…

TCP的三次握手以及四次断开

TCP的三次握手和四次断开&#xff0c;就是TCP通信建立连接以及断开的过程 目录 【1】TCP的三次握手过程 ---- TCP建立连接的过程 【2】TCP的四次挥手 ---- TCP会话的断开 注意&#xff1a; 【1】TCP的三次握手过程 ---- TCP建立连接的过程 三次握手的过程&#xff1a…

TPC-DS 标准介绍、工具下载地址

目录 一、TPC-DS标准介绍 1. DMS介绍 2. TCP-DS概念 二、数据库模型 1. 数据库模型介绍 2. 数据库模型包含内容 三、数据生成器 1. 数据生成器介绍 2. 数据生成器包含内容 四、查询集合 1. 查询集合介绍 2. 查询集合包含的88个标准化查询和17个基准统计函数 五、性…

easyui实用点

easyui实用点 1.下拉框&#xff08;input框只能选不能手动输入编辑&#xff09; data-options"editable:false"//不可编辑2.日期框&#xff0c;下拉框&#xff0c;文本框等class class"easyui-datebox"//不带时分秒 class"easyui-datetimebox"…

【C++】C++入门

1.C关键字 2.命名空间 变量、函数和后面学到的类都是大量存在的&#xff0c;这些变量、函数和名称都将存在于全局作用域中&#xff0c;可能会导致一些冲突&#xff0c;比如命名冲突。使用命名空间的目的是对标识符的名称进行本地化&#xff0c;以避免命名冲突和名字污染。 2.1…

Oracle设置某个表字段递增

当Oracle设置字段递增创建触发器 先建一个序列&#xff0c;打开PLSQL 找到Sequences&#xff0c;右击新建 根据自己的需要填写 然后添加触发器&#xff0c;点新建-程序窗口-空白 --TEST_ID为触发器的名字&#xff0c;TEST是添加触发器的表名 CREATE OR REPLACE TRIGGER &qu…

【Ubuntu 18.04 搭建 DHCP 服务】

参考Ubuntu官方文档&#xff1a;https://ubuntu.com/server/docs/how-to-install-and-configure-isc-dhcp-server dhcpd.conf 手册页 配置&#xff1a;https://maas.io/docs/about-dhcp 实验环境规划 Ubuntu 18.04&#xff08;172.16.65.128/24&#xff09;dhcp服务端Ubuntu…

记录--一个好用的轮子 turn.js 实现仿真翻书的效果

这里给大家分享我在网上总结出来的一些知识&#xff0c;希望对大家有所帮助 国际惯例&#xff0c;官网链接 官网传送门 Github地址 github上有几个demos例子&#xff0c;介绍了基础用法。 我参考官网的例子&#xff0c;写了一个demo示例 安装 turn.js 依赖 jquery 库&#xff0…

InnoDB引擎底层逻辑讲解——架构之磁盘架构

1. System Tablespaces区域 系统表空间是change buffer&#xff08;更改缓冲区&#xff09;的存放区域&#xff0c;这是在8.0之后重新规划的&#xff0c;在5.x版本的时候&#xff0c;系统表空间还会存放innodb的数据字典undolog日志等信息&#xff0c;在8.0之后主要主要存放更…

APP开发入门:了解主流的编程语言

在过去的几年里&#xff0c;有许多程序员开始学习和使用编程语言。这其中包括C、C、 Java和 Python。尽管有许多语言可供选择&#xff0c;但大多数程序员都会选择最容易学习的编程语言。 如今&#xff0c;有很多编程语言供选择。程序员们在学习这些语言时可以自由地选择他们喜…

原子操作的重要性

原子操作&#xff1a;要么不做&#xff0c;要么一次性做完 非原子操作 其实ABCD都是对的。 B选项&#xff1a;正常执行&#xff0c;I线程执行2条语句全部执行完毕,再执行II线程重新执行一遍foo函数。 C选项&#xff1a;先执行I线程foo函数第一行代码&#xff0c;然后跳转执行…

蓝牙、GPS定位学习

启动状态&#xff08;APP&#xff09; 冷启动 指在启动应用时&#xff0c;后台没有应用的进程或者进程被杀死的情况下&#xff0c;系统会重新创建一个新的进程&#xff0c;并按照一定的顺序创建和初始化Application类和MainActivity类&#xff0c;最后显示在界面上。这个过程需…

深度学习技巧应用24-深度学习手撕代码与训练流程的联系记忆方法

大家好,我是微学AI,今天给大家介绍一下深度学习技巧应用24-深度学习手撕代码与训练流程的联系记忆方法,大家都知道深度学习模型训练过程是个复杂的过程,这个过程包括数据的收集,数据的处理,模型的搭建,优化器的选择,损失函数的选择,模型训练,模型评估等步骤,其中缺少…

/bin/bash: Resource temporarily unavailable

有现场反馈plsql无法连接数据库了&#xff0c;登录环境查看时发现从root切换到grid时报错/bin/bash: Resource temporarily unavailable [rootdb1 ~]# su - grid Last login: Thu Jul 27 18:45:04 CST 2023 su: failed to execute /bin/bash: Resource temporarily unavailab…

springboot 入门

前提是已安装java环境&#xff0c;分为三部分 一、项目构建 二、项目组成 三、常用注解 Demo源码 spring-demo: springboot 入门项目 一、springboot-stater 使用IDEA快速构建springboot项目 1、新建项目 2、选择maven&#xff0c;在选择next 3、填写好项目信息 4、pom…

学习购药系统源码:从前端到后端的技术探索

本文将带领读者探索购药系统源码&#xff0c;从前端到后端逐步深入&#xff0c;了解其核心功能和实现方式。我们将使用常见的Web技术&#xff0c;包括HTML、CSS、JavaScript、以及Python的Django框架&#xff0c;展示购药系统的技术奥秘。 前端技术探索 HTML结构搭建 购药系…

el-cascader级联选择器加载远程数据、默认开始加载固定条、可以根据搜索加载远程数据。

加载用户列表分页请求、默认请求20条数据。想添加远程搜索用户功能。原有的方法filter-method不能监听到输入清空数据的时候。这样搜索完无法返回默认的20条数据。直接监听级联选择的v-model绑定的值是无法检测到用户自己输入的。 解决思路&#xff1a; el-cascader 没有提供…

mac 下用brew快速安装CommandLineTools

有时候用git 就会提示安装CommandLineTools &#xff0c;xcode太大又不想安装&#xff0c;怎么办呢我们可以试下下面的方式 什么是Brew&#xff1a; Brew是Mac OS X下的一个包管理器&#xff0c;可以方便地安装、升级和卸载很多常用的软件包 在mac下如何安装呢&#xff1a; …

机器学习十大经典算法

机器学习算法是计算机科学和人工智能领域的关键组成部分&#xff0c;它们用于从数据中学习模式并作出预测或做出决策。本文将为大家介绍十大经典机器学习算法&#xff0c;其中包括了线性回归、逻辑回归、支持向量机、朴素贝叶斯、决策树等算法&#xff0c;每种算法都在特定的领…
最新文章