资讯专栏INFORMATION COLUMN

在NutzBoot中拆分Shiro.ini配置文件使 Urls 可以配置多个并和 main 配置分离

eternalshallow / 1036人阅读

摘要:简介为一个基于框架的微服务方案以下简称其余略文档简介简介首先关于以及等介绍以及微服务的概念在此略过本文中介绍的方法基于框架但实现思路和核心类应该可以在其他框架中通用一首先阐述一下研究这个东西的出发点一开始在中也是使用的配置文件完成对的配置的

Nutzboot简介:

 NutzBoot为一个基于Nutz框架的微服务方案,以下简称NB!其余略...

 NB文档简介:http://www.nutzam.com/core/bo...

简介:

 首先关于Nutz以及NB,shiro等介绍以及微服务的概念在此略过,本文中介绍的方法基于Nutz框架,但实现思路和核心类应该可以在其他框架中通用.

一.首先阐述一下研究这个东西的出发点.

 一开始在NB中也是使用的shiro.ini配置文件完成对shiro的配置的,但是在实际开发过程中发现,在配置微服务的过程中,shiro文件需要配置或复制多次,这里插一嘴我们的实现方式,我们服务的实现方式为,所有需要独立部署的服务器都会实现同一个基础服务器运行库,来完成通用配置等.

 在配置多个服务器的时候发现不同服务器之间如果只使用一个shiro.ini配置文件会出现,[urls]配置下的url重复的情况,即例如前后台的/user/login接口,既是在NB的配置中配置不同服务器上下文,也无法避免同一个shiro配置文件出现此问题

 为了解决这个问题其实也想过将不同服务的配置文件分离(当然这在NB结构中是可以实现的),但是出现shiro.ini中[main]等配置被复制多次的情况,不美观也不利于修改.

二.解决思路

 为了解决这个问题其实一开始想到的是通过NB中shiro-stater中已有的 shiro.ini.urls 配置解决(这个配置允许在其他一个文件中手写shiro urls 配置列表)

 后来发现这个配置无法和 shiro.ini配置文件一起使用(这个配置大概是给使用默认配置的同学使用的)

 而已有的shiro大部分配置都在shiro.ini配置文件中,不太可能写成代码形式,只能另寻他法

 最后经过几经寻找,最终确定能解决这个问题的方法是(也修改了很多次,这里说了最后两种)

 1.复制shiro-starter源码,利用其中已有的重写shiro的 EnvironmentLoaderListener的类,以和之前部分相同的逻辑初始化Shiro.

 2.修改上述Listener在传入Environment处做修改(此处省略了starter获取配置文件路径并传入的部分,以及配置非空部分),传入一个重写的Environment,这个重写的类中大部分实现逻辑是由 shiro处理源码IniWebEnvironment类复制过来的,用来完成 shiro.ini文件的配置加载.

 3.修改重写类代码,使其可以获取到NB starter的配置(略,用来传入路径或urls),并修改源码中获取Filter的方法createFilterChainResolver()

 在其创建Filter实例之前插入代码

</>复制代码

  1. ini.load(String);

 源码:(此处检查了是否有 urls和filter配置)

</>复制代码

  1. // only create a resolver if the "filters" or "urls" sections are defined:
  2. Ini.Section urls = ini.getSection(IniFilterChainResolverFactory.URLS);
  3. Ini.Section filters = ini.getSection(IniFilterChainResolverFactory.FILTERS);
  4. if (!CollectionUtils.isEmpty(urls) || !CollectionUtils.isEmpty(filters)) {
  5. // either the urls section or the filters section was defined. Go ahead and create the resolver:
  6. IniFilterChainResolverFactory factory = new IniFilterChainResolverFactory(ini, this.objects);
  7. resolver = factory.getInstance();
  8. }

 修改后的代码(此处需要注意我们逻辑中没有 filter配置,这里就没判断)

</>复制代码

  1. //urls为符合 ini语法的字符串 例如 /user/login = anon
  2. String iniUrls = "[urls]
  3. " + urls;
  4. ini.load(iniUrls);
  5. // 此代码前,在此处ini会被加载成类
  6. // ini对象在此方法之前就存在,this.object则由父类中负责
  7. IniFilterChainResolverFactory factory = new IniFilterChainResolverFactory(ini, this.objects);
  8. resolver = factory.getInstance();

 这里需要注意在调用 ini.load后原文件中的 [urls] 配置会被覆盖,而当只有[urls] 但并没有实际内容时并不会被覆盖(没试过空行,请注意)

 4.在完成这段代码后发现代码非常难看,shiro urls被配置到了java文件中,为了避免这个问题使用了NB-start直接带的配置方式以及已经存在的 shiro.ini.urls属性,将配置文件中的 urls传入代码中

 所以在NB中就成了这样

</>复制代码

  1. //获取配置文件中urls
  2. String urls = conf.get(ShiroEnvStarter.PROP_INIT_URLS, null);
  3. //urls为符合 ini语法的字符串 例如 /user/login = anon
  4. String iniUrls = "[urls]
  5. " + urls;
  6. ini.load(iniUrls);
  7. // 此代码前,在此处ini会被加载成类
  8. // ini对象在此方法之前就存在,this.object则由父类中负责
  9. IniFilterChainResolverFactory factory = new IniFilterChainResolverFactory(ini, this.objects);
  10. resolver = factory.getInstance();

 在NB的application.properties配置文件中写法为

</>复制代码

  1. shiro.ini.urls:
  2. /unathenticated = anon
  3. /user/login = anon
  4. #end

 这里还要手动@并感谢下 @wendal @nutzcn
 之前并不知道application.properties中多行的写法

 至此,整个在代码中覆盖 shiro urls 配置的思路基本就完成了,只剩下一些类似于非空判断参数获取的代码.在此实现下即可实现项目中Shiro main配置为统一文件,而urls配置为专用多带带文件

 之后要介绍的就是优化部分以及,完整代码

三.优化(完全基于NB)

 1.在使用中发现虽然现在 urls已经可以独立文件配置,但多行之间并不可以写注解(在NB层就不会读取完整),并且和 shiro.ini中语法并不完全一样.

 最后解决办法为:在项目中添加另一个.ini的配置文件,并在项目中读取ini文件并使用 ini.load加载

 2.在添加了ini配置文件后发现最好可以有一部分urls可以通用配置,另一部分可以独立配置.

 最后解决方式为:添加两个shiro-url.ini配置文件,并在代码中读取并拼接,在库服务中添加,一个ini文件,并在每个独立的服务中添加完全同路径和名称的文件,使用其打包时互相覆盖的特性,达到独立配置的目的,而另一个不进行覆盖达到通用配置的目的.

 而在NB中通过在 starter源码中添加新的配置达到url可以配置并传入的目的.

</>复制代码

  1. @PropDoc(value = "urls过滤清单ini文件1路径")
  2. public static final String PROP_INIT_URLS_PATH1 = "shiro.ini.urls.path1";
  3. @PropDoc(value = "urls过滤清单ini文件2路径")
  4. public static final String PROP_INIT_URLS_PATH2 = "shiro.ini.urls.path2";

 这里附上读取并拼接两个 ini的代码

</>复制代码

  1. private boolean loadIniPath1ANd2(Ini ini) {
  2. String urlsAll = "";
  3. String urls1 = readConfig(ShiroEnvStarter.PROP_INIT_URLS_PATH1);
  4. String urls2 = readConfig(ShiroEnvStarter.PROP_INIT_URLS_PATH2);
  5. urlsAll = urls1 + urls2;
  6. if (!urlsAll.equals("")) {
  7. String iniUrls = "[urls]
  8. " + urlsAll;
  9. log.info("shiro ini urls --->
  10. " + iniUrls);
  11. // Ini ini = new Ini();
  12. // ini.load(iniUrls);
  13. // Ini.Section section = ini.getSection(Ini.DEFAULT_SECTION_NAME);
  14. // Log.info(section.toString());
  15. // 注意这个代码中这里load过一次了
  16. ini.load(iniUrls);
  17. // 此处验证了 ini并没有全被覆盖,只覆盖了 加载的配置文件部分
  18. // 如果新加载的内容中 只有 [main] 标签不会被覆盖,但是如果 [main]标签下有内容 则会覆盖之前的配置
  19. // for (Entry entry : ini.entrySet()) {
  20. // jline.internal.Log.info(entry.getKey());
  21. // for (Entry entryStr : entry.getValue().entrySet()) {
  22. // jline.internal.Log.info(entryStr);
  23. // }
  24. // }
  25. return true;
  26. }
  27. return false;
  28. }
  29. private String readConfig(String confPath) {
  30. String urls1 = "";
  31. try {
  32. String path = conf.get(confPath, "").trim();
  33. log.info("path:" + path);
  34. if (path != null && appContext.getResourceLoader().has(path)) {
  35. InputStream is = ResourceUtils.getInputStreamForPath("classpath:" + path);
  36. if (is != null) {
  37. urls1 = readIniFile(is);
  38. }
  39. }
  40. } catch (FileNotFoundException e) {
  41. e.printStackTrace();
  42. } catch (IOException e) {
  43. e.printStackTrace();
  44. }
  45. return urls1;
  46. }
  47. private String readIniFile(InputStream is) throws IOException {
  48. // InputStreamReader reader =new InputStreamReader(new
  49. // FileInputStream(file),"UTF-8");
  50. InputStreamReader reader = new InputStreamReader(is);
  51. BufferedReader br = new BufferedReader(reader);
  52. StringBuffer sbf = new StringBuffer();
  53. while (true) {
  54. String str = br.readLine();
  55. if (str != null) {
  56. sbf.append(str).append("
  57. ");
  58. } else {
  59. break;
  60. }
  61. }
  62. br.close();
  63. reader.close();
  64. return sbf.toString();
  65. }

 当然代码中依旧有可以优化的地方,不过这里就先不写了,嘿嘿

 不过至此已经达到能想到的最好的效果了,父子项目中 父项目配置 shiro main中验证和DB,Redis的大部分通用配置,以及所有通用的urls过滤,而子类可以添加新的urls配置,并且各个子项目中 shiro配置并不冲突.

 至此整偏博客结束,如果其中有错误也请大家告诉我了~~

 下面是源码部分,不看可以跳过了!~

四.源码部分

 starter源码部分

 不包括starter中未修改的类

 ShiroEnvStarter.java

</>复制代码

  1. //添加常量
  2. @PropDoc(value = "urls过滤清单ini文件1路径")
  3. public static final String PROP_INIT_URLS_PATH1 = "shiro.ini.urls.path1";
  4. @PropDoc(value = "urls过滤清单ini文件2路径")
  5. public static final String PROP_INIT_URLS_PATH2 = "shiro.ini.urls.path2";

 NbShiroEnvironmentLoaderListener.java

</>复制代码

  1. //修改
  2. import java.io.IOException;
  3. import javax.servlet.ServletContext;
  4. import javax.servlet.ServletContextEvent;
  5. import org.apache.shiro.ShiroException;
  6. import org.apache.shiro.config.ConfigurationException;
  7. import org.apache.shiro.util.ClassUtils;
  8. import org.apache.shiro.util.UnknownClassException;
  9. import org.apache.shiro.web.env.EnvironmentLoader;
  10. import org.apache.shiro.web.env.EnvironmentLoaderListener;
  11. import org.apache.shiro.web.env.IniWebEnvironment;
  12. import org.nutz.boot.AppContext;
  13. import org.nutz.ioc.impl.PropertiesProxy;
  14. import org.nutz.lang.Lang;
  15. import org.slf4j.Logger;
  16. import org.slf4j.LoggerFactory;
  17. import jline.internal.Log;
  18. public class NbShiroEnvironmentLoaderListener extends EnvironmentLoaderListener {
  19. private static final Logger log = LoggerFactory.getLogger(NbShiroEnvironmentLoaderListener.class);
  20. protected PropertiesProxy conf;
  21. protected AppContext appContext;
  22. @Override
  23. public void contextInitialized(ServletContextEvent sce) {
  24. PropertiesProxy conf = appContext.getConfigureLoader().get();
  25. try {
  26. boolean hasUrlsPath = hasIniUrlsPath(conf, appContext);
  27. // 走原生API的shiro.ini文件吗?
  28. String iniPath = conf.get("shiro.ini.path", "shiro.ini");
  29. boolean hasIniPath = conf.has("shiro.ini.path") || appContext.getResourceLoader().has(iniPath);
  30. if (hasIniPath || (hasIniPath && hasUrlsPath)) {
  31. sce.getServletContext().setAttribute(EnvironmentLoader.CONFIG_LOCATIONS_PARAM, iniPath);
  32. super.contextInitialized(sce);
  33. return;
  34. }
  35. } catch (Exception e) {
  36. throw Lang.wrapThrow(e);
  37. }
  38. // 没有配置文件 走nb(默认)配置
  39. sce.getServletContext().setAttribute(ENVIRONMENT_CLASS_PARAM, NbResourceBasedWebEnvironment.class.getName());
  40. super.contextInitialized(sce);
  41. }
  42. protected Class determineWebEnvironmentClass(ServletContext servletContext) {
  43. // nb 默认配置
  44. String className = servletContext.getInitParameter(ENVIRONMENT_CLASS_PARAM);
  45. if (className != null) {
  46. try {
  47. return ClassUtils.forName(className);
  48. } catch (UnknownClassException ex) {
  49. throw new ConfigurationException("Failed to load custom WebEnvironment class [" + className + "]", ex);
  50. }
  51. } else {
  52. try {
  53. boolean hasUrlsPath = hasIniUrlsPath(conf, appContext);
  54. // 如果有配置文件
  55. String iniPath = conf.get("shiro.ini.path", "shiro.ini");
  56. boolean hasIniPath = conf.has("shiro.ini.path") || appContext.getResourceLoader().has(iniPath);
  57. if (hasIniPath && hasUrlsPath) {
  58. return IniMixWebEnvironment.class;
  59. } else if (hasIniPath) {
  60. return IniWebEnvironment.class;
  61. }
  62. } catch (IOException e) {
  63. throw new ShiroException(e);
  64. }
  65. return NbResourceBasedWebEnvironment.class;
  66. }
  67. }
  68. private boolean hasIniUrlsPath(PropertiesProxy conf, AppContext appContext) throws IOException {
  69. String iniUrlsPath1 = conf.get(ShiroEnvStarter.PROP_INIT_URLS_PATH1, null);
  70. boolean hasIniUrlsPath1 = false;
  71. if (iniUrlsPath1 != null) {
  72. hasIniUrlsPath1 = (conf.has(ShiroEnvStarter.PROP_INIT_URLS_PATH1)
  73. || appContext.getResourceLoader().has(iniUrlsPath1));
  74. }
  75. String iniUrlsPath2 = conf.get(ShiroEnvStarter.PROP_INIT_URLS_PATH2, null);
  76. boolean hasIniUrlsPath2 = false;
  77. if (iniUrlsPath2 != null) {
  78. hasIniUrlsPath2 = (conf.has(ShiroEnvStarter.PROP_INIT_URLS_PATH2)
  79. || appContext.getResourceLoader().has(iniUrlsPath2));
  80. }
  81. if (hasIniUrlsPath1 || hasIniUrlsPath2) {
  82. return true;
  83. }
  84. return false;
  85. }
  86. }

基于 shiro原生实现的实现类

</>复制代码

  1. import java.io.BufferedReader;
  2. import java.io.FileNotFoundException;
  3. import java.io.IOException;
  4. import java.io.InputStream;
  5. import java.io.InputStreamReader;
  6. import java.util.Map;
  7. import javax.servlet.ServletContext;
  8. import org.apache.shiro.config.ConfigurationException;
  9. import org.apache.shiro.config.Ini;
  10. import org.apache.shiro.config.IniFactorySupport;
  11. import org.apache.shiro.io.ResourceUtils;
  12. import org.apache.shiro.util.CollectionUtils;
  13. import org.apache.shiro.util.Destroyable;
  14. import org.apache.shiro.util.Initializable;
  15. import org.apache.shiro.util.StringUtils;
  16. import org.apache.shiro.web.config.IniFilterChainResolverFactory;
  17. import org.apache.shiro.web.config.WebIniSecurityManagerFactory;
  18. import org.apache.shiro.web.env.IniWebEnvironment;
  19. import org.apache.shiro.web.env.ResourceBasedWebEnvironment;
  20. import org.apache.shiro.web.env.WebEnvironment;
  21. import org.apache.shiro.web.filter.mgt.FilterChainResolver;
  22. import org.apache.shiro.web.mgt.WebSecurityManager;
  23. import org.apache.shiro.web.util.WebUtils;
  24. import org.nutz.boot.AppContext;
  25. import org.nutz.ioc.Ioc;
  26. import org.nutz.ioc.impl.PropertiesProxy;
  27. import org.slf4j.Logger;
  28. import org.slf4j.LoggerFactory;
  29. /**
  30. * {@link WebEnvironment} implementation configured by an {@link Ini} instance
  31. * or {@code Ini} resource locations.
  32. *
  33. * 代码主要实现部分由shiro IniWebEnvironment源码抄过来的
  34. * 修改了 createFilterChainResolver 方法,让 ini又load了一个 urls 配置
  35. * 目前从现象看 ini.load 似乎不会覆盖整个配置
  36. *
  37. * @since 1.2
  38. */
  39. public class IniMixWebEnvironment extends ResourceBasedWebEnvironment implements Initializable, Destroyable {
  40. // *********非源码部分**********
  41. protected AppContext appContext;
  42. protected Ioc ioc;
  43. protected PropertiesProxy conf;
  44. // ****************************
  45. public static final String DEFAULT_WEB_INI_RESOURCE_PATH = "/WEB-INF/shiro.ini";
  46. private static final Logger log = LoggerFactory.getLogger(IniWebEnvironment.class);
  47. /**
  48. * The Ini that configures this WebEnvironment instance.
  49. */
  50. private Ini ini;
  51. /**
  52. * Initializes this instance by resolving any potential (explicit or
  53. * resource-configured) {@link Ini} configuration and calling
  54. * {@link #configure() configure} for actual instance configuration.
  55. */
  56. public void init() {
  57. // *********非源码部分**********
  58. appContext = AppContext.getDefault();
  59. ioc = appContext.getIoc();
  60. conf = appContext.getConfigureLoader().get();
  61. // ****************************
  62. Ini ini = getIni();
  63. String[] configLocations = getConfigLocations();
  64. if (log.isWarnEnabled() && !CollectionUtils.isEmpty(ini) && configLocations != null
  65. && configLocations.length > 0) {
  66. log.warn("Explicit INI instance has been provided, but configuration locations have also been "
  67. + "specified. The {} implementation does not currently support multiple Ini config, but this may "
  68. + "be supported in the future. Only the INI instance will be used for configuration.",
  69. IniWebEnvironment.class.getName());
  70. }
  71. if (CollectionUtils.isEmpty(ini)) {
  72. log.debug("Checking any specified config locations.");
  73. ini = getSpecifiedIni(configLocations);
  74. }
  75. if (CollectionUtils.isEmpty(ini)) {
  76. log.debug("No INI instance or config locations specified. Trying default config locations.");
  77. ini = getDefaultIni();
  78. }
  79. if (CollectionUtils.isEmpty(ini)) {
  80. String msg = "Shiro INI configuration was either not found or discovered to be empty/unconfigured.";
  81. throw new ConfigurationException(msg);
  82. }
  83. setIni(ini);
  84. configure();
  85. }
  86. protected void configure() {
  87. this.objects.clear();
  88. WebSecurityManager securityManager = createWebSecurityManager();
  89. setWebSecurityManager(securityManager);
  90. FilterChainResolver resolver = createFilterChainResolver();
  91. if (resolver != null) {
  92. setFilterChainResolver(resolver);
  93. }
  94. }
  95. protected Ini getSpecifiedIni(String[] configLocations) throws ConfigurationException {
  96. Ini ini = null;
  97. if (configLocations != null && configLocations.length > 0) {
  98. if (configLocations.length > 1) {
  99. log.warn(
  100. "More than one Shiro .ini config location has been specified. Only the first will be "
  101. + "used for configuration as the {} implementation does not currently support multiple "
  102. + "files. This may be supported in the future however.",
  103. IniWebEnvironment.class.getName());
  104. }
  105. // required, as it is user specified:
  106. ini = createIni(configLocations[0], true);
  107. }
  108. return ini;
  109. }
  110. protected Ini getDefaultIni() {
  111. Ini ini = null;
  112. String[] configLocations = getDefaultConfigLocations();
  113. if (configLocations != null) {
  114. for (String location : configLocations) {
  115. ini = createIni(location, false);
  116. if (!CollectionUtils.isEmpty(ini)) {
  117. log.debug("Discovered non-empty INI configuration at location "{}". Using for configuration.",
  118. location);
  119. break;
  120. }
  121. }
  122. }
  123. return ini;
  124. }
  125. /**
  126. * Creates an {@link Ini} instance reflecting the specified path, or
  127. * {@code null} if the path does not exist and is not required.
  128. *

  129. * If the path is required and does not exist or is empty, a
  130. * {@link ConfigurationException} will be thrown.
  131. *
  132. * @param configLocation the resource path to load into an {@code Ini} instance.
  133. * @param required if the path must exist and be converted to a non-empty
  134. * {@link Ini} instance.
  135. * @return an {@link Ini} instance reflecting the specified path, or
  136. * {@code null} if the path does not exist and is not required.
  137. * @throws ConfigurationException if the path is required but results in a null
  138. * or empty Ini instance.
  139. */
  140. protected Ini createIni(String configLocation, boolean required) throws ConfigurationException {
  141. Ini ini = null;
  142. if (configLocation != null) {
  143. ini = convertPathToIni(configLocation, required);
  144. }
  145. if (required && CollectionUtils.isEmpty(ini)) {
  146. String msg = "Required configuration location "" + configLocation + "" does not exist or did not "
  147. + "contain any INI configuration.";
  148. throw new ConfigurationException(msg);
  149. }
  150. return ini;
  151. }
  152. protected FilterChainResolver createFilterChainResolver() {
  153. FilterChainResolver resolver = null;
  154. Ini ini = getIni();
  155. if (!CollectionUtils.isEmpty(ini)) {
  156. // only create a resolver if the "filters" or "urls" sections are defined:
  157. // Ini.Section urls = ini.getSection(IniFilterChainResolverFactory.URLS);
  158. // Ini.Section filters = ini.getSection(IniFilterChainResolverFactory.FILTERS);
  159. // *********非源码部分**********
  160. // boolean loadUrls = loadIniUrls(ini);
  161. boolean loadUrls = loadIniPath1ANd2(ini);
  162. if (loadUrls) {
  163. // ****************************
  164. // if (!CollectionUtils.isEmpty(urls) || !CollectionUtils.isEmpty(filters)) {
  165. // either the urls section or the filters section was defined. Go ahead and create the resolver:
  166. IniFilterChainResolverFactory factory = new IniFilterChainResolverFactory(ini, this.objects);
  167. resolver = factory.getInstance();
  168. }
  169. }
  170. return resolver;
  171. }
  172. // *********非源码部分**********
  173. private boolean loadIniPath1ANd2(Ini ini) {
  174. String urlsAll = "";
  175. String urls1 = readConfig(ShiroEnvStarter.PROP_INIT_URLS_PATH1);
  176. String urls2 = readConfig(ShiroEnvStarter.PROP_INIT_URLS_PATH2);
  177. urlsAll = urls1 + urls2;
  178. if (!urlsAll.equals("")) {
  179. String iniUrls = "[urls]
  180. " + urlsAll;
  181. log.info("shiro ini urls --->
  182. " + iniUrls);
  183. // Ini ini = new Ini();
  184. // ini.load(iniUrls);
  185. // Ini.Section section = ini.getSection(Ini.DEFAULT_SECTION_NAME);
  186. // Log.info(section.toString());
  187. ini.load(iniUrls);
  188. // 此处验证了 ini并没有全被覆盖,只覆盖了 加载的配置文件部分
  189. // 如果新加载的内容中 只有 [main] 标签不会被覆盖,但是如果 [main]标签下有内容 则会覆盖之前的配置
  190. // for (Entry entry : ini.entrySet()) {
  191. // jline.internal.Log.info(entry.getKey());
  192. // for (Entry entryStr : entry.getValue().entrySet()) {
  193. // jline.internal.Log.info(entryStr);
  194. // }
  195. // }
  196. return true;
  197. }
  198. return false;
  199. }
  200. private String readConfig(String confPath) {
  201. String urls1 = "";
  202. try {
  203. String path = conf.get(confPath, "").trim();
  204. log.info("path:" + path);
  205. if (path != null && appContext.getResourceLoader().has(path)) {
  206. InputStream is = ResourceUtils.getInputStreamForPath("classpath:" + path);
  207. if (is != null) {
  208. urls1 = readIniFile(is);
  209. }
  210. }
  211. } catch (FileNotFoundException e) {
  212. e.printStackTrace();
  213. } catch (IOException e) {
  214. e.printStackTrace();
  215. }
  216. return urls1;
  217. }
  218. private String readIniFile(InputStream is) throws IOException {
  219. // InputStreamReader reader =new InputStreamReader(new
  220. // FileInputStream(file),"UTF-8");
  221. InputStreamReader reader = new InputStreamReader(is);
  222. BufferedReader br = new BufferedReader(reader);
  223. StringBuffer sbf = new StringBuffer();
  224. while (true) {
  225. String str = br.readLine();
  226. if (str != null) {
  227. sbf.append(str).append("
  228. ");
  229. } else {
  230. break;
  231. }
  232. }
  233. br.close();
  234. reader.close();
  235. return sbf.toString();
  236. }
  237. private boolean loadIniUrls(Ini ini) {
  238. // 使用了 原 start中定义的 shiro.ini.urls
  239. String config = conf.get(ShiroEnvStarter.PROP_INIT_URLS, "").trim();
  240. if (config != null && !config.equals("")) {
  241. String iniUrls = "[urls]
  242. " + config;
  243. log.info("shiro ini urls --->
  244. " + iniUrls);
  245. // Ini ini = new Ini();
  246. // ini.load(iniUrls);
  247. // Ini.Section section = ini.getSection(Ini.DEFAULT_SECTION_NAME);
  248. // Log.info(section.toString());
  249. ini.load(iniUrls);
  250. return true;
  251. }
  252. return false;
  253. }
  254. // ****************************
  255. protected WebSecurityManager createWebSecurityManager() {
  256. WebIniSecurityManagerFactory factory;
  257. Ini ini = getIni();
  258. if (CollectionUtils.isEmpty(ini)) {
  259. factory = new WebIniSecurityManagerFactory();
  260. } else {
  261. factory = new WebIniSecurityManagerFactory(ini);
  262. }
  263. WebSecurityManager wsm = (WebSecurityManager) factory.getInstance();
  264. // SHIRO-306 - get beans after they"ve been created (the call was before the
  265. // factory.getInstance() call,
  266. // which always returned null.
  267. Map beans = factory.getBeans();
  268. if (!CollectionUtils.isEmpty(beans)) {
  269. this.objects.putAll(beans);
  270. }
  271. return wsm;
  272. }
  273. /**
  274. * Returns an array with two elements, {@code /WEB-INF/shiro.ini} and
  275. * {@code classpath:shiro.ini}.
  276. *
  277. * @return an array with two elements, {@code /WEB-INF/shiro.ini} and
  278. * {@code classpath:shiro.ini}.
  279. */
  280. protected String[] getDefaultConfigLocations() {
  281. return new String[] { DEFAULT_WEB_INI_RESOURCE_PATH, IniFactorySupport.DEFAULT_INI_RESOURCE_PATH };
  282. }
  283. /**
  284. * Converts the specified file path to an {@link Ini} instance.
  285. *

  286. * If the path does not have a resource prefix as defined by
  287. * {@link org.apache.shiro.io.ResourceUtils#hasResourcePrefix(String)}, the path
  288. * is expected to be resolvable by the {@code ServletContext} via
  289. * {@link javax.servlet.ServletContext#getResourceAsStream(String)}.
  290. *
  291. * @param path the path of the INI resource to load into an INI instance.
  292. * @param required if the specified path must exist
  293. * @return an INI instance populated based on the given INI resource path.
  294. */
  295. private Ini convertPathToIni(String path, boolean required) {
  296. // TODO - this logic is ugly - it"d be ideal if we had a Resource API to
  297. // polymorphically encaspulate this behavior
  298. Ini ini = null;
  299. if (StringUtils.hasText(path)) {
  300. InputStream is = null;
  301. // SHIRO-178: Check for servlet context resource and not only resource paths:
  302. if (!ResourceUtils.hasResourcePrefix(path)) {
  303. is = getServletContextResourceStream(path);
  304. } else {
  305. try {
  306. is = ResourceUtils.getInputStreamForPath(path);
  307. } catch (IOException e) {
  308. if (required) {
  309. throw new ConfigurationException(e);
  310. } else {
  311. if (log.isDebugEnabled()) {
  312. log.debug("Unable to load optional path "" + path + "".", e);
  313. }
  314. }
  315. }
  316. }
  317. if (is != null) {
  318. ini = new Ini();
  319. ini.load(is);
  320. } else {
  321. if (required) {
  322. throw new ConfigurationException("Unable to load resource path "" + path + """);
  323. }
  324. }
  325. }
  326. return ini;
  327. }
  328. // TODO - this logic is ugly - it"d be ideal if we had a Resource API to
  329. // polymorphically encaspulate this behavior
  330. private InputStream getServletContextResourceStream(String path) {
  331. InputStream is = null;
  332. path = WebUtils.normalize(path);
  333. ServletContext sc = getServletContext();
  334. if (sc != null) {
  335. is = sc.getResourceAsStream(path);
  336. }
  337. return is;
  338. }
  339. /**
  340. * Returns the {@code Ini} instance reflecting this WebEnvironment"s
  341. * configuration.
  342. *
  343. * @return the {@code Ini} instance reflecting this WebEnvironment"s
  344. * configuration.
  345. */
  346. public Ini getIni() {
  347. return this.ini;
  348. }
  349. /**
  350. * Allows for configuration via a direct {@link Ini} instance instead of via
  351. * {@link #getConfigLocations() config locations}.
  352. *

  353. * If the specified instance is null or empty, the fallback/default
  354. * resource-based configuration will be used.
  355. *
  356. * @param ini the ini instance to use for creation.
  357. */
  358. public void setIni(Ini ini) {
  359. this.ini = ini;
  360. }
  361. }

如果以后想到什么再补充吧

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/76484.html

相关文章

  • Apache Shiro 简介

    摘要:的很容易反映出常见的工作流程。权限检查是执行授权的另一种方式。在安全框架领域提供了一些独特的东西一致的会话,可用于任何应用程序和任何架构层。 Apache Shiro™是一个功能强大且易于使用的Java安全框架,可执行身份验证,授权,加密和会话管理。借助Shiro易于理解的API,可以快速轻松地保护任何应用程序 - 从最小的移动应用程序到最大的Web和企业应用程序。 1. Apache S...

    econi 评论0 收藏0
  • Shiro入门这篇就够了【Shiro的基础知识、回顾URL拦截】

    摘要:细粒度权限管理就是数据级别的权限管理。张三只能查看行政部的用户信息,李四只能查看开发部门的用户信息。比如通过的拦截器实现授权。 前言 本文主要讲解的知识点有以下: 权限管理的基础知识 模型 粗粒度和细粒度的概念 回顾URL拦截的实现 Shiro的介绍与简单入门 一、Shiro基础知识 在学习Shiro这个框架之前,首先我们要先了解Shiro需要的基础知识:权限管理 1.1什...

    chenjiang3 评论0 收藏0
  • Shiro【授权、整合Spirng、Shiro过滤器】

    摘要:表示对用户资源进行操作,相当于,对所有用户资源实例进行操作。与整合,实际上的操作都是通过过滤器来干的。将安全管理器交由工厂来进行管理。在过滤器链中设置静态资源不拦截。 前言 本文主要讲解的知识点有以下: Shiro授权的方式简单介绍 与Spring整合 初始Shiro过滤器 一、Shiro授权 上一篇我们已经讲解了Shiro的认证相关的知识了,现在我们来弄Shiro的授权 Shir...

    ralap 评论0 收藏0
  • Shiro实战(一) Shiro核心概念

    摘要:是什么是功能强大简单易用的安全框架,核心功能包括认证授权加密以及管理。的主要作用就是用来执行认证和授权的逻辑,它其实就相当于与安全数据用户账号密码角色权限之间进行交互的桥梁。至此,的三个核心概念已经介绍完毕。 1、Shiro是什么 Shiro是功能强大、简单易用的Java安全框架,核心功能包括:认证、授权、加密以及Session管理。Shiro的应用范围很广泛,小型移动端应用、大型We...

    mdluo 评论0 收藏0
  • 深入理解 Webpack 打包分块(上)

    摘要:而一个哈希字符串就是根据文件内容产生的签名,每当文件内容发生更改时,哈希串也就发生了更改,文件名也就随之更改。很显然这不是我们需要的,如果文件内容发生了更改,的打包文件的哈希应该发生变化,但是不应该。前言 随着前端代码需要处理的业务越来越繁重,我们不得不面临的一个问题是前端的代码体积也变得越来越庞大。这造成无论是在调式还是在上线时都需要花长时间等待编译完成,并且用户也不得不花额外的时间和带宽...

    Rocko 评论0 收藏0

发表评论

0条评论

eternalshallow

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<