“ Apache Shiro™是一个功能强大且易于使用的Java安全框架,它执行身份验证,授权,加密和会话管理。”
1. 搭建 SpringMVC 的环境
要整合 SpringMVC 就必须先搭建 SpringMVC 的环境, 这不是本文的重点, 帅帅只把配置给大家, 大家自行复制黏贴或者看看就好.
1.1 pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0modelVersion>
<groupId>club.javafamilygroupId>
<artifactId>shiro02artifactId>
<version>1.0-SNAPSHOTversion>
<packaging>warpackaging>
<name>shiro02 Maven Webappname>
<url>http://localhost/shiro/url>
<properties>
<springframework.version>5.2.3.RELEASEspringframework.version>
<project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
<maven.compiler.source>1.8maven.compiler.source>
<maven.compiler.target>1.8maven.compiler.target>
<tomcat7.port>80tomcat7.port>
<tomcat7.path>/shirotomcat7.path>
properties>
<dependencies>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>4.11version>
<scope>testscope>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-beansartifactId>
<version>${springframework.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-contextartifactId>
<version>${springframework.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webartifactId>
<version>${springframework.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webmvcartifactId>
<version>${springframework.version}version>
dependency>
<dependency>
<groupId>org.apache.tomcatgroupId>
<artifactId>jsp-apiartifactId>
<version>6.0.36version>
<scope>providedscope>
dependency>
<dependency>
<groupId>javax.servletgroupId>
<artifactId>javax.servlet-apiartifactId>
<version>3.1.0version>
<scope>providedscope>
dependency>
<dependency>
<groupId>commons-collectionsgroupId>
<artifactId>commons-collectionsartifactId>
<version>3.2.2version>
dependency>
<dependency>
<groupId>commons-codecgroupId>
<artifactId>commons-codecartifactId>
<version>1.10version>
dependency>
<dependency>
<groupId>org.apache.commonsgroupId>
<artifactId>commons-lang3artifactId>
<version>3.5version>
dependency>
dependencies>
<build>
<finalName>shiro02finalName>
<pluginManagement>
<plugins>
<plugin>
<artifactId>maven-clean-pluginartifactId>
<version>3.1.0version>
plugin>
<plugin>
<artifactId>maven-resources-pluginartifactId>
<version>3.0.2version>
plugin>
<plugin>
<artifactId>maven-compiler-pluginartifactId>
<version>3.8.0version>
plugin>
<plugin>
<artifactId>maven-surefire-pluginartifactId>
<version>2.22.1version>
plugin>
<plugin>
<artifactId>maven-war-pluginartifactId>
<version>3.2.2version>
plugin>
<plugin>
<artifactId>maven-install-pluginartifactId>
<version>2.5.2version>
plugin>
<plugin>
<artifactId>maven-deploy-pluginartifactId>
<version>2.8.2version>
plugin>
plugins>
pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.tomcat.mavengroupId>
<artifactId>tomcat7-maven-pluginartifactId>
<version>2.1version>
<configuration>
<port>${tomcat7.port}port>
<path>${tomcat7.path}path>
<uriEncoding>${project.build.sourceEncoding}uriEncoding>
<server>tomcat7server>
configuration>
plugin>
plugins>
build>
project>
1.2 web.xml
br /> "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>Shiro-Spring Demodisplay-name>
<context-param>
<param-name>contextConfigLocationparam-name>
<param-value>classpath:applicationContext.xmlparam-value>
context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
listener>
<servlet>
<servlet-name>dispatcherservlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
<init-param>
<param-name>contextConfigLocationparam-name>
<param-value>classpath:dispatcher-servlet.xmlparam-value>
init-param>
<load-on-startup>1load-on-startup>
servlet>
<servlet-mapping>
<servlet-name>dispatcherservlet-name>
<url-pattern>/url-pattern>
servlet-mapping>
<welcome-file-list>
<welcome-file>index.htmlwelcome-file>
<welcome-file>index.jspwelcome-file>
welcome-file-list>
web-app>
1.3 dispatcher-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:mvc="http://www.springframework.org/schema/mvc"xmlns:context="http://www.springframework.org/schema/context"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="club.javafamily.shiro">context:component-scan>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/">property>
<property name="suffix" value=".jsp">property>
bean>
<mvc:annotation-driven>mvc:annotation-driven>
<mvc:default-servlet-handler>mvc:default-servlet-handler>
beans>
1.4 applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
beans>
1.5 SpringMVC 环境测试
添加一个 controller 用于测试 mvc 环境
package club.javafamily.shiro.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class PingController {
@GetMapping("/ping")
public String ping() {
return "pong";
}
}
然后用浏览器访问 http://localhost/shiro/ping 查看结果
1.6 目录结构
2. 引入 Shiro
2.1 引入 pom 依赖
<dependency>
<groupId>org.apache.shirogroupId>
<artifactId>shiro-coreartifactId>
<version>${shiro.version}version>
dependency>
<dependency>
<groupId>org.apache.shirogroupId>
<artifactId>shiro-springartifactId>
<version>${shiro.version}version>
dependency>
<dependency>
<groupId>org.apache.shirogroupId>
<artifactId>shiro-ehcacheartifactId>
<version>${shiro.version}version>
dependency>
<dependency>
<groupId>org.slf4jgroupId>
<artifactId>jcl-over-slf4jartifactId>
<scope>runtimescope>
<version>${slf4j.version}version>
dependency>
<dependency>
<groupId>org.slf4jgroupId>
<artifactId>slf4j-log4j12artifactId>
<scope>runtimescope>
<version>${slf4j.version}version>
dependency>
<dependency>
<groupId>log4jgroupId>
<artifactId>log4jartifactId>
<scope>runtimescope>
<version>${log4j.version}version>
dependency>
2.2 配置 web.xml
在 Springmvc 环境中使用 Shiro 需要配置一个 Shiro Filter 来拦截请求.
<filter>
<filter-name>shiroFilterfilter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxyfilter-class>
<init-param>
<param-name>targetFilterLifecycleparam-name>
<param-value>trueparam-value>
init-param>
<init-param>
<param-name>targetBeanNameparam-name>
<param-value>shiroFilter2param-value>
init-param>
filter>
<filter-mapping>
<filter-name>shiroFilterfilter-name>
<url-pattern>/*url-pattern>
filter-mapping>
注意 DelegatingFilterProxy 这是一个代理类, 默认情况下, 这将从 Spring IOC 容器中查找 \ 指定的 Filter Name 的 Bean 作为具体的 Filter, 也可以通过 targetBeanName 初始化参数去指定 IOC 中具体 Filter Bean 的名称(这样的设计思想是来源于 Spring Security.)
2.3 配置 Shiro 组件
在
applicationContext.xml
中配置 Shiro 的核心组件
<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
<property name="cacheManager" ref="cacheManager">property>
<property name="realm" ref="shiroRealm">property>
bean>
<bean id="cacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager">
<property name="cacheManagerConfigFile" value="classpath:ehcache.xml">property>
bean>
<bean id="shiroRealm" class="club.javafamily.shiro.realm.ShiroRealm">bean>
<bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor">bean>
<bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator"depends-on="lifecycleBeanPostProcessor">bean>
<bean id="shiroFilter2" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
<property name="securityManager" ref="securityManager">property>
<property name="loginUrl" value="/login.jsp">property>
<property name="successUrl" value="/index.jsp">property>
<property name="unauthorizedUrl" value="/unauthorizedUrl.jsp">property>
<property name="filterChainDefinitions">
<value>
/login.jsp = anon
/ping = anon
/** = authc
value>
property>
bean>
2.3.1 ShiroFilter
上面配置的 Shiro Filter 的 id 必须和 web.xml 文件中配置的 DelegatingFilterProxy 的 targetBeanName 一致, 如果没有指定 targetBeanName 则默认为 \ 指定的 filter 名称. 如果不一致则会抛出以下异常, 因为 web.xml 配置的是 Filter 代理
严重: Exception starting filter shiroFilter
org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'shiroFilter' available
2.3.2 filterChainDefinitions
ShiroFilter
的filterChainDefinitions
指定那些页面需要受保护, 以及访问这些页面那些权限
anon: 代表可以被匿名访问(不配置也代表可以匿名访问, 但是需要注意 /** 是配置所有的请求)
authc: 代表必须认证登录后才能访问
/** 代表所有请求
filterChainDefinitions 采用第一次匹配优先的方式. 并支持通配符匹配
?: 匹配一个任意字符
*: 匹配 0 个或者多个任意字符
**: 匹配多层路径
2.3.3 jsp 页面
index.jsp
默认的项目首页, 也是我们通过Shiro
的successUrl
配置的登录成功跳转的页面.list.jsp
需要授权的页面login.jsp
登录页面unauthorizedUrl.jsp
没有权限跳转的提示页面
2.3.4 ShiroRealm
上面的
ShiroRealm
目前我们只是一个实现了Reaml
接口的空实现, 关于 Reaml 的作用可以参考我们上一篇 Shiro 文章 认证与授权 --- Shiro (一)
package club.javafamily.shiro.realm;
import org.apache.shiro.authc.*;
import org.apache.shiro.realm.Realm;
public class ShiroRealm implements Realm {
@Override
public String getName() {
return null;
}
@Override
public boolean supports(AuthenticationToken token) {
return false;
}
@Override
public AuthenticationInfo getAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
return null;
}
}
2.4 ehcache.xml
因为我们 shiro-cache 使用了 ehcache, 所以需要添加 ehcache 的配置, 不多说, 不懂得.
<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:noNamespaceSchemaLocation="http://www.ehcache.org/ehcache.xsd"updateCheck="true" monitoring="autodetect" dynamicConfig="true">
<defaultCacheeternal="false"maxElementsInMemory="1000"overflowToDisk="false"diskPersistent="false"timeToIdleSeconds="0"timeToLiveSeconds="600"memoryStoreEvictionPolicy="LRU" />
ehcache>
2.5 log4j.properties
log4j.rootLogger=INFO, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m %n
# General Apache libraries
log4j.logger.org.apache=WARN
# Spring
log4j.logger.org.springframework=WARN
# Default Shiro logging
log4j.logger.org.apache.shiro=INFO
# Disable verbose logging
log4j.logger.org.apache.shiro.util.ThreadContext=WARN
log4j.logger.org.apache.shiro.cache.ehcache.EhCache=WARN
2.6 运行测试
因为我们引入了
tomcat7-maven-plugin
所以只需要执行mvn tomcat7:run
来发布运行项目就可以进行测试.
访问
http://localhost/shiro/ping
或者http://localhost/shiro/login.jsp
都可以直接访问
访问
http://localhost/shiro/list.jsp
或者任何不存在的路径将都会自动跳转到登录界面.
具体的登录认证我们下一篇接着聊哦...
每文一骚
————
What's your superpower? Courage.
你的超能力是什么? 勇气.
日常求赞
————
您的三连就是帅帅我深夜撸文的最大的动力, 诚挚的邀请您动动手指头, 转发, 评论, Wow.
关注加好友
拉你进大佬交流群
————————————————