学习笔记 : SpringBoot集成Shiro的基本配置
Spring集成Shiro一般通过的 xml 配置,比较繁琐,而Spring Boot集成Shiro相对简单,只需要配置两个类 : ShiroConfiguration类及继承AuthorizingRealm的Realm类,如下所示 :
ShiroConfig
: 顾名思义就是对Shiro的一些配置,相对于Spring中的xml配置. 包括 : 包括过滤器(ShiroFilter)、安全事务管理器(SecurityManager)、密码凭证匹配器(CredentialsMatcher)、缓冲管理器(EhCacheManager)、aop注解支持(authorizationAttributeSourceAdvisor)、等等
CustomRealm
: 自定义的CustomRealm继承自AuthorizingRealm,重写了父类中的doGetAuthorizationInfo(授权认证)、doGetAuthenticationInfo(登陆认证)这两个方法
基本的配置
以下示例代码摘自 : 一个简单的SpringBoot集成Shiro的权限管理案例
Shiro的基本配置信息
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144
| package pers.huangyuhui.ss.shiro;
import at.pollux.thymeleaf.shiro.dialect.ShiroDialect; import net.sf.ehcache.CacheManager; import org.apache.shiro.authc.credential.HashedCredentialsMatcher; import org.apache.shiro.cache.ehcache.EhCacheManager; import org.apache.shiro.mgt.SecurityManager; import org.apache.shiro.spring.web.ShiroFilterFactoryBean; import org.apache.shiro.web.mgt.DefaultWebSecurityManager; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration;
import java.util.LinkedHashMap; import java.util.Map;
@Configuration public class ShiroConfig {
@Bean public ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityManager securityManager) { ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean(); shiroFilterFactoryBean.setSecurityManager(securityManager); shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap()); shiroFilterFactoryBean.setLoginUrl("/loginView"); shiroFilterFactoryBean.setUnauthorizedUrl("/unauthorizedView"); return shiroFilterFactoryBean; }
@Bean public UserRealm userRealm(HashedCredentialsMatcher hashedCredentialsMatcher) { UserRealm userRealm = new UserRealm(); userRealm.setCredentialsMatcher(hashedCredentialsMatcher); return userRealm; }
@Bean public SecurityManager securityManager(UserRealm userRealm, EhCacheManager ehCacheManager) { DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager(); defaultWebSecurityManager.setRealm(userRealm); defaultWebSecurityManager.setCacheManager(ehCacheManager); return defaultWebSecurityManager; }
@Bean public HashedCredentialsMatcher hashedCredentialsMatcher() { HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher(); hashedCredentialsMatcher.setHashAlgorithmName("md5"); hashedCredentialsMatcher.setHashIterations(3); hashedCredentialsMatcher.setStoredCredentialsHexEncoded(true); return hashedCredentialsMatcher; }
@Bean public EhCacheManager ehCacheManager() { CacheManager cacheManager = CacheManager.getCacheManager("myEhcache"); if (cacheManager == null) { cacheManager = CacheManager.create(); } EhCacheManager ehCacheManager = new EhCacheManager(); ehCacheManager.setCacheManager(cacheManager); return ehCacheManager; }
private Map<String, String> filterChainDefinitionMap() { Map<String, String> filterMap = new LinkedHashMap<>(); filterMap.put("/stuListView", "authc"); filterMap.put("/teaListView", "authc"); filterMap.put("/login", "anon"); filterMap.put("/logout", "logout"); filterMap.put("/teaListView", "roles[admin]"); filterMap.put("/stuListView", "perms[stuListView:view]"); filterMap.put("/teaListView", "perms[teaListView:view]"); filterMap.put("/**", "authc"); return filterMap; }
@Bean public ShiroDialect shiroDialect() { return new ShiroDialect(); }
}
|
ehcache-shiro.xml : EhCache缓存框架的配置文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
| <?xml version="1.0" encoding="UTF-8"?> <ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd" updateCheck="false" name="myEhcache"> <diskStore path="java.io.tmpdir"/> <cache name="authorizationCache" maxEntriesLocalHeap="2000" timeToIdleSeconds="1800" timeToLiveSeconds="1800" overflowToDisk="false" statistics="true"> </cache> <cache name="authenticationCache" maxEntriesLocalHeap="2000" timeToIdleSeconds="1800" timeToLiveSeconds="1800" overflowToDisk="false" statistics="true"> </cache> <cache name="activeSessionCache" maxEntriesLocalHeap="2000" timeToIdleSeconds="1800" timeToLiveSeconds="1800" overflowToDisk="false" statistics="true"> </cache> <cache name="halfHour" maxElementsInMemory="10000" maxElementsOnDisk="100000" timeToIdleSeconds="1800" timeToLiveSeconds="1800" overflowToDisk="false" diskPersistent="false"/> <cache name="hour" maxElementsInMemory="10000" maxElementsOnDisk="100000" timeToIdleSeconds="3600" timeToLiveSeconds="3600" overflowToDisk="false" diskPersistent="false"/> <cache name="oneDay" maxElementsInMemory="10000" maxElementsOnDisk="100000" timeToIdleSeconds="86400" timeToLiveSeconds="86400" overflowToDisk="false" diskPersistent="false"/>
<defaultCache name="defaultCache" maxElementsInMemory="10000" timeToIdleSeconds="600" timeToLiveSeconds="600" overflowToDisk="false" maxElementsOnDisk="100000" diskPersistent="false" diskExpiryThreadIntervalSeconds="120" memoryStoreEvictionPolicy="LRU"> </defaultCache> </ehcache>
|
自定义Realm
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
| package pers.huangyuhui.ss.shiro;
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.apache.shiro.subject.Subject; import org.apache.shiro.util.ByteSource; import org.springframework.beans.factory.annotation.Autowired; import pers.huangyuhui.ss.bean.Permission; import pers.huangyuhui.ss.bean.Role; import pers.huangyuhui.ss.bean.User; import pers.huangyuhui.ss.service.UserService;
import java.util.Collection; import java.util.HashSet; import java.util.Set;
public class UserRealm extends AuthorizingRealm {
@Autowired private UserService userService;
@Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) { System.err.println("------------> 授权认证 ------------>"); Subject currentUser = SecurityUtils.getSubject(); User u = (User) currentUser.getPrincipal(); User user = userService.findByName(u.getUsername()); if (user != null) { SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(); Collection<String> rolesCollection = new HashSet<>(); Collection<String> permissionsCollection = new HashSet<>(); Set<Role> roles = user.getRoles(); for (Role role : roles) { rolesCollection.add(role.getName()); Set<Permission> permissionSet = role.getPermissions(); for (Permission permission : permissionSet) { permissionsCollection.add(permission.getName()); } info.addStringPermissions(permissionsCollection); } info.addRoles(rolesCollection); System.out.println("[roles]------------>" + rolesCollection.toString()); System.out.println("[permissions]------------>" + permissionsCollection.toString()); return info; } return null; }
@Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException { System.err.println("------------> 开始认证 ------------>"); UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken; User user = userService.findByName(token.getUsername()); if (user == null) { return null; } return new SimpleAuthenticationInfo(user, user.getPassword(), ByteSource.Util.bytes(user.getUsername()), this.getName()); } }
|