application.properties
spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=
mybatis.mapper-locations=classpath:mapper/*Mapper.xml
spring.mvc.view.prefix=/WEB-INF/pages/
spring.mvc.view.suffix=.jsp
ShiroConfigration
package com.ylm.jspshiro.config;
import com.ylm.jspshiro.util.AuthsMySQLRealm;
import org.apache.shiro.spring.LifecycleBeanPostProcessor;
import org.apache.shiro.spring.config.ShiroConfiguration;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.filter.DelegatingFilterProxy;
import java.util.LinkedHashMap;
import java.util.Map;
@Configuration
public class ShiroConfigration {
@SuppressWarnings("unused")
private static final Logger logger = LoggerFactory.getLogger(ShiroConfiguration.class);
// public EhCacheManager getEhCacheManager() {
// EhCacheManager em = new EhCacheManager();
// em.setCacheManagerConfigFile("classpath:ehcache-shiro.xml");
// return em;
// }
/**
* 注册DelegatingFilterProxy(Shiro)
*/
@Bean
public FilterRegistrationBean filterRegistrationBean() {
FilterRegistrationBean filterRegistration = new FilterRegistrationBean();
filterRegistration.setFilter(new DelegatingFilterProxy("shiroFilter"));
// 该值缺省为false,表示生命周期由SpringApplicationContext管理,设置为true则表示由ServletContainer管理
filterRegistration.addInitParameter("targetFilterLifecycle", "true");
filterRegistration.setEnabled(true);
filterRegistration.addUrlPatterns("/*");
return filterRegistration;
}
@Bean(name = "lifecycleBeanPostProcessor")
public LifecycleBeanPostProcessor getLifecycleBeanPostProcessor() {
return new LifecycleBeanPostProcessor();
}
@Bean
public DefaultAdvisorAutoProxyCreator getDefaultAdvisorAutoProxyCreator() {
DefaultAdvisorAutoProxyCreator daap = new DefaultAdvisorAutoProxyCreator();
daap.setProxyTargetClass(true);
return daap;
}
@Bean(name = "securityManager")
public DefaultWebSecurityManager getDefaultWebSecurityManager(AuthsMySQLRealm authsMySQLRealm) {
DefaultWebSecurityManager dwsm = new DefaultWebSecurityManager();
dwsm.setRealm(authsMySQLRealm);
// <!-- 用户授权/认证信息Cache, 采用EhCache 缓存 -->
// dwsm.setCacheManager(getEhCacheManager());
return dwsm;
}
@Bean
public AuthorizationAttributeSourceAdvisor getAuthorizationAttributeSourceAdvisor(AuthsMySQLRealm authsMySQLRealm) {
AuthorizationAttributeSourceAdvisor aasa = new AuthorizationAttributeSourceAdvisor();
aasa.setSecurityManager(getDefaultWebSecurityManager(authsMySQLRealm));
return new AuthorizationAttributeSourceAdvisor();
}
/**
* 加载shiroFilter权限控制规则(从数据库读取然后配置)
*/
@Bean(name = "shiroFilter")
public ShiroFilterFactoryBean getShiroFilterFactoryBean(AuthsMySQLRealm authsMySQLRealm) {
ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
shiroFilterFactoryBean.setSecurityManager(getDefaultWebSecurityManager(authsMySQLRealm));
shiroFilterFactoryBean.setLoginUrl("/login");
shiroFilterFactoryBean.setSuccessUrl("/login_enter");
shiroFilterFactoryBean.setUnauthorizedUrl("/403");
Map<String, String> filterChainDefinitionMap = new LinkedHashMap<String, String>();
filterChainDefinitionMap.put("/test", "anon");
filterChainDefinitionMap.put("/bbbb", "authc,perms[emp]");
/*filterChainDefinitionMap.put("/testtt", "authc");
filterChainDefinitionMap.put("/**", "user");*/
shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
return shiroFilterFactoryBean;
}
}
AuthsMySQLRealm
package com.ylm.jspshiro.util;
import com.ylm.jspshiro.entity.User;
import com.ylm.jspshiro.service.AuthService;
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.stereotype.Component;
import javax.annotation.Resource;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
@Component
public class AuthsMySQLRealm extends AuthorizingRealm {
@Resource
private AuthService authService;
@Override
public String getName() {
return "authsMySQLRealm";
}
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
Iterator iterator = principals.iterator();
if (iterator.hasNext()){
User user = (User) iterator.next();
List<String> codes = authService.findRoleCodeByUserId(user.getId());
if (codes != null && codes.size() > 0){
Set<String> codesSet = new HashSet<String>(codes);
Set<String> authsSet = new HashSet<String>();
for (String code : codes) {
List<String> auths = authService.findAuthCodeByRoleCode(String.valueOf(user.getId()));
// List<String> auths = authService.findAuthCodeByRoleCode(code);
authsSet.addAll(auths);
}
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
info.setRoles(codesSet);
info.setStringPermissions(authsSet);
return info;
}
}
return null;
}
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token)
throws AuthenticationException {
UsernamePasswordToken upToken = (UsernamePasswordToken)token;
String number = upToken.getUsername();
String pwd = new String(upToken.getPassword());
User user = authService.findUserByNumberAndPwd(number, pwd);
if (user != null){
SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, user.getPwd(), getName());
return info;
}
return null;
}
}
AuthMapper.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.ylm.jspshiro.dao.AuthDAO">
<resultMap id="authMap" type="com.ylm.jspshiro.entity.Auth">
<id column="auth_id" property="authId"></id>
<result column="auth_name" property="authName"></result>
<result column="auth_code" property="authCode"></result>
<association property="authGroup" column="group_id" select="com.ylm.jspshiro.dao.AuthGroupDAO.findById"></association>
</resultMap>
<select id="findAll" resultMap="authMap">
SELECT auth_id, auth_name, auth_code, group_id FROM auths
</select>
<select id="findByGroupId" resultMap="authMap">
SELECT auth_id, auth_name, auth_code, group_id FROM auths WHERE group_id = #{groupId}
</select>
<select id="findUserByNumberAndPwd" resultMap="com.ylm.jspshiro.dao.UserDAO.userMap">
SELECT user_id, user_name, user_number, user_pwd FROM users
WHERE user_number = #{number} AND user_pwd = #{pwd}
</select>
<select id="findRoleCodeByUserId" resultType="java.lang.String">
SELECT r.role_code FROM
roles r
INNER JOIN
users u
ON r.role_id = u.role_id
WHERE u.user_id = #{userId}
</select>
<select id="findAuthCodeByRoleCode" resultType="java.lang.String">
SELECT a.auth_code FROM
auths a
INNER JOIN
user_auth ur
ON a.auth_id = ur.auth_id
INNER JOIN users u
ON ur.user_id = u.user_id
WHERE u.user_id = #{userId}
</select>
</mapper>
User findUserByNumberAndPwd(@Param("number") String number, @Param("pwd") String pwd);