SpringBoot 는 shiro - ehcache 캐 시 를 사용 합 니 다.
27187 단어 SpringBootshiro
4.0.0
org.springframework.boot
spring-boot-starter-parent
2.1.4.RELEASE
com.example
springboot-shiro
0.0.1-SNAPSHOT
springboot-shiro
Demo project for Spring Boot
1.8
org.springframework.boot
spring-boot-starter-thymeleaf
org.springframework.boot
spring-boot-starter-web
org.mybatis.spring.boot
mybatis-spring-boot-starter
2.0.1
mysql
mysql-connector-java
runtime
org.projectlombok
lombok
true
org.springframework.boot
spring-boot-starter-test
test
org.apache.shiro
shiro-spring
1.4.0
cn.hutool
hutool-all
4.5.7
org.apache.shiro
shiro-ehcache
1.4.0
org.springframework.boot
spring-boot-maven-plugin
org.mybatis.generator
mybatis-generator-maven-plugin
1.3.7
src/main/resources/mybatis-generator-config.xml
true
true
org.mybatis.generator
mybatis-generator-core
1.3.7
데이터베이스 파일:
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for permission
-- ----------------------------
DROP TABLE IF EXISTS `permission`;
CREATE TABLE `permission` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT ' id',
`name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT ' ',
`permission` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT ' ',
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 10 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of permission
-- ----------------------------
INSERT INTO `permission` VALUES (1, ' ', 'user:list');
INSERT INTO `permission` VALUES (2, ' / ', 'user:add');
INSERT INTO `permission` VALUES (3, ' ', 'user:delete');
INSERT INTO `permission` VALUES (4, ' ', 'user:edit');
INSERT INTO `permission` VALUES (5, ' ', 'post:list');
INSERT INTO `permission` VALUES (6, ' ', 'post:search');
INSERT INTO `permission` VALUES (7, ' ', 'post:new');
INSERT INTO `permission` VALUES (8, ' / ', 'post:save');
INSERT INTO `permission` VALUES (9, ' ', 'post:edit');
-- ----------------------------
-- Table structure for role
-- ----------------------------
DROP TABLE IF EXISTS `role`;
CREATE TABLE `role` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT ' id',
`role` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT ' ',
`description` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT ' ',
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 4 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of role
-- ----------------------------
INSERT INTO `role` VALUES (1, 'admin', ' ');
INSERT INTO `role` VALUES (2, 'author', ' ');
INSERT INTO `role` VALUES (3, 'subscriber', ' ');
-- ----------------------------
-- Table structure for role_permission_ref
-- ----------------------------
DROP TABLE IF EXISTS `role_permission_ref`;
CREATE TABLE `role_permission_ref` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT ' role_permission_id',
`role_id` int(11) NOT NULL COMMENT ' id',
`permission_id` int(11) NOT NULL COMMENT ' id',
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 10 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of role_permission_ref
-- ----------------------------
INSERT INTO `role_permission_ref` VALUES (1, 1, 1);
INSERT INTO `role_permission_ref` VALUES (2, 1, 2);
INSERT INTO `role_permission_ref` VALUES (3, 1, 3);
INSERT INTO `role_permission_ref` VALUES (4, 1, 4);
INSERT INTO `role_permission_ref` VALUES (5, 1, 5);
INSERT INTO `role_permission_ref` VALUES (6, 1, 6);
INSERT INTO `role_permission_ref` VALUES (7, 1, 7);
INSERT INTO `role_permission_ref` VALUES (8, 1, 8);
INSERT INTO `role_permission_ref` VALUES (9, 1, 9);
INSERT INTO `role_permission_ref` VALUES (10, 2, 1);
-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT ' id',
`username` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT ' ',
`password` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT ' ',
`name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT ' ',
`salt` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT ' ',
`email` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT ' ',
`create_time` timestamp(0) NOT NULL ON UPDATE CURRENT_TIMESTAMP(0) COMMENT ' ',
`update_time` timestamp(0) NOT NULL ON UPDATE CURRENT_TIMESTAMP(0) COMMENT ' ',
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 3 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES (1, 'tom', '9ade9a62fe19ed021b87f8dff0236ad7', ' ', 'n3R2XG', '[email protected]', '2019-05-05 10:38:49', '2019-05-05 10:38:49');
INSERT INTO `user` VALUES (2, 'cat', '5b345ca8ab78e8728cc8448203246496', 'CAT', '1gvEVM', '[email protected]', '2019-05-05 10:39:11', '2019-05-05 10:39:11');
-- ----------------------------
-- Table structure for user_role_ref
-- ----------------------------
DROP TABLE IF EXISTS `user_role_ref`;
CREATE TABLE `user_role_ref` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT ' user_role_id',
`user_id` int(11) NOT NULL COMMENT ' id',
`role_id` int(11) NOT NULL COMMENT ' id',
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 5 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of user_role_ref
-- ----------------------------
INSERT INTO `user_role_ref` VALUES (1, 1, 1);
INSERT INTO `user_role_ref` VALUES (2, 1, 2);
INSERT INTO `user_role_ref` VALUES (3, 1, 3);
INSERT INTO `user_role_ref` VALUES (4, 2, 2);
SET FOREIGN_KEY_CHECKS = 1;
Shiro 프로필
package com.example.springbootshiro.shiro;
import lombok.extern.log4j.Log4j2;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.cache.CacheManager;
import org.apache.shiro.cache.MemoryConstrainedCacheManager;
import org.apache.shiro.cache.ehcache.EhCacheManager;
import org.apache.shiro.codec.Base64;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.CookieRememberMeManager;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.servlet.SimpleCookie;
import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.config.MethodInvokingFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.LinkedHashMap;
import java.util.Map;
@Configuration
@Log4j2
public class ShiroConfig {
/**
* ShiroFilterFactoryBean
*/
@Bean
public ShiroFilterFactoryBean shiroFilter(@Qualifier("securityManager") SecurityManager securityManager){
log.info(" 【shiroFilter】");
ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
shiroFilterFactoryBean.setSecurityManager(securityManager);
//
Map filterChainDefinitionMap = new LinkedHashMap<>();
filterChainDefinitionMap.put("/static/**", "anon");
filterChainDefinitionMap.put("/user/login", "anon");
filterChainDefinitionMap.put("/user/logout", "logout");
//
// filterChainDefinitionMap.put("/add", "roles[admin]");
// filterChainDefinitionMap.put("/delete", "roles[admin]");
// filterChainDefinitionMap.put("/delete", "roles[author]");
filterChainDefinitionMap.put("/addPermission", "roles[author]");
filterChainDefinitionMap.put("/add", "perms[user:add]");
filterChainDefinitionMap.put("/delete", "perms[user:delete]");
filterChainDefinitionMap.put("/userList", "perms[user:list]");
// /**
// Map , , ,
// ,
// /**
filterChainDefinitionMap.put("/**", "authc");
// shiro
shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
// Web "/login.jsp"
shiroFilterFactoryBean.setLoginUrl("/login");
//
shiroFilterFactoryBean.setSuccessUrl("/index");
//
shiroFilterFactoryBean.setUnauthorizedUrl("/403");
return shiroFilterFactoryBean;
}
/**
* securityManager
*/
@Bean(name = "securityManager")
public SecurityManager securityManager(
@Qualifier("myShiroRealm") MyShiroRealm myShiroRealm,
@Qualifier("rememberMeManager") CookieRememberMeManager rememberMeManager,
// @Qualifier("cacheManager") CacheManager cacheManager,
@Qualifier("ehCacheManager")EhCacheManager ehCacheManager){
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
// securityManager.setCacheManager(cacheManager);
securityManager.setCacheManager(ehCacheManager);
securityManager.setRememberMeManager(rememberMeManager);
securityManager.setRealm(myShiroRealm);
return securityManager;
}
/**
* shiroRealm
*/
@Bean(name = "myShiroRealm")
public MyShiroRealm myShiroRealm(@Qualifier("hashedCredentialsMatcher") HashedCredentialsMatcher hashedCredentialsMatcher){
MyShiroRealm myShiroRealm = new MyShiroRealm();
myShiroRealm.setCachingEnabled(true);
// , AuthenticationInfo , false
myShiroRealm.setAuthenticationCachingEnabled(true);
// AuthenticationInfo ehcache-shiro.xml
myShiroRealm.setAuthenticationCacheName("authenticationCache");
// , AuthorizationInfo , false
myShiroRealm.setAuthorizationCachingEnabled(true);
// AuthorizationInfo ehcache-shiro.xml
myShiroRealm.setAuthorizationCacheName("authorizationCache");
myShiroRealm.setCredentialsMatcher(hashedCredentialsMatcher);
return new MyShiroRealm();
}
/**
*
*
* @return
*/
@Bean(name = "hashedCredentialsMatcher")
public HashedCredentialsMatcher hashedCredentialsMatcher() {
log.info("hashedCredentialsMatcher()");
HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();
hashedCredentialsMatcher.setHashAlgorithmName("MD5");// : MD5 ;
hashedCredentialsMatcher.setHashIterations(1024);// , , md5(md5(""));
return hashedCredentialsMatcher;
}
/**
* cookie
* @return
*/
@Bean(name = "rememberMeCookie")
public SimpleCookie rememberMeCookie(){
SimpleCookie simpleCookie = new SimpleCookie("rememberMe");
simpleCookie.setHttpOnly(true);
// 30
simpleCookie.setMaxAge(259200);
return simpleCookie;
}
@Bean(name = "rememberMeManager")
public CookieRememberMeManager rememberMeManager(@Qualifier("rememberMeCookie")SimpleCookie rememberMeCookie){
CookieRememberMeManager cookieRememberMeManager = new CookieRememberMeManager();
cookieRememberMeManager.setCookie(rememberMeCookie);
//rememberMe cookie AES (128 256 512 )
cookieRememberMeManager.setCipherKey(Base64.decode("2AvVhdsgUs0FSA3SDFAdag=="));
return cookieRememberMeManager;
}
/**
* shiro aop
* ;
* @param securityManager
*/
@Bean
public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager){
AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
return authorizationAttributeSourceAdvisor;
}
/**
* cglib
*/
@Bean
public DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator() {
DefaultAdvisorAutoProxyCreator creator = new DefaultAdvisorAutoProxyCreator();
creator.setProxyTargetClass(true);
return creator;
}
//
//shiro MemoryConstrainedCacheManager
// , , ehcache
@Bean(name = "cacheManager")
public CacheManager cacheManager() {
MemoryConstrainedCacheManager cacheManager=new MemoryConstrainedCacheManager();//
return cacheManager;
}
// ehcache
@Bean(name = "ehCacheManager")
public EhCacheManager ehCacheManager(){
EhCacheManager ehCacheManager = new EhCacheManager();
ehCacheManager.setCacheManagerConfigFile("classpath:config/ehcache-shiro.xml");
return ehCacheManager;
}
// spring , , ,
// spring PropertyPlaceholderConfigurer ,
// org.springframework.beans.factory.config.MethodInvokingFactoryBean bean 。
// MethodInvokingFactory Bean , 。
// MethodInvokingFactoryBean , , 。
// bean , bean
// http://blog.sina.com.cn/s/blog_72ef7bea0102wa0v.html
/**
* Bean
* Spring
* @param myShiroRealm
* @param rememberMeManager
* @param ehCacheManager
* @return
*/
@Bean(name = "methodInvokingFactoryBean")
public MethodInvokingFactoryBean methodInvokingFactoryBean(
@Qualifier("myShiroRealm") MyShiroRealm myShiroRealm,
@Qualifier("rememberMeManager") CookieRememberMeManager rememberMeManager,
@Qualifier("ehCacheManager")EhCacheManager ehCacheManager){
MethodInvokingFactoryBean factoryBean = new MethodInvokingFactoryBean();
factoryBean.setStaticMethod("org.apache.shiro.SecurityUtils.setSecurityManager");
factoryBean.setArguments(new Object[]{securityManager(myShiroRealm, rememberMeManager,ehCacheManager)});
return factoryBean;
}
}
사용자 정의 Realm:
package com.example.springbootshiro.shiro;
import cn.hutool.core.lang.Validator;
import com.example.springbootshiro.entity.Permission;
import com.example.springbootshiro.entity.Role;
import com.example.springbootshiro.entity.User;
import com.example.springbootshiro.service.PermissionService;
import com.example.springbootshiro.service.RoleService;
import com.example.springbootshiro.service.UserService;
import lombok.extern.log4j.Log4j2;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.List;
@Log4j2
public class MyShiroRealm extends AuthorizingRealm {
@Autowired
private UserService userService;
@Autowired
private RoleService roleService;
@Autowired
private PermissionService permissionService;
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
log.info(" 【doGetAuthorizationInfo】");
SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
User user = (User) principals.getPrimaryPrincipal();
List roleList = roleService.getRoleListByUserId(user.getId());
for (Role role : roleList) {
//
authorizationInfo.addRole(role.getRole());
List permissionList = permissionService.getPermissionListByRoleId(role.getId());
for (Permission permission : permissionList) {
//
authorizationInfo.addStringPermission(permission.getPermission());
}
}
return authorizationInfo;
}
/**
*
* @param authenticationToken
* @return
* @throws AuthenticationException
*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
// post ,
if (authenticationToken.getPrincipal() == null){
return null;
}
log.info(" 【doGetAuthenticationInfo】");
UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
String username = token.getUsername();
User user = null;
if (Validator.isEmail(username)){
user = userService.getUserByEmail(username);
}else {
user = userService.getUserByUserName(username);
}
if (user == null){
log.info(" !");
return null;
}
// AuthenticationInfo,
SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(
user, user.getPassword(), ByteSource.Util.bytes(user.getSalt()), getName());
return info;
}
/**
* ,
* @param principals
*/
@Override
public void clearCachedAuthorizationInfo(PrincipalCollection principals) {
super.clearCachedAuthorizationInfo(principals);
}
/**
* ,
* @param principals
*/
@Override
public void clearCachedAuthenticationInfo(PrincipalCollection principals) {
super.clearCachedAuthenticationInfo(principals);
}
@Override
public void clearCache(PrincipalCollection principals) {
super.clearCache(principals);
}
/**
* :
*/
public void clearAllCachedAuthorizationInfo() {
getAuthorizationCache().clear();
}
/**
* :
*/
public void clearAllCachedAuthenticationInfo() {
getAuthenticationCache().clear();
}
/**
* :
*/
public void clearAllCache() {
clearAllCachedAuthenticationInfo();
clearAllCachedAuthorizationInfo();
}
/**
*
* @param args
*/
public static void main(String[] args) {
String hashAlgorithName = "MD5";
String password = "123";
int hashIterations = 1024;
ByteSource credentialsSalt = ByteSource.Util.bytes("tom");
Object obj = new SimpleHash(hashAlgorithName, password, credentialsSalt, hashIterations);
log.info(obj);
}
}
resources 아래 에 config 폴 더 를 새로 만 들 고 ehcache - shiro. xml 파일 을 만 듭 니 다.
주요 프로필 이 여기 있 습 니 다.토론 을 환영 합 니 다. 프로그램 에 오류 가 발생 하면 가볍게 뿌 려 주세요 ~ ~
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
【Java・SpringBoot・Thymeleaf】 에러 메세지를 구현(SpringBoot 어플리케이션 실천편 3)로그인하여 사용자 목록을 표시하는 응용 프로그램을 만들고, Spring에서의 개발에 대해 공부하겠습니다 🌟 마지막 데이터 바인딩에 계속 바인딩 실패 시 오류 메시지를 구현합니다. 마지막 기사🌟 src/main/res...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.