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(一)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!


原文地址:https://blog.csdn.net/qq_37745470/article/details/84849617
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.chinasem.cn/article/792810

相关文章

Java利用docx4j+Freemarker生成word文档

《Java利用docx4j+Freemarker生成word文档》这篇文章主要为大家详细介绍了Java如何利用docx4j+Freemarker生成word文档,文中的示例代码讲解详细,感兴趣的小伙伴... 目录技术方案maven依赖创建模板文件实现代码技术方案Java 1.8 + docx4j + Fr

SpringBoot首笔交易慢问题排查与优化方案

《SpringBoot首笔交易慢问题排查与优化方案》在我们的微服务项目中,遇到这样的问题:应用启动后,第一笔交易响应耗时高达4、5秒,而后续请求均能在毫秒级完成,这不仅触发监控告警,也极大影响了用户体... 目录问题背景排查步骤1. 日志分析2. 性能工具定位优化方案:提前预热各种资源1. Flowable

基于SpringBoot+Mybatis实现Mysql分表

《基于SpringBoot+Mybatis实现Mysql分表》这篇文章主要为大家详细介绍了基于SpringBoot+Mybatis实现Mysql分表的相关知识,文中的示例代码讲解详细,感兴趣的小伙伴可... 目录基本思路定义注解创建ThreadLocal创建拦截器业务处理基本思路1.根据创建时间字段按年进

Java编译生成多个.class文件的原理和作用

《Java编译生成多个.class文件的原理和作用》作为一名经验丰富的开发者,在Java项目中执行编译后,可能会发现一个.java源文件有时会产生多个.class文件,从技术实现层面详细剖析这一现象... 目录一、内部类机制与.class文件生成成员内部类(常规内部类)局部内部类(方法内部类)匿名内部类二、

SpringBoot实现数据库读写分离的3种方法小结

《SpringBoot实现数据库读写分离的3种方法小结》为了提高系统的读写性能和可用性,读写分离是一种经典的数据库架构模式,在SpringBoot应用中,有多种方式可以实现数据库读写分离,本文将介绍三... 目录一、数据库读写分离概述二、方案一:基于AbstractRoutingDataSource实现动态

Springboot @Autowired和@Resource的区别解析

《Springboot@Autowired和@Resource的区别解析》@Resource是JDK提供的注解,只是Spring在实现上提供了这个注解的功能支持,本文给大家介绍Springboot@... 目录【一】定义【1】@Autowired【2】@Resource【二】区别【1】包含的属性不同【2】@

springboot循环依赖问题案例代码及解决办法

《springboot循环依赖问题案例代码及解决办法》在SpringBoot中,如果两个或多个Bean之间存在循环依赖(即BeanA依赖BeanB,而BeanB又依赖BeanA),会导致Spring的... 目录1. 什么是循环依赖?2. 循环依赖的场景案例3. 解决循环依赖的常见方法方法 1:使用 @La

Java枚举类实现Key-Value映射的多种实现方式

《Java枚举类实现Key-Value映射的多种实现方式》在Java开发中,枚举(Enum)是一种特殊的类,本文将详细介绍Java枚举类实现key-value映射的多种方式,有需要的小伙伴可以根据需要... 目录前言一、基础实现方式1.1 为枚举添加属性和构造方法二、http://www.cppcns.co

Elasticsearch 在 Java 中的使用教程

《Elasticsearch在Java中的使用教程》Elasticsearch是一个分布式搜索和分析引擎,基于ApacheLucene构建,能够实现实时数据的存储、搜索、和分析,它广泛应用于全文... 目录1. Elasticsearch 简介2. 环境准备2.1 安装 Elasticsearch2.2 J

Java中的String.valueOf()和toString()方法区别小结

《Java中的String.valueOf()和toString()方法区别小结》字符串操作是开发者日常编程任务中不可或缺的一部分,转换为字符串是一种常见需求,其中最常见的就是String.value... 目录String.valueOf()方法方法定义方法实现使用示例使用场景toString()方法方法