【问题标题】:Configuring Shiro with Guice without a ServletContext在没有 ServletContext 的情况下使用 Guice 配置 Shiro
【发布时间】:2012-11-18 12:12:40
【问题描述】:

我正在使用 Guice 连接 Jetty 服务器,我想通过 Apache Shiro 添加一些安全性。

似乎 Shiro 需要配置 ServletContext,但问题是我在配置时没有 ServletContext(例如在 ServletModule 作为文档状态)。 ServletContextGuiceServletContextListener 中可用,但是此时,我的注入器已经创建,所以安装 Shiro 模块为时已晚。

我尝试通过 Guice 提供程序将 ServletContext 提供给 Shiro,(Provider)但仍然没有成功。我认为这个提供者将在创建后为 ServletContext 提供服务。这也给出了一个警告:

"com.google.inject.servlet.InternalServletModule$BackwardsCompatibleServletContextProvider get
WARNING: You are attempting to use a deprecated API (specifically, attempting to @Inject ServletContext inside an eagerly created singleton. While we allow this for backwards compatibility, be warned that this MAY have unexpected behavior if you have more than one injector (with ServletModule) running in the same JVM."

在注入器创建后如何安装 Shiro Web 模块?

【问题讨论】:

    标签: java apache jetty guice shiro


    【解决方案1】:

    获取 ServletContext 的标准方法是扩展 GuiceServletContextListener

    恕我直言,这是对 API 的重大疏忽。

    http://code.google.com/p/google-guice/issues/detail?id=603

    这里也有教程:

    https://issues.apache.org/jira/browse/SHIRO-320

    (编辑:阅读 cmets 后) 你有两个选择:

    1. 重构代码只在GuiceServletContextListener中创建注入器
    2. 使用儿童注射器(棘手)

    对于子注入器,只有子注入器创建的实例才会获得“Shiroed”。请记住:为子注入器创建的即时绑定将尽可能在祖先注入器中创建。

    您的 Servlet 和过滤器将按预期工作,但如果您在已创建的 Injector 中有业务逻辑,他们将看不到 Shiro。您可以通过多种方式解决此问题...

    【讨论】:

    • 在我的例子中,在 GuiceServletContextListener 中初始化 ServletContext 时,已经创建了注入器。
    • 在 Guice 中,WebGuiceEnvironment 中需要 ServletContext。我尝试在注入器创建后修改 WebGuiceEnvironment 并设置 ServletContext,但它似乎也不是这样工作的。请求被阻止,但我的 Realm 没有被要求授权(这意味着每次都被阻止)
    • 你能在现有的 Injector 中添加一个模块吗?你是如何创建它的?
    • 注入器创建是应用程序做的第一件事。这就是为什么我说在 GuiceServletContextListener 中创建注入器为时已晚。创建注入器后,据我所知,无法添加其他模块(除非使用子注入器 - 已经尝试过,在这种情况下不起作用)
    • 我会在您的 Application Injector 中添加常规 ShiroModule,然后添加 WebShiroModule(已修改以删除 ShiroModule 中已包含的绑定)。这应该涵盖所有角度。
    【解决方案2】:

    遇到了同样的问题,使用来自@Mircea 的信息,我所做的只是将 GuiceServletContextLister 转换为 ServletContext

    Guice.createInjector(new ShiroWebModule((ServletContext)this);

    希望这会有所帮助

    【讨论】:

      猜你喜欢
      • 2011-04-18
      • 2011-08-18
      • 1970-01-01
      • 2023-03-08
      • 2017-12-02
      • 1970-01-01
      • 2011-09-13
      • 2019-10-31
      • 1970-01-01
      相关资源
      最近更新 更多