1.配置pom.xml文件
这是我自己用的maven依赖
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.3.18.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-dbcp/commons-dbcp -->
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.6</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>4.3.18.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.3.18.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.47</version>
</dependency>
<!-- https://mvnrepository.com/artifact/log4j/log4j -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<!-- https://mvnrepository.com/artifact/jstl/jstl -->
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!--Redis start -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>1.6.1.RELEASE</version>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.7.3</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.5.4</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.5.4</version>
</dependency>
<!--shiro-->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-aspectj</artifactId>
<version>1.3.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.shiro/shiro-cas -->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-cas</artifactId>
<version>1.3.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.shiro/shiro-core -->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>1.3.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.shiro/shiro-ehcache -->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-ehcache</artifactId>
<version>1.3.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.shiro/shiro-guice -->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-guice</artifactId>
<version>1.3.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.shiro/shiro-quartz -->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-quartz</artifactId>
<version>1.3.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.shiro/shiro-spring -->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.3.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.shiro.tools/shiro-tools-hasher -->
<dependency>
<groupId>org.apache.shiro.tools</groupId>
<artifactId>shiro-tools-hasher</artifactId>
<version>1.3.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.shiro/shiro-web -->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-web</artifactId>
<version>1.3.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-log4j12 -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.12</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-api -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.21</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.47</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.47</version>
</dependency>
</dependencies>
2.配置applicationContext-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 id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
<!--配置securityManager-->
<property name="securityManager" ref="securityManager"/>
<!--当访问需要认证的资源时,如果没有认证,那么将自动跳转到登陆Url,如果不配置属性,默认会到根路径login.jsp-->
<property name="loginUrl" value=""/>
<!--认证成功-->
<property name="successUrl" value="/index.do"/>
<!--配置用户没有资源时,跳转的页面-->
<property name="unauthorizedUrl" value="/refuse.do"/>
<!--配置shiro的过滤链-->
<property name="filterChainDefinitions">
<value>
/index.do=authc
/logout=logout
/**=anon
</value>
</property>
</bean>
<!--配置securityManager-->
<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
<!--自定义Realm-->
<property name="realm" ref="userRealm"/>
<!-- 注入缓存管理器 -->
<property name="cacheManager" ref="cacheManager"/>
<!-- 注入session管理器 -->
<property name="sessionManager" ref="sessionManager" />
</bean>
<!--配置自定义userRealm-->
<bean id="userRealm" class="com.crud.realm.UserRealm">
<property name="credentialsMatcher" ref="credentialsMatcher"/>
</bean>
<!-- 缓存管理器 -->
<bean id="cacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager">
<property name="cacheManagerConfigFile" value="classpath:ehcache-shiro.xml"/>
</bean>
<!-- 会话管理器 -->
<bean id="sessionManager" class="org.apache.shiro.web.session.mgt.DefaultWebSessionManager">
<!-- session的失效时长,单位毫秒 -->
<property name="globalSessionTimeout" value="600000"/>
<!-- 删除失效的session -->
<property name="deleteInvalidSessions" value="true"/>
</bean>
<!--rememberMe cookie-->
<bean id="rememberMe" class="org.apache.shiro.web.servlet.SimpleCookie">
<constructor-arg value="rememberMe"/>
<property name="httpOnly" value="true"/>
<!--cookie 的最大失效时间 30天-->
<property name="maxAge" value="259200"/>
</bean>
<!--rememberMe 管理器-->
<bean id="rememberMeManager" class="org.apache.shiro.web.mgt.CookieRememberMeManager">
<property name="cipherKey" value="#{T(org.apache.shiro.codec.Base64).decode('4AvVhmFLUs0KTA3Kprsdag==')}"/>
<property name="cookie" ref="rememberMe"/>
</bean>
<!--配置凭证匹配器-->
<bean id="credentialsMatcher" class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
<property name="hashAlgorithmName" value="md5"/>
<!--该属性为加密次数,需要配合加盐使用,我这里没使用所以就注释了>
<!--<property name="hashIterations" value="2"/>-->
</bean>
</beans>
缓存文件:ehcache-shiro.xml
<?xml version="1.0" encoding="UTF-8"?>
<ehcache updateCheck="false" name="shiroCache">
<diskStore path="C:\shiro\ehcache" />
<!-- <diskStore path="java.io.tmpdir"/> -->
<!--
eternal:缓存中对象是否为永久的,如果是,超时设置将被忽略,对象从不过期。
maxElementsInMemory:缓存中允许创建的最大对象数
overflowToDisk:内存不足时,是否启用磁盘缓存。
timeToIdleSeconds:缓存数据的钝化时间,也就是在一个元素消亡之前, 两次访问时间的最大时间间隔值,这只能在元素不是永久驻留时有效,如果该值是 0 就意味着元素可以停顿无穷长的时间。
timeToLiveSeconds:缓存数据的生存时间,也就是一个元素从构建到消亡的最大时间间隔值,这只能在元素不是永久驻留时有效,如果该值是0就意味着元素可以停顿无穷长的时间。
memoryStoreEvictionPolicy:缓存满了之后的淘汰算法。
diskPersistent:设定在虚拟机重启时是否进行磁盘存储,默认为false
diskExpiryThreadIntervalSeconds: 属性可以设置该线程执行的间隔时间(默认是120秒,不能太小
1 FIFO,先进先出
2 LFU,最少被使用,缓存的元素有一个hit属性,hit值最小的将会被清出缓存。
3 LRU,最近最少使用的,缓存的元素有一个时间戳,当缓存容量满了,而又需要腾出地方来缓存新的元素的时候,那么现有缓存元素中时间戳离当前时间最远的元素将被清出缓存。
-->
<defaultCache
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
overflowToDisk="false"
diskPersistent="false"
diskExpiryThreadIntervalSeconds="120"
/>
<cache name="activeSessionCache"
maxElementsInMemory="10000"
eternal="true"
overflowToDisk="false"
diskPersistent="true"
diskExpiryThreadIntervalSeconds="600"/>
<cache name="shiro.authorizationCache"
maxElementsInMemory="100"
eternal="false"
timeToLiveSeconds="600"
overflowToDisk="false"/>
</ehcache>
3.编写Mapper和Service
eg:
这里用了三个自己写的方法
ShiroMapper
package com.crud.dao;
import com.crud.entity.Permission;
import com.crud.entity.User;
import java.util.List;
public interface ShiroMapper {
//根据用户名获取密码
User findPasswordByName(String username);
//根据用户id获取角色id
List<Integer> getRoleByUserId(int id);
//根据角色id获取权限信息
List<Permission> getPermissionByRoleId(int id);
}
ShiroMapping
<?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.crud.dao.ShiroMapper">
<!--根据用户名获取密码-->
<select id="findPasswordByName" resultType="com.crud.entity.User">
select * FROM user
WHERE username= #{0}
</select>
<!--根据用户id获取角色id-->
<select id="getRoleByUserId" resultType="int">
SELECT r.id
FROM USER u,user_role ur,role r
WHERE u.id=ur.uid AND r.id=ur.rid AND u.id=#{id}
</select>
<!--根据角色id获取权限信息-->
<select id="getPermissionByRoleId" resultType="com.crud.entity.Permission">
SELECT p.*
FROM role r,role_permission rp,permission p
WHERE r.id=rp.rid AND p.pid=rp.pid AND r.id=#{id}
</select>
</mapper>
ShiroService
package com.crud.service;
import com.crud.entity.Permission;
import com.crud.entity.User;
import java.util.List;
public interface ShiroService {
/**
* 根据账号获取账号密码
* @param username
* @return UserPojo
*/
User findPasswordByName(String username);
/**
* 根据账号获取该账号的权限
* @param user
* @return List
*/
List<Permission> getPermissionsByUser(User user);
}
ShiroServiceImpl
package com.crud.service;
import com.crud.dao.ShiroMapper;
import com.crud.entity.Permission;
import com.crud.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
@Service
public class ShiroServiceImpl implements ShiroService {
@Autowired
ShiroMapper shiroMapper;
@Override
//根据账号获取账号密码
public User findPasswordByName(String username) {
return shiroMapper.findPasswordByName(username);
}
@Override
public List<Permission> getPermissionsByUser(User user) {
//通过用户ID获取到用户角色集合
List<Integer> roleId = shiroMapper.getRoleByUserId(user.getId());
System.out.println("角色ID集合为" + roleId);
//声明权限集合
List<Permission> perArrary = new ArrayList<>();
if (roleId != null && roleId.size() != 0) {
//遍历角色ID集合
for (Integer i : roleId) {
//将此roleId集合中的所有元素加入到权限集合中
perArrary.addAll(shiroMapper.getPermissionByRoleId(i));
}
}
System.out.println("perArrary" + perArrary);
return perArrary;
}
}
4.自定义Reaml
这里的Reaml命名为UserReaml,自行修改
package com.crud.realm;
import com.crud.entity.Permission;
import com.crud.entity.User;
import com.crud.service.ShiroService;
import org.apache.shiro.SecurityUtils;
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.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.List;
public class UserRealm extends AuthorizingRealm {
@Autowired
private ShiroService shiroService;
private final org.slf4j.Logger logger = LoggerFactory.getLogger(UserRealm.class);
@Override
public String getName() {
return "userRealm";
}
/**
* 登陆认证方法
* @param authenticationToken
* @return
* @throws AuthenticationException
*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
System.out.println("--------------认证方法执行了--------------");
//方法一:
UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
System.out.println("token中的用户名:"+token.getUsername());
User user = shiroService.findPasswordByName(token.getUsername());
if(user==null){
return null;
}
//最后的比对需要交给安全管理器
//三个参数进行初步的简单认证信息对象的包装
AuthenticationInfo info = new SimpleAuthenticationInfo(user, user.getPassword(), this.getClass().getSimpleName());
return info;
// 方法二:
// 这里是用authenticationToken对象的方法进行认证,需要自己写个用用户名查找用户密码的方法
// String username = authenticationToken.getPrincipal().toString();
// User user = shiroService.findPasswordByName(username);
// System.out.println(user);
// if (user == null) {
// System.out.println("用户不存在");
// throw new AccountException("不存在此用户");
// }
// return new SimpleAuthenticationInfo(user, user.getPassword(), getName());
}
/**
* 用户授权方法
* @param principalCollection
* @return
*/
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
//方法一:获得user对象
System.out.println("--------------授权方法执行了--------------");
User user = (User) principalCollection.getPrimaryPrincipal();
System.out.println("获取到用户:"+user);
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
//获取permission
if (user != null) {
List<Permission> permissionsByUser = shiroService.getPermissionsByUser(user);
System.out.println("获取到用户的权限:"+permissionsByUser);
if (permissionsByUser.size() != 0) {
for (Permission p : permissionsByUser) {
info.addStringPermission(p.getUrl());
}
return info;
}
}
//方法二: 从subject管理器里获取user
// Subject subject = SecurityUtils.getSubject();
// User _user = (User) subject.getPrincipal();
// System.out.println("subject"+_user.getUsername());
return null;
}
/**
* 更新用户授权信息缓存.
*/
public void clearCachedAuthorizationInfo(PrincipalCollection principals) {
System.out.println("-------更新缓存-------");
super.clearCachedAuthorizationInfo(principals);
}
/**
* 更新用户信息缓存.
*/
public void clearCachedAuthenticationInfo(PrincipalCollection principals) {
System.out.println("-------更新用户信息缓存-------");
super.clearCachedAuthenticationInfo(principals);
}
/**
* 清除用户授权信息缓存.
*/
public void clearAllCachedAuthorizationInfo() {
System.out.println("-------清除用户授权信息缓存-------");
getAuthorizationCache().clear();
}
/**
* 清除用户信息缓存.
*/
public void clearAllCachedAuthenticationInfo() {
System.out.println("-------清除用户信息缓存-------");
getAuthenticationCache().clear();
}
/**
* 清空所有缓存
*/
public void clearCache(PrincipalCollection principals) {
System.out.println("------清空所有缓存------");
super.clearCache(principals);
}
/**
* 清空所有认证缓存
*/
public void clearAllCache() {
System.out.println("------清空所有认证缓存------");
clearAllCachedAuthenticationInfo();
clearAllCachedAuthorizationInfo();
}
/**
*
* @Title: clearAuthz
* @Description: TODO()
* @return void 返回类型
* @throws
*/
public void clearAuthz(){
this.clearCachedAuthorizationInfo(SecurityUtils.getSubject().getPrincipals());
}
}
5.配置web.xml
其实就是在SSM的基础上加上shiro的配置
eg:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>ajax_crud</display-name>
<welcome-file-list>
<welcome-file>login.jsp</welcome-file>
</welcome-file-list>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext-*.xml</param-value>
</context-param>
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.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>
<!--配置shiroFilter 通过代理配置,对象由spring容器创建,但是交由servlet管理-->
<filter>
<filter-name>shiroFilter</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
<init-param>
<!--表示bean的生命周期由servlet管理-->
<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>
<!--字符过滤器-->
<filter>
<filter-name>encodingFilter</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>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
测试代码运行
认证:
授权:
这是我自己写的第一个权限管理系统,记录下。