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 中实现 FreeMarker 模板

《如何在SpringBoot中实现FreeMarker模板》FreeMarker是一种功能强大、轻量级的模板引擎,用于在Java应用中生成动态文本输出(如HTML、XML、邮件内容等),本文... 目录什么是 FreeMarker 模板?在 Spring Boot 中实现 FreeMarker 模板1. 环

SpringMVC 通过ajax 前后端数据交互的实现方法

《SpringMVC通过ajax前后端数据交互的实现方法》:本文主要介绍SpringMVC通过ajax前后端数据交互的实现方法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价... 在前端的开发过程中,经常在html页面通过AJAX进行前后端数据的交互,SpringMVC的controll

Java中的工具类命名方法

《Java中的工具类命名方法》:本文主要介绍Java中的工具类究竟如何命名,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧... 目录Java中的工具类究竟如何命名?先来几个例子几种命名方式的比较到底如何命名 ?总结Java中的工具类究竟如何命名?先来几个例子JD

Java Stream流使用案例深入详解

《JavaStream流使用案例深入详解》:本文主要介绍JavaStream流使用案例详解,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧... 目录前言1. Lambda1.1 语法1.2 没参数只有一条语句或者多条语句1.3 一个参数只有一条语句或者多

Spring Security自定义身份认证的实现方法

《SpringSecurity自定义身份认证的实现方法》:本文主要介绍SpringSecurity自定义身份认证的实现方法,下面对SpringSecurity的这三种自定义身份认证进行详细讲解,... 目录1.内存身份认证(1)创建配置类(2)验证内存身份认证2.JDBC身份认证(1)数据准备 (2)配置依

SpringBoot整合OpenFeign的完整指南

《SpringBoot整合OpenFeign的完整指南》OpenFeign是由Netflix开发的一个声明式Web服务客户端,它使得编写HTTP客户端变得更加简单,本文为大家介绍了SpringBoot... 目录什么是OpenFeign环境准备创建 Spring Boot 项目添加依赖启用 OpenFeig

Java Spring 中 @PostConstruct 注解使用原理及常见场景

《JavaSpring中@PostConstruct注解使用原理及常见场景》在JavaSpring中,@PostConstruct注解是一个非常实用的功能,它允许开发者在Spring容器完全初... 目录一、@PostConstruct 注解概述二、@PostConstruct 注解的基本使用2.1 基本代

springboot使用Scheduling实现动态增删启停定时任务教程

《springboot使用Scheduling实现动态增删启停定时任务教程》:本文主要介绍springboot使用Scheduling实现动态增删启停定时任务教程,具有很好的参考价值,希望对大家有... 目录1、配置定时任务需要的线程池2、创建ScheduledFuture的包装类3、注册定时任务,增加、删

SpringBoot整合mybatisPlus实现批量插入并获取ID详解

《SpringBoot整合mybatisPlus实现批量插入并获取ID详解》这篇文章主要为大家详细介绍了SpringBoot如何整合mybatisPlus实现批量插入并获取ID,文中的示例代码讲解详细... 目录【1】saveBATch(一万条数据总耗时:2478ms)【2】集合方式foreach(一万条数

IntelliJ IDEA 中配置 Spring MVC 环境的详细步骤及问题解决

《IntelliJIDEA中配置SpringMVC环境的详细步骤及问题解决》:本文主要介绍IntelliJIDEA中配置SpringMVC环境的详细步骤及问题解决,本文分步骤结合实例给大... 目录步骤 1:创建 Maven Web 项目步骤 2:添加 Spring MVC 依赖1、保存后执行2、将新的依赖