ShiroConfig.java 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  1. /**
  2. * The MIT License (MIT)
  3. * Copyright (c) 2012-present 铭软科技(mingsoft.net)
  4. * Permission is hereby granted, free of charge, to any person obtaining a copy of
  5. * this software and associated documentation files (the "Software"), to deal in
  6. * the Software without restriction, including without limitation the rights to
  7. * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
  8. * the Software, and to permit persons to whom the Software is furnished to do so,
  9. * subject to the following conditions:
  10. * <p>
  11. * The above copyright notice and this permission notice shall be included in all
  12. * copies or substantial portions of the Software.
  13. * <p>
  14. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
  16. * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
  17. * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
  18. * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
  19. * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  20. */
  21. package net.mingsoft.config;
  22. import jakarta.annotation.Resource;
  23. import jakarta.servlet.Filter;
  24. import net.mingsoft.basic.filter.ShiroLoginFilter;
  25. import net.mingsoft.basic.filter.ShiroRoleFilter;
  26. import net.mingsoft.basic.realm.CustomModularRealmAuthenticator;
  27. import net.mingsoft.basic.realm.ManagerAuthRealm;
  28. import net.mingsoft.basic.strategy.ILoginStrategy;
  29. import net.mingsoft.basic.strategy.IModelStrategy;
  30. import net.mingsoft.basic.strategy.ManagerLoginStrategy;
  31. import net.mingsoft.basic.strategy.ManagerModelStrategy;
  32. import net.mingsoft.people.action.web.WxCustomUserNamePasswordToken;
  33. import net.mingsoft.people.filter.PeopleLoginFilter;
  34. import net.mingsoft.people.realm.PeopleAuthRealm;
  35. import net.mingsoft.people.realm.PeopleLoginMD5CredentialsMatcher;
  36. import org.apache.shiro.authc.AuthenticationInfo;
  37. import org.apache.shiro.authc.AuthenticationToken;
  38. import org.apache.shiro.authc.Authenticator;
  39. import org.apache.shiro.authc.pam.AtLeastOneSuccessfulStrategy;
  40. import org.apache.shiro.mgt.SecurityManager;
  41. import org.apache.shiro.realm.Realm;
  42. import org.apache.shiro.session.mgt.eis.MemorySessionDAO;
  43. import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
  44. import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
  45. import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
  46. import org.apache.shiro.web.servlet.SimpleCookie;
  47. import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
  48. import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;
  49. import org.springframework.beans.factory.annotation.Autowired;
  50. import org.springframework.boot.autoconfigure.web.ServerProperties;
  51. import org.springframework.context.annotation.Bean;
  52. import org.springframework.context.annotation.Configuration;
  53. import java.util.LinkedHashMap;
  54. import java.util.List;
  55. import java.util.Map;
  56. @Configuration
  57. public class ShiroConfig {
  58. @Autowired(required = false)
  59. MSProperties msProperties;
  60. @Resource
  61. ServerProperties serverProperties;
  62. /**
  63. * 开启Shiro的注解(如@RequiresRoles , @RequiresPermissions),需借助SspringAOP扫描使用Sshiro注解的类,并在必要时进行安全逻辑验证
  64. * 配置以下两个bean(Defaul tAdvisorAutoProxyCreator和uthorizat ionAttributeSourceAdvisor)即可实现此功能
  65. */
  66. @Bean
  67. public DefaultAdvisorAutoProxyCreator advisorAutoProxyCreator() {
  68. DefaultAdvisorAutoProxyCreator advisorAutoProxyCreator = new DefaultAdvisorAutoProxyCreator();
  69. advisorAutoProxyCreator.setProxyTargetClass(true);
  70. return advisorAutoProxyCreator;
  71. }
  72. /**
  73. * 开启shiro aop注解支持
  74. * 使用代理方式;所以需要开启代码支持
  75. * @param securityManager
  76. */
  77. @Bean
  78. public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager) {
  79. AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
  80. authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
  81. return authorizationAttributeSourceAdvisor;
  82. }
  83. @Bean
  84. public AuthorizationAttributeSourceAdvisor getAuthorizationAttributeSourceAdvisor(
  85. @Autowired(required = false) DefaultWebSecurityManager securityManager) {
  86. AuthorizationAttributeSourceAdvisor advisor = new AuthorizationAttributeSourceAdvisor();
  87. advisor.setSecurityManager(securityManager);
  88. return advisor;
  89. }
  90. @Bean
  91. public DefaultAdvisorAutoProxyCreator getDefaultAdvisorAutoProxyCreator() {
  92. DefaultAdvisorAutoProxyCreator autoProxyCreator = new DefaultAdvisorAutoProxyCreator();
  93. autoProxyCreator.setProxyTargetClass(true);
  94. return autoProxyCreator;
  95. }
  96. @Bean(name = "shiroFilterFactoryBean")
  97. public ShiroFilterFactoryBean shirFilter(SecurityManager securityManager) {
  98. ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
  99. // 必须设置 SecurityManager
  100. shiroFilterFactoryBean.setSecurityManager(securityManager);
  101. // setLoginUrl 如果不设置值,默认会自动寻找Web工程根目录下的"/login.jsp"页面 或 "/login" 映射
  102. shiroFilterFactoryBean.setLoginUrl(MSProperties.manager.path + "/login.do");
  103. // 设置无权限时跳转的 url;
  104. shiroFilterFactoryBean.setUnauthorizedUrl(MSProperties.manager.path + "/404.do");
  105. Map<String, Filter> filters = shiroFilterFactoryBean.getFilters();
  106. filters.put("authc", new ShiroLoginFilter());
  107. // 依赖会员后需放开104行,107行
  108. // PeopleLoginFilter会员登录过滤器,在这里people/**接口都会拦截校验是否登录
  109. filters.put("pauth", new PeopleLoginFilter(MSProperties.people.loginUrl));
  110. // 角色校验过滤器最终会在对应的reaml中的hasRole校验,可以在ShiroRoleFilter中自定义一些操作
  111. filters.put("managerRoles", new ShiroRoleFilter(MSProperties.manager.path + "/login.do"));
  112. filters.put("peopleRoles", new ShiroRoleFilter(MSProperties.people.loginUrl));
  113. // 设置拦截器
  114. Map<String, String> filterChainDefinitionMap = new LinkedHashMap<>();
  115. // 游客,开发权限
  116. filterChainDefinitionMap.put("/static/**", "anon");
  117. filterChainDefinitionMap.put("/html/**", "anon");
  118. // 开放登陆接口
  119. filterChainDefinitionMap.put(MSProperties.manager.path + "/login.do", "anon");
  120. filterChainDefinitionMap.put(MSProperties.manager.path + "/checkLogin.do", "anon");
  121. // 其余接口一律拦截
  122. // 主要这行代码必须放在所有权限设置的最后,不然会导致所有 url 都被拦截
  123. // 依赖会员后,放开123行以及202-205行
  124. // roles[**]中的**值必须和对应的Reaml赋予当前登录的Roles名称一致,然后值必须时CustomUserNamePasswordToken.AuthType中的值,如果这里值和对应Reaml值不一致则会出现无法访问情况
  125. filterChainDefinitionMap.put(msProperties.getManager().path + "/**", "authc,managerRoles[MANAGER]");
  126. filterChainDefinitionMap.put("/people/**", "pauth,peopleRoles[PEOPLE]");
  127. shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
  128. return shiroFilterFactoryBean;
  129. }
  130. /**
  131. * 注入 securityManager
  132. */
  133. @Bean("securityManager")
  134. public DefaultWebSecurityManager securityManager(List<Realm> realms, Authenticator authenticator, DefaultWebSessionManager sessionManager) {
  135. DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
  136. securityManager.setSessionManager(sessionManager);
  137. securityManager.setAuthenticator(authenticator);
  138. // 集群环境下使用redis共享session用下行代码
  139. // securityManager.setCacheManager(shiroRedisCacheManager);
  140. // 设置realm
  141. securityManager.setRealms(realms);
  142. return securityManager;
  143. }
  144. /**
  145. * 重写defaultWebSessionManager,防止url拼接jsessionid
  146. * @return
  147. */
  148. @Bean
  149. public DefaultWebSessionManager defaultWebSessionManager() {
  150. DefaultWebSessionManager sessionManager = new DefaultWebSessionManager();
  151. if (serverProperties.getServlet().getSession().getTimeout() != null) {
  152. // 单位毫秒
  153. sessionManager.setGlobalSessionTimeout(serverProperties.getServlet().getSession().getTimeout().getSeconds() * 1000L);
  154. }
  155. sessionManager.setSessionDAO(getMemorySessionDAO());
  156. sessionManager.setSessionIdCookie(getSimpleCookie());
  157. sessionManager.setSessionIdUrlRewritingEnabled(false);
  158. return sessionManager;
  159. }
  160. /**
  161. * 身份验证器
  162. * @return Authenticator
  163. */
  164. @Bean
  165. public Authenticator authenticator() {
  166. CustomModularRealmAuthenticator modularRealmAuthenticator = new CustomModularRealmAuthenticator();
  167. modularRealmAuthenticator.setAuthenticationStrategy(new AtLeastOneSuccessfulStrategy());
  168. return modularRealmAuthenticator;
  169. }
  170. @Bean
  171. public MemorySessionDAO getMemorySessionDAO() {
  172. return new MemorySessionDAO();
  173. }
  174. @Bean
  175. public SimpleCookie getSimpleCookie() {
  176. SimpleCookie simpleCookie = new SimpleCookie();
  177. simpleCookie.setName(msProperties.getCookieName());
  178. return simpleCookie;
  179. }
  180. /**
  181. * 自定义身份认证 realm;
  182. * <p>
  183. * 必须写这个类,并加上 @Bean 注解,目的是注入 CustomRealm, 否则会影响 CustomRealm类 中其他类的依赖注入
  184. */
  185. @Bean
  186. public ManagerAuthRealm customRealm() {
  187. return new ManagerAuthRealm();
  188. }
  189. /**
  190. * 自定义会员身份认证realm,依赖会员后放开202-205行
  191. * @return
  192. */
  193. @Bean("peopleAuth")
  194. public PeopleAuthRealm peopleAuthRealm() {
  195. PeopleAuthRealm peopleAuthRealm = new PeopleAuthRealm();
  196. peopleAuthRealm.setCredentialsMatcher(new PeopleLoginMD5CredentialsMatcher() {
  197. @Override
  198. public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {
  199. if (token instanceof WxCustomUserNamePasswordToken) {
  200. // 微信登录,忽略密码验证
  201. return true;
  202. }
  203. return super.doCredentialsMatch(token, info);
  204. }
  205. });
  206. return peopleAuthRealm;
  207. }
  208. /**
  209. * 管理员菜单策略
  210. *
  211. * @return
  212. */
  213. @Bean
  214. public IModelStrategy modelStrategy() {
  215. return new ManagerModelStrategy();
  216. }
  217. /**
  218. * 管理登录策略
  219. *
  220. * @return
  221. */
  222. @Bean
  223. public ILoginStrategy loginStrategy() {
  224. return new ManagerLoginStrategy();
  225. }
  226. }