Shiro与SSM整合
在搭建好SSM环境下
1.1导入依赖
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-web</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.3.2</version>
</dependency>
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.0</modelVersion>
<groupId>com.qfedu</groupId>
<artifactId>days58SSM</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
<spring-version>5.1.6.RELEASE</spring-version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring-version}</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.6.8</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.6</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.8</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.10</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.16</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.24</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-web</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.3.2</version>
</dependency>
</dependencies>
<build>
<plugins>
<!-- define the project compile level -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.6.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<!-- 添加tomcat插件 -->
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.2</version>
<configuration>
<path>/</path>
<port>8081</port>
</configuration>
</plugin>
</plugins>
</build>
</project>
1.2在web.xml中配置Shiro的过滤器
<filter>
<filter-name>shiroFilter</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
<!--
将过滤器的生命周期从“出生”到“死亡”完全交给spring来管理
-->
<init-param>
<param-name>targetFilterLifecycle</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-*.xml</param-value>
</context-param>
<filter-mapping>
<filter-name>shiroFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<filter>
<filter-name>shiroFilter</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
<!--
将过滤器的生命周期从“出生”到“死亡”完全交给spring来管理
-->
<init-param>
<param-name>targetFilterLifecycle</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-*.xml</param-value>
</context-param>
<filter-mapping>
<filter-name>shiroFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>mvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-mvc.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>mvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<filter>
<filter-name>characterEncode</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>characterEncode</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
1.3Spring-mvc配置文件中不用引入spring-mybatis.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:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
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">
<context:component-scan base-package="com.controller" />
<context:component-scan base-package="com.service" />
<mvc:annotation-driven />
<mvc:default-servlet-handler />
</beans>
1.4Spring-mybatis.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:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
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/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
<!--context:property-placeholder 用来配置数据库链接在字符串资源-->
<context:property-placeholder location="classpath:db.properties" />
<!--Druid数据源的配置-->
<!--这里的username注意如果使用${username}则会识别为主机名 程序无法正常运行-->
<bean id="ds" class="com.alibaba.druid.pool.DruidDataSource">
<property name="url" value="${url}" />
<property name="driverClassName" value="${driver}" />
<property name="username" value="${user}" />
<property name="password" value="${pass}" />
</bean>
<!--
配置SqlSessionFactoryBean,用来获取SqlSession对象
SqlSession使用SqlSessionFactory来获取,mybatis交给spring管理后,使用SqlSessionFactoryBean来创建对应的对象
而且高度封装后,不再看到SqlSession,都是controller-service-dao的操作。
配置了四个属性:
typeAliasesPackage:指明要扫描的pojo的包,该包下的所有类,都可以使用类名来简写
dataSource:指明了数据源
mapperLocations:ssm整体使用的是mybatis的xml+接口的方式,所以需要对应的xml文件,指定xml文件的匹配规则和路径
configLocation:配置路径,可以用来配置单独的mybatis的配置信息
-->
<bean class="org.mybatis.spring.SqlSessionFactoryBean" id="sf">
<property name="typeAliasesPackage" value="com.pojo" />
<property name="dataSource" ref="ds" />
<property name="mapperLocations" value="classpath:mapper/*Mapper.xml" />
<property name="configLocation" value="classpath:mybatis.xml" />
</bean>
<!--
MapperScannerConfigurer:配置映射扫描,可以扫描dao包下的所有资源
basePackage:设置扫描dao包
sqlSessionFactoryBeanName:指定SqlSessionFactorybean的文件
-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.dao" />
<property name="sqlSessionFactoryBeanName" value="sf" />
</bean>
<!--
DataSourceTransactionManager:数据源事务管理器
设置事务数据源管理器的数据源
-->
<bean class="org.springframework.jdbc.datasource.DataSourceTransactionManager" id="txm">
<property name="dataSource" ref="ds" />
</bean>
<!--
配置事务管理
-->
<tx:advice transaction-manager="txm" id="tx">
<tx:attributes>
<!--
分别以save、delete、update和add开头的方法都将被切面识别
声明式事务的配置,配置事务的规则
-->
<tx:method name="save*" propagation="REQUIRED" isolation="DEFAULT" rollback-for="Exception" />
<tx:method name="delete*" propagation="REQUIRED" isolation="DEFAULT" rollback-for="Exception" />
<tx:method name="update*" propagation="REQUIRED" isolation="DEFAULT" rollback-for="Exception" />
<tx:method name="add*" propagation="REQUIRED" isolation="DEFAULT" rollback-for="Exception" />
</tx:attributes>
</tx:advice>
<!--
定义切面
-->
<aop:config>
<aop:pointcut id="mpt" expression="execution(* com.service.*.*(..))"/>
<aop:advisor advice-ref="tx" pointcut-ref="mpt" />
</aop:config>
</beans>
1.5mybatis.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<settings>
<!--日志-->
<setting name="logImpl" value="LOG4J"/>
</settings>
</configuration>
1.6.spring-shiro.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">
<bean class="org.apache.shiro.spring.web.ShiroFilterFactoryBean" id="shiroFilter">
<property name="securityManager" ref="securityManager" />
<property name="filterChainDefinitions">
<value>
/login.jsp=anon
/success.jsp=authc
</value>
</property>
</bean>
<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
<property name="realm" ref="mr" />
</bean>
<bean id="mr" class="com.shiro.MyRealm" />
<bean class="org.apache.shiro.spring.LifecycleBeanPostProcessor" id="lifecycleBeanPostProcessor" />
</beans>
1.7编码
MyRealm.java
package com.shiro;
import com.pojo.Perms;
import com.pojo.Roles;
import com.pojo.Users;
import com.service.IUserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.List;
public class MyRealm extends AuthorizingRealm {
@Autowired
private IUserService ius;
/**
* 授权方法,含有的参数是身份集合,使用身份集合就可以获取用户账户信息
*
* @param principalCollection
* @return AuthorizationInfo接口对象
* 剩余的事情就交给了shiro的会话管理器来自动完成
*/
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
String username = getAvailablePrincipal(principalCollection).toString();
System.out.println(username + "---------------");
List<Roles> roles = ius.getRolesByUserName(username);
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
for (Roles r : roles) {
info.addRole(r.getRname());
}
List<Perms> perms = ius.getPermsByUserName(username);
for (Perms p : perms) {
info.addStringPermission(p.getPname());
}
return info;
}
/**
* 认证方法,用户在输入了自己的用户名和密码信息之后,点击提交按钮,即通过subject的login(token)方法,
* 将请求传递给当前方法,进行认证的处理
* @param authenticationToken,含有用户名和密码参数的token对象,可以获取到用户名(身份)和密码(凭证)信息
* @return AuthenticationInfo接口对象
* @throws AuthenticationException
*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
String username = token.getUsername();
char[] passchar = token.getPassword(); // 为了保证密码的安全性,java几乎将密码都设置成立字符数组
String password = new String(passchar);
System.out.println(username + "\t" + password);
Users u = ius.login(username, password);
if(u != null){
SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(username, password, getName());
return info;
}
return null;
}
}
实体类同上一篇文章
编写dao层
public interface IUserDao {
List<Users> getAllUsers();
List<Roles> getRolesByUserName(String username);
List<Perms> getPermsByUserName(String username);
Users login(@Param("username") String username, @Param("password") String password);
}
UserMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.dao.IUserDao">
<select id="getAllUsers" resultType="users">
select * from users
</select>
<select id="login" resultType="users">
select * from users where username = #{username} and password = #{password}
</select>
<select id="getRolesByUserName" resultType="roles">
select r.* from users u ,
user_role ur,
roles r
where u.uid = ur.uid and ur.rid = r.rid
and username = #{username}
</select>
<select id="getPermsByUserName" resultType="perms">
select distinct p.* from users u ,
user_role ur,
roles r,
role_perm rp,
perms p
where u.uid = ur.uid and ur.rid = r.rid
and r.rid = rp.rid and rp.pid = p.pid
and username = #{username}
</select>
</mapper>
编写service层
package com.service;
import com.pojo.Perms;
import com.pojo.Roles;
import com.pojo.Users;
import java.util.List;
public interface IUserService {
List<Users> getAllUsers();
List<Roles> getRolesByUserName(String username);
List<Perms> getPermsByUserName(String username);
Users login(String username, String password);
}
实现类
package com.service.impl;
import com.dao.IUserDao;
import com.pojo.Perms;
import com.pojo.Roles;
import com.pojo.Users;
import com.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class UserServiceImpl implements IUserService {
@Autowired
private IUserDao iud;
@Override
public List<Users> getAllUsers() {
return iud.getAllUsers();
}
@Override
public List<Roles> getRolesByUserName(String username) {
return iud.getRolesByUserName(username);
}
@Override
public List<Perms> getPermsByUserName(String username) {
return iud.getPermsByUserName(username);
}
@Override
public Users login(String username, String password) {
return iud.login(username, password);
}
}
编写controller层
package com.qfedu.controller;
import com.qfedu.pojo.Users;
import com.qfedu.service.IUserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@Controller
public class UserController {
@GetMapping("/Users")
@ResponseBody
public List<Users> getAllUsers(){
// return ius.getAllUsers();
return null;
}
@PostMapping("/login")
public String login(String username, String password){
Subject subject = SecurityUtils.getSubject();
UsernamePasswordToken token = new UsernamePasswordToken(username, password);
try {
subject.login(token);
return "success.jsp";
} catch (AuthenticationException e) {
e.printStackTrace();
}
return "login.jsp";
}
}
前端页面
login.jsp
<%--
Created by IntelliJ IDEA.
User: mac
Date: 2022/9/29
Time: 9:47
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>login</title>
</head>
<body>
<form method="post" action="/login">
username:<input type="text" name="username" /><p />
password:<input type="text" name="password" /><p />
<input type="submit" value="submit" /><p />
</form>
</body>
</html>
success.jsp
<%--
Created by IntelliJ IDEA.
User: mac
Date: 2022/9/30
Time: 10:45
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>success</title>
</head>
<body>
<h1>this is success page.</h1>
</body>
</html>
Shiro与SpringBoot整合
搭建SpringBoot环境.
2.1在pom.xml中添加Shiro依赖
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring-boot-web-starter</artifactId>
<version>1.4.0</version>
</dependency>
2.2新建config.ShiroConfig类
package com.config;
import com.shiro.MyRealm;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.HashMap;
import java.util.Map;
@Configuration
public class ShiroConfig {
@Bean
public ShiroFilterFactoryBean shiroFilterFactoryBean(
@Qualifier("defaultWebSecurityManager")DefaultWebSecurityManager defaultWebSecurityManager){
ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
shiroFilterFactoryBean.setSecurityManager(defaultWebSecurityManager);
Map<String, String> map = new HashMap<>();
map.put("/login.jsp", "anon");
map.put("/success.jsp", "authc");
//map.put("/**", "authc");
shiroFilterFactoryBean.setFilterChainDefinitionMap(map);
shiroFilterFactoryBean.setLoginUrl("/login.jsp");
return shiroFilterFactoryBean;
}
@Bean("defaultWebSecurityManager")
public DefaultWebSecurityManager defaultWebSecurityManager(@Qualifier("mr") MyRealm mr){
DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();
defaultWebSecurityManager.setRealm(mr);
return defaultWebSecurityManager;
}
/**
* 通知方式开启Shiro的注解模式
* 需要借助spring的aop扫描shiro的注解类,来进行安全校验
* @return
*/
@Bean
public DefaultAdvisorAutoProxyCreator advisorAutoProxyCreator(){
DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator = new DefaultAdvisorAutoProxyCreator();
//advisorAutoProxyCreator().setProxyTargetClass(true);
defaultAdvisorAutoProxyCreator.setProxyTargetClass(true);
return defaultAdvisorAutoProxyCreator;
}
/**
* 开启AOP的注解支持
* @param defaultWebSecurityManager
* @return
*/
@Bean
public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(DefaultWebSecurityManager defaultWebSecurityManager){
AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
authorizationAttributeSourceAdvisor.setSecurityManager(defaultWebSecurityManager);
return authorizationAttributeSourceAdvisor;
}
}
MyRealm.java
package com.shiro;
import com.pojo.Perms;
import com.pojo.Roles;
import com.pojo.Users;
import com.service.IUserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.List;
@Component("mr")
public class MyRealm extends AuthorizingRealm {
@Autowired
private IUserService ius;
/**
* 授权方法,含有的参数是身份集合,使用身份集合就可以获取用户账户信息
*
* @param principalCollection
* @return AuthorizationInfo接口对象
* 剩余的事情就交给了shiro的会话管理器来自动完成
*/
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
String username = getAvailablePrincipal(principalCollection).toString();
System.out.println(username + "---------------");
List<Roles> roles = ius.getRolesByUserName(username);
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
for (Roles r : roles) {
info.addRole(r.getRname());
}
List<Perms> perms = ius.getPermsByUserName(username);
for (Perms p : perms) {
info.addStringPermission(p.getPname());
}
return info;
}
/**
* 认证方法,用户在输入了自己的用户名和密码信息之后,点击提交按钮,即通过subject的login(token)方法,
* 将请求传递给当前方法,进行认证的处理
* @param authenticationToken,含有用户名和密码参数的token对象,可以获取到用户名(身份)和密码(凭证)信息
* @return AuthenticationInfo接口对象
* @throws AuthenticationException
*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
String username = token.getUsername();
char[] passchar = token.getPassword(); // 为了保证密码的安全性,java几乎将密码都设置成立字符数组
String password = new String(passchar);
System.out.println(username + "\t" + password);
Users u = ius.login(username, password);
if(u != null){
SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(username, password, getName());
return info;
}
return null;
}
}