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整合dubbo+zookeeper的详细过程

《Springboot整合dubbo+zookeeper的详细过程》本文讲解SpringBoot整合Dubbo与Zookeeper实现API、Provider、Consumer模式,包含依赖配置、... 目录Spring boot整合dubbo+zookeeper1.创建父工程2.父工程引入依赖3.创建ap

SpringBoot3.X 整合 MinIO 存储原生方案

《SpringBoot3.X整合MinIO存储原生方案》本文详细介绍了SpringBoot3.X整合MinIO的原生方案,从环境搭建到核心功能实现,涵盖了文件上传、下载、删除等常用操作,并补充了... 目录SpringBoot3.X整合MinIO存储原生方案:从环境搭建到实战开发一、前言:为什么选择MinI

SpringBoot结合Docker进行容器化处理指南

《SpringBoot结合Docker进行容器化处理指南》在当今快速发展的软件工程领域,SpringBoot和Docker已经成为现代Java开发者的必备工具,本文将深入讲解如何将一个SpringBo... 目录前言一、为什么选择 Spring Bootjavascript + docker1. 快速部署与

Spring Boot spring-boot-maven-plugin 参数配置详解(最新推荐)

《SpringBootspring-boot-maven-plugin参数配置详解(最新推荐)》文章介绍了SpringBootMaven插件的5个核心目标(repackage、run、start... 目录一 spring-boot-maven-plugin 插件的5个Goals二 应用场景1 重新打包应用

SpringBoot+EasyExcel实现自定义复杂样式导入导出

《SpringBoot+EasyExcel实现自定义复杂样式导入导出》这篇文章主要为大家详细介绍了SpringBoot如何结果EasyExcel实现自定义复杂样式导入导出功能,文中的示例代码讲解详细,... 目录安装处理自定义导出复杂场景1、列不固定,动态列2、动态下拉3、自定义锁定行/列,添加密码4、合并

Spring Boot集成Druid实现数据源管理与监控的详细步骤

《SpringBoot集成Druid实现数据源管理与监控的详细步骤》本文介绍如何在SpringBoot项目中集成Druid数据库连接池,包括环境搭建、Maven依赖配置、SpringBoot配置文件... 目录1. 引言1.1 环境准备1.2 Druid介绍2. 配置Druid连接池3. 查看Druid监控

Java中读取YAML文件配置信息常见问题及解决方法

《Java中读取YAML文件配置信息常见问题及解决方法》:本文主要介绍Java中读取YAML文件配置信息常见问题及解决方法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要... 目录1 使用Spring Boot的@ConfigurationProperties2. 使用@Valu

创建Java keystore文件的完整指南及详细步骤

《创建Javakeystore文件的完整指南及详细步骤》本文详解Java中keystore的创建与配置,涵盖私钥管理、自签名与CA证书生成、SSL/TLS应用,强调安全存储及验证机制,确保通信加密和... 目录1. 秘密键(私钥)的理解与管理私钥的定义与重要性私钥的管理策略私钥的生成与存储2. 证书的创建与

浅析Spring如何控制Bean的加载顺序

《浅析Spring如何控制Bean的加载顺序》在大多数情况下,我们不需要手动控制Bean的加载顺序,因为Spring的IoC容器足够智能,但在某些特殊场景下,这种隐式的依赖关系可能不存在,下面我们就来... 目录核心原则:依赖驱动加载手动控制 Bean 加载顺序的方法方法 1:使用@DependsOn(最直

SpringBoot中如何使用Assert进行断言校验

《SpringBoot中如何使用Assert进行断言校验》Java提供了内置的assert机制,而Spring框架也提供了更强大的Assert工具类来帮助开发者进行参数校验和状态检查,下... 目录前言一、Java 原生assert简介1.1 使用方式1.2 示例代码1.3 优缺点分析二、Spring Fr