Shiro与Spring MVC集成详解
在Java Web开发领域,Shiro和Spring MVC是两个非常流行的框架。Shiro作为一个强大的Java安全框架,专注于身份验证、授权、密码学和会话管理,而Spring MVC则提供了灵活的模型-视图-控制器(MVC)架构,用于构建Web应用程序。将Shiro与Spring MVC集成,可以使得Web应用的安全性管理更加高效和便捷。接下来,我们将详细探讨Shiro与Spring MVC的集成过程,包括环境搭建、配置步骤及示例代码。
一、环境搭建
首先,需要创建一个Maven-based的Web项目,并引入Shiro和Spring MVC的相关依赖。在pom.xml
中添加以下依赖项:
<!-- Shiro核心库 -->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>1.4.0</version>
</dependency>
<!-- Shiro与Spring的集成库 -->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.4.0</version>
</dependency>
<!-- Spring MVC核心库 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.10.RELEASE</version>
</dependency>
<!-- Servlet API -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<scope>provided</scope>
</dependency>
<!-- 日志依赖 -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.30</version>
</dependency>
二、配置web.xml
在web.xml
中配置Shiro的Filter以及Spring的监听器和DispatcherServlet。
<web-app>
<!-- Spring监听器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- Shiro过滤器 -->
<filter>
<filter-name>shiroFilter</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
<init-param>
<param-name>targetFilterLifecycle</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>shiroFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- Spring MVC DispatcherServlet -->
<servlet>
<servlet-name>springMvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springMvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
三、配置Spring和Shiro
1. 配置Spring
在src/main/resources
目录下创建applicationContext.xml
和spring-shiro-web.xml
配置文件。applicationContext.xml
用于全局Spring Bean的配置,而spring-shiro-web.xml
则专门用于Shiro的配置。
applicationContext.xml
<beans ...>
<!-- 引入Shiro配置 -->
<import resource="spring-shiro-web.xml"/>
<!-- 其他Spring Bean配置 -->
</beans>
spring-shiro-web.xml
<beans ...>
<!-- 安全管理器 -->
<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
<property name="realm" ref="userRealm"/>
</bean>
<!-- 自定义Realm -->
<bean id="userRealm" class="com.example.shiro.UserRealm"/>
<!-- Shiro的生命周期处理器 -->
<bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>
<!-- 开启Shiro注解支持 -->
<bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
<property name="securityManager" ref="securityManager"/>
</bean>
<!-- Shiro过滤器链定义 -->
<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
<property name="securityManager" ref="securityManager"/>
<property name="loginUrl" value="/login.jsp"/>
<property name="successUrl" value="/main.jsp"/>
<property name="unauthorizedUrl" value="/unauthorized.jsp"/>
<property name="filterChainDefinitions">
<value>
/login.jsp = anon
/logout = logout
/** = authc
</value>
</property>
</bean>
</beans>
2. 配置Spring MVC
在WEB-INF
目录下创建spring-servlet.xml
,配置Spring MVC的相关Bean和视图解析器。
<beans ...>
<!-- 启用注解驱动的Spring MVC -->
<mvc:annotation-driven/>
<!-- 视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
<!-- 控制器扫描 -->
<context:component-scan base-package="com.example.controller"/>
</beans>
四、实现自定义Realm
自定义Realm是Shiro认证和授权的核心部分。通过继承AuthorizingRealm
并实现其doGetAuthenticationInfo
和doGetAuthorizationInfo
方法,可以实现自定义的认证和授权逻辑。
package com.example.shiro;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
public class UserRealm extends AuthorizingRealm {
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
// 假设token中的用户名是username
String username = (String) token.getPrincipal();
// 这里应该是查询数据库等数据源获取用户信息
// 示例中直接使用用户名作为密码(实际中应使用密码加密比对)
return new SimpleAuthenticationInfo(username, username, getName());
}
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
String username = (String) principals.getPrimaryPrincipal();
// 根据用户名查询用户权限
// 示例中简单分配权限
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
if ("admin".equals(username)) {
info.addRole("admin");
info.addStringPermission("user:view", "user:edit", "menu:view");
} else {
info.addRole("user");
info.addStringPermission("user:view");
}
return info;
}
}
五、创建登录和首页
在WEB-INF/jsp
目录下创建login.jsp
和main.jsp
,用于登录和首页显示。
login.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Login</title>
</head>
<body>
<form action="/login" method="post">
Username: <input type="text" name="username"/><br/>
Password: <input type="password" name="password"/><br/>
<input type="submit" value="Login"/>
</form>
</body>
</html>
main.jsp
<%@ page contentType="text/html;charset