Shiro安全框架第八篇| Spring整合Shiro(一)

2024-03-10 02:59

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

做技术的永远别丢了技术,除非你已经考虑好换行了。热情和危机感并存,保持对技术的热情,不断学习新技术,对已掌握的技术要了解的更系统。学了shiro,那么下面就开始与其他框架一起整合使用。

Spring整合shiro

项目工程结构:

首先新建一个Maven工程,再建一个Maven模块,需要在pom.xml中引入spring以及shiro个spring和shiro整个的相关JAR包。

 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    </dependencies>

配置web.xml文件,在这里就是配置springmvc控制器和配置shiro过滤器,对主体的请求进行认证,授权。

 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文件。

  • 扫描controller组件,在xml文件配置了<context:component-scan>标签后,spring容器可以自动去扫描base-pack所指定的包或其子包下面的java类文件,如果扫描到有@Component、@Controller、@Service 、@Repository等注解修饰的Java类,则将这些类注册为spring容器中的bean。

  • 在使用Spring MVC来做web前端框架时,需要使用标签<mvc:annotation-driven/>,它是启用MVC注解的钥匙。如果没有使用这个标签,而仅仅是使用<context:component-scan/>标签扫描并注册了相关的注解类到bean中,<mvc:annotation-driven/>则是告诉框架让这些注解生效。

  • <mvc:resources>标签是用来进行配置静态资源访问的。

     

 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>

spring.xml文件,在这里就是配置shiroFilter的Bean,需要securityManager对象配置进去。realm通过查询数据库,当主体提交请求时,我们需要与数据库的用户信息进行相关的认证。

 

"filterChainDefinitions " Shiro连接约束配置,即过滤链的定义

  • /login.html=anon 不需要认证就可以访问

  • /userLogin=anon 不需要认证就可以访问

  • /*=authc 访问需要认证

 

 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 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">56    <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">7        <property name="securityManager" ref="securityManager"></property>8        <property name="loginUrl" value="login.html"></property>9        <property name="unauthorizedUrl" value="403.html"></property>
10        <property name="filterChainDefinitions">
11            <value>
12                /login.html=anon
13                /userLogin=anon
14                /*=authc
15            </value>
16        </property>
17    </bean>
18    <!--创建 securityManager 对象-->
19    <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
20        <property name="realm" ref="realm"></property>
21    </bean>
22
23    <bean id="realm" class="com.jiuyue.shiro.realm.CustomRealm">
24        <property name="credentialsMatcher" ref="credentialsMatcher"></property>
25    </bean>
26
27    <bean id="credentialsMatcher" class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
28        <property name="hashAlgorithmName" value="md5"></property>
29        <property name="hashIterations" value="1"></property>
30    </bean>
31</beans>

自定义的realm

 1package com.jiuyue.shiro.realm;23import org.apache.shiro.authc.AuthenticationException;4import org.apache.shiro.authc.AuthenticationInfo;5import org.apache.shiro.authc.AuthenticationToken;6import org.apache.shiro.authc.SimpleAuthenticationInfo;7import org.apache.shiro.authz.AuthorizationInfo;8import org.apache.shiro.crypto.hash.Md5Hash;9import org.apache.shiro.realm.AuthorizingRealm;
10import org.apache.shiro.subject.PrincipalCollection;
11
12import java.util.HashMap;
13import java.util.Map;
14
15/**
16 * Create bySeptember
17 * 2018/11/28
18 * 18:43
19 */
20public class CustomRealm extends AuthorizingRealm {
21    Map<String,String> userMap = new HashMap<>();
22    {
23         String password="12345";
24         Md5Hash md5Hash = new Md5Hash(password);
25         userMap.put("jiuyue",md5Hash.toString());
26         super.setName("customReal");
27    }
28    @Override
29    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
30        return null;
31    }
32
33    @Override
34    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
35        //1、从主体中获取认证信息的用户名
36        String userName = (String) token.getPrincipal();
37        //2、通过用户名获得密码
38        String password = getPasswordByUsername(userName);
39        if (password == null){
40            return null;
41        }else {
42            //查询到用户,则返回AuthenticationInfo对象
43            SimpleAuthenticationInfo simpleAuthenticationInfo =
44                    new SimpleAuthenticationInfo(userName,password,"customReal");
45            return simpleAuthenticationInfo;
46        }
47    }
48
49    /**
50     * 通过username从集合中(数据库中返回password)
51     * @param username
52     * @return
53     */
54    private String getPasswordByUsername(String username) {
55        return userMap.get(username);
56    }
57}

controller控制器类

 1@Controller2public class UserController {3    @RequestMapping(value = "userLogin",method = RequestMethod.POST)4    @ResponseBody5    public String login(User user){6        System.out.println("here");7        //主体8        Subject subject = SecurityUtils.getSubject();9        //主体提交请求
10        UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(),user.getPassword());
11        try {
12            subject.login(token);
13        }catch (AuthenticationException e){
14            return e.getMessage();
15        }
16        return "登录成功";
17    }
18}

 

                     “扫码关注“

 

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



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

相关文章

Spring Boot 实现 IP 限流的原理、实践与利弊解析

《SpringBoot实现IP限流的原理、实践与利弊解析》在SpringBoot中实现IP限流是一种简单而有效的方式来保障系统的稳定性和可用性,本文给大家介绍SpringBoot实现IP限... 目录一、引言二、IP 限流原理2.1 令牌桶算法2.2 漏桶算法三、使用场景3.1 防止恶意攻击3.2 控制资源

Mac系统下卸载JAVA和JDK的步骤

《Mac系统下卸载JAVA和JDK的步骤》JDK是Java语言的软件开发工具包,它提供了开发和运行Java应用程序所需的工具、库和资源,:本文主要介绍Mac系统下卸载JAVA和JDK的相关资料,需... 目录1. 卸载系统自带的 Java 版本检查当前 Java 版本通过命令卸载系统 Java2. 卸载自定

springboot下载接口限速功能实现

《springboot下载接口限速功能实现》通过Redis统计并发数动态调整每个用户带宽,核心逻辑为每秒读取并发送限定数据量,防止单用户占用过多资源,确保整体下载均衡且高效,本文给大家介绍spring... 目录 一、整体目标 二、涉及的主要类/方法✅ 三、核心流程图解(简化) 四、关键代码详解1️⃣ 设置

Java Spring ApplicationEvent 代码示例解析

《JavaSpringApplicationEvent代码示例解析》本文解析了Spring事件机制,涵盖核心概念(发布-订阅/观察者模式)、代码实现(事件定义、发布、监听)及高级应用(异步处理、... 目录一、Spring 事件机制核心概念1. 事件驱动架构模型2. 核心组件二、代码示例解析1. 事件定义

SpringMVC高效获取JavaBean对象指南

《SpringMVC高效获取JavaBean对象指南》SpringMVC通过数据绑定自动将请求参数映射到JavaBean,支持表单、URL及JSON数据,需用@ModelAttribute、@Requ... 目录Spring MVC 获取 JavaBean 对象指南核心机制:数据绑定实现步骤1. 定义 Ja

javax.net.ssl.SSLHandshakeException:异常原因及解决方案

《javax.net.ssl.SSLHandshakeException:异常原因及解决方案》javax.net.ssl.SSLHandshakeException是一个SSL握手异常,通常在建立SS... 目录报错原因在程序中绕过服务器的安全验证注意点最后多说一句报错原因一般出现这种问题是因为目标服务器

Java实现删除文件中的指定内容

《Java实现删除文件中的指定内容》在日常开发中,经常需要对文本文件进行批量处理,其中,删除文件中指定内容是最常见的需求之一,下面我们就来看看如何使用java实现删除文件中的指定内容吧... 目录1. 项目背景详细介绍2. 项目需求详细介绍2.1 功能需求2.2 非功能需求3. 相关技术详细介绍3.1 Ja

springboot项目中整合高德地图的实践

《springboot项目中整合高德地图的实践》:本文主要介绍springboot项目中整合高德地图的实践,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一:高德开放平台的使用二:创建数据库(我是用的是mysql)三:Springboot所需的依赖(根据你的需求再

spring中的ImportSelector接口示例详解

《spring中的ImportSelector接口示例详解》Spring的ImportSelector接口用于动态选择配置类,实现条件化和模块化配置,关键方法selectImports根据注解信息返回... 目录一、核心作用二、关键方法三、扩展功能四、使用示例五、工作原理六、应用场景七、自定义实现Impor

SpringBoot3应用中集成和使用Spring Retry的实践记录

《SpringBoot3应用中集成和使用SpringRetry的实践记录》SpringRetry为SpringBoot3提供重试机制,支持注解和编程式两种方式,可配置重试策略与监听器,适用于临时性故... 目录1. 简介2. 环境准备3. 使用方式3.1 注解方式 基础使用自定义重试策略失败恢复机制注意事项