Shiro安全框架第九篇| Spring整合Shiro(二)

2024-03-10 02:59

本文主要是介绍Shiro安全框架第九篇| Spring整合Shiro(二),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

 

spring整合shiro

做技术的永远别丢了技术,除非你已经考虑好换行了。热情和危机感并存,保持对技术的热情,不断学习新技术,对已掌握的技术要了解的更系统。

项目需要引入的依赖包,因为要连接mysql数据库,所以引入了mysql驱动、数据源以及JDBC。

 1   <dependencies>2        <dependency>3            <groupId>org.springframework</groupId>4            <artifactId>spring-context</artifactId>5            <version>5.0.8.RELEASE</version>6        </dependency>7        <dependency>8            <groupId>org.springframework</groupId>9            <artifactId>spring-webmvc</artifactId>
10            <version>5.0.8.RELEASE</version>
11        </dependency>
12        <dependency>
13            <groupId>org.apache.shiro</groupId>
14            <artifactId>shiro-core</artifactId>
15            <version>1.4.0</version>
16        </dependency>
17        <dependency>
18            <groupId>org.apache.shiro</groupId>
19            <artifactId>shiro-spring</artifactId>
20            <version>1.4.0</version>
21        </dependency>
22        <dependency>
23            <groupId>org.apache.shiro</groupId>
24            <artifactId>shiro-web</artifactId>
25            <version>1.4.0</version>
26        </dependency>
27        <!--mysql数据库驱动-->
28        <dependency>
29            <groupId>mysql</groupId>
30            <artifactId>mysql-connector-java</artifactId>
31        </dependency>
32        <!--数据源-->
33        <dependency>
34            <groupId>com.alibaba</groupId>
35            <artifactId>druid</artifactId>
36            <version>1.1.10</version>
37        </dependency>
38        <!--JDBC-->
39        <dependency>
40            <groupId>org.springframework</groupId>
41            <artifactId>spring-jdbc</artifactId>
42            <version>5.0.8.RELEASE</version>
43        </dependency>
44    </dependencies>

web.xml文件

 1<?xml version="1.0" encoding="UTF-8"?>2<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"3         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"4         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"5         version="4.0">67    <!--配置Shiro过滤器-->8    <filter>9        <filter-name>shiroFilter</filter-name>
10        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
11    </filter>
12    <filter-mapping>
13        <filter-name>shiroFilter</filter-name>
14        <url-pattern>/*</url-pattern>
15    </filter-mapping>
16
17    <!--配置spring文件-->
18    <context-param>
19        <param-name>contextConfigLocation</param-name>
20        <param-value>classpath*:spring/spring.xml</param-value>
21    </context-param>
22
23    <listener>
24        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
25    </listener>
26
27    <listener>
28        <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
29    </listener>
30    <!--配置springmvc-->
31    <servlet>
32        <servlet-name>dispatcherServlet</servlet-name>
33        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
34        <init-param>
35            <param-name>contextConfigLocation</param-name>
36            <param-value>classpath*:spring/springmvc.xml</param-value>
37        </init-param>
38        <load-on-startup>1</load-on-startup>
39    </servlet>
40    <servlet-mapping>
41        <servlet-name>dispatcherServlet</servlet-name>
42        <url-pattern>/</url-pattern>
43    </servlet-mapping>
44    <welcome-file-list>
45        <welcome-file>/login.html</welcome-file>
46    </welcome-file-list>
47</web-app>

springmvc.xml

 1<?xml version="1.0" encoding="UTF-8"?>2<beans xmlns="http://www.springframework.org/schema/beans"3       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"4       xmlns:context="http://www.springframework.org/schema/context"5       xmlns:mvc="http://www.springframework.org/schema/mvc"6       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">7        <!--扫描controller-->8        <context:component-scan base-package="com.jiuyue.controller"/>9        <mvc:annotation-driven/>
10        <!--排除静态文件-->
11        <mvc:resources mapping="/*" location="/"/>
12</beans>

配置数据源,注册JdbcTemplate类Bean
spring-dao.xml

 1<?xml version="1.0" encoding="UTF-8"?>2<beans xmlns="http://www.springframework.org/schema/beans"3       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"4       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">5    <!--配置数据源-->6    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">7        <property name="url" value="jdbc:mysql://localhost:3306/test"/>8        <property name="username" value="root"/>9        <property name="password" value="1111"/>
10    </bean>
11
12    <!--JDBC模板接口,并引入数据源-->
13    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
14        <property name="dataSource" ref="dataSource"/>
15    </bean>
16</beans>

spring.xml
需要将spring-dao导入到spring,需要扫描com.jiuyue包下的组件注册成Bean,比如与数据库交接的UserDaoImpl类上要注解@Component,让spring知道这是一个组件,并通过扫描包将其注册成Bean。

 1<?xml version="1.0" encoding="UTF-8"?>2<beans xmlns="http://www.springframework.org/schema/beans"3       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"4       xmlns:context="http://www.springframework.org/schema/context"5       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">6    <!--将spring-dao配置-->7    <import resource="spring-dao.xml" />8    <!--扫描将组件引入-->9    <context:component-scan base-package="com.jiuyue"/>
10    <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
11        <property name="securityManager" ref="securityManager"></property>
12        <property name="loginUrl" value="login.html"></property>
13        <property name="unauthorizedUrl" value="403.html"></property>
14        <property name="filterChainDefinitions">
15            <value>
16                /login.html=anon
17                /userLogin=anon
18                /*=authc
19            </value>
20        </property>
21    </bean>
22    <!--创建 securityManager 对象-->
23    <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
24        <property name="realm" ref="realm"></property>
25    </bean>
26
27    <bean id="realm" class="com.jiuyue.shiro.realm.CustomRealm">
28        <property name="credentialsMatcher" ref="credentialsMatcher"></property>
29    </bean>
30
31    <bean id="credentialsMatcher" class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
32        <property name="hashAlgorithmName" value="md5"></property>
33        <property name="hashIterations" value="1"></property>
34    </bean>
35</beans>

自定义的realm
与数据库的用户信息进行认证。

 1public class CustomRealm extends AuthorizingRealm {2    @Resource3    private UserDao userDao;45//    Map<String,String> userMap = new HashMap<>();6//    {7//         String password="12345";8//         Md5Hash md5Hash = new Md5Hash(password);9//         userMap.put("jiuyue",md5Hash.toString());
10//         super.setName("customReal");
11//    }
12    @Override
13    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
14        return null;
15    }
16
17    @Override
18    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
19        //1、从主体中获取认证信息的用户名
20        String userName = (String) token.getPrincipal();
21        //2、通过用户名获得密码
22        String password = getPasswordByUsername(userName);
23        if (password == null){
24            return null;
25        }else {
26            //查询到用户,则返回AuthenticationInfo对象
27            SimpleAuthenticationInfo simpleAuthenticationInfo =
28                    new SimpleAuthenticationInfo(userName,password,"customReal");
29            return simpleAuthenticationInfo;
30        }
31    }
32
33    /**
34     * 通过username从集合中(数据库中返回password)
35     * @param username
36     * @return
37     */
38    private String getPasswordByUsername(String username) {
39        //return userMap.get(username);
40        User user = userDao.getUserByUserName(username);
41        if (user != null) {
42            return user.getPassword();
43        }
44        return null;
45    }
46}

controller控制器

 1@Controller2public class UserController {3    @RequestMapping(value = "userLogin",method = RequestMethod.POST,4    produces = "application/json;charset=utf-8")5    @ResponseBody6    public String login(User user){7         String password="12345";8         Md5Hash md5Hash = new Md5Hash(password);9        System.out.println("md5:"+md5Hash.toString());
10        //主体
11        Subject subject = SecurityUtils.getSubject();
12        //主体提交请求
13        UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(),user.getPassword());
14        try {
15            subject.login(token);
16        }catch (AuthenticationException e){
17            return e.getMessage();
18        }
19        return "登录成功";
20    }
21}

 

                 “扫码关注“

这篇关于Shiro安全框架第九篇| Spring整合Shiro(二)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/792811

相关文章

Spring Boot集成/输出/日志级别控制/持久化开发实践

《SpringBoot集成/输出/日志级别控制/持久化开发实践》SpringBoot默认集成Logback,支持灵活日志级别配置(INFO/DEBUG等),输出包含时间戳、级别、类名等信息,并可通过... 目录一、日志概述1.1、Spring Boot日志简介1.2、日志框架与默认配置1.3、日志的核心作用

破茧 JDBC:MyBatis 在 Spring Boot 中的轻量实践指南

《破茧JDBC:MyBatis在SpringBoot中的轻量实践指南》MyBatis是持久层框架,简化JDBC开发,通过接口+XML/注解实现数据访问,动态代理生成实现类,支持增删改查及参数... 目录一、什么是 MyBATis二、 MyBatis 入门2.1、创建项目2.2、配置数据库连接字符串2.3、入

Springboot项目启动失败提示找不到dao类的解决

《Springboot项目启动失败提示找不到dao类的解决》SpringBoot启动失败,因ProductServiceImpl未正确注入ProductDao,原因:Dao未注册为Bean,解决:在启... 目录错误描述原因解决方法总结***************************APPLICA编

深度解析Spring Security 中的 SecurityFilterChain核心功能

《深度解析SpringSecurity中的SecurityFilterChain核心功能》SecurityFilterChain通过组件化配置、类型安全路径匹配、多链协同三大特性,重构了Spri... 目录Spring Security 中的SecurityFilterChain深度解析一、Security

SpringBoot多环境配置数据读取方式

《SpringBoot多环境配置数据读取方式》SpringBoot通过环境隔离机制,支持properties/yaml/yml多格式配置,结合@Value、Environment和@Configura... 目录一、多环境配置的核心思路二、3种配置文件格式详解2.1 properties格式(传统格式)1.

Apache Ignite 与 Spring Boot 集成详细指南

《ApacheIgnite与SpringBoot集成详细指南》ApacheIgnite官方指南详解如何通过SpringBootStarter扩展实现自动配置,支持厚/轻客户端模式,简化Ign... 目录 一、背景:为什么需要这个集成? 二、两种集成方式(对应两种客户端模型) 三、方式一:自动配置 Thick

Spring WebClient从入门到精通

《SpringWebClient从入门到精通》本文详解SpringWebClient非阻塞响应式特性及优势,涵盖核心API、实战应用与性能优化,对比RestTemplate,为微服务通信提供高效解决... 目录一、WebClient 概述1.1 为什么选择 WebClient?1.2 WebClient 与

Java.lang.InterruptedException被中止异常的原因及解决方案

《Java.lang.InterruptedException被中止异常的原因及解决方案》Java.lang.InterruptedException是线程被中断时抛出的异常,用于协作停止执行,常见于... 目录报错问题报错原因解决方法Java.lang.InterruptedException 是 Jav

深入浅出SpringBoot WebSocket构建实时应用全面指南

《深入浅出SpringBootWebSocket构建实时应用全面指南》WebSocket是一种在单个TCP连接上进行全双工通信的协议,这篇文章主要为大家详细介绍了SpringBoot如何集成WebS... 目录前言为什么需要 WebSocketWebSocket 是什么Spring Boot 如何简化 We

java中pdf模版填充表单踩坑实战记录(itextPdf、openPdf、pdfbox)

《java中pdf模版填充表单踩坑实战记录(itextPdf、openPdf、pdfbox)》:本文主要介绍java中pdf模版填充表单踩坑的相关资料,OpenPDF、iText、PDFBox是三... 目录准备Pdf模版方法1:itextpdf7填充表单(1)加入依赖(2)代码(3)遇到的问题方法2:pd