4

我用 Jersey 开发了一个 rest api,并想使用 Google Guice 进行依赖注入和 Apache Shiro 作为安全框架。

对于身份验证,我创建了一个自定义领域,我必须向其中注入一个连接到 EntityManager 的自定义身份验证器。

但是,依赖项不会注入到领域中。我猜想 shiro.ini (我必须在其中定义使用的领域)不是由 guice 管理的。

如何将依赖项注入 Apache Shiro,尤其是使用的领域?

我的 web.xml 只有一个映射到 guice 的过滤器

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<filter>
    <filter-name>guiceFilter</filter-name>
    <filter-class>com.google.inject.servlet.GuiceFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>guiceFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

<listener>
    <listener-class>GuiceServletConfig</listener-class>
</listener>
</web-app>

我的 GuiceServletConfig 配置所有依赖项,包括 CustomRealm

public class GuiceServletConfig extends GuiceServletContextListener {

@Override
protected Injector getInjector() {
    return Guice.createInjector(new DbModule(), new JerseyServletModule() {

        @Override
        protected void configureServlets() {
            // ...
            // CustomRealm is only used when i use it as an eager singleton
            bind(CustomRealm.class).asEagerSingleton();
            bind(org.apache.shiro.web.servlet.IniShiroFilter.class).in(Singleton.class);
            filter("/*").through(org.apache.shiro.web.servlet.IniShiroFilter.class);
            serve("/api/*").with(GuiceContainer.class);
        }
    });
}
}

shiro ini 只定义领域

[main]
myRealm = CustomRealm
[users] # for testing
root = secret,admin
[roles] # for testing
admin = *
[urls]
/api/** = authcBasic
4

1 回答 1

5

Apache Shiro 的 INI 配置非常适合许多用例,但如果您拥有像 Spring 或 Guice 这样的 IoC 框架的全部功能,通常最好直接在 IoC 机制中配置所有 Shiro。Shiro 的 Spring 集成就是一个很好的例子:http ://shiro.apache.org/spring.html 建议对 Guice 环境做一些几乎相同的事情。

如果您不想这样做而宁愿继续使用 INI,Shiro 有一个 RealmFactory 概念。

你可以创建一个 RealmFactory 实现,它与你的 Guice 环境通信并“拉”你的 Guice 配置的领域。然后你在 Shiro INI 中定义你的 RealmFactory 实现:

[main]
...
guiceRealmFactory = com.foo.bar.shiro.GuiceRealmFactory
...

但是请注意,Shiro 的 INI 仅支持通过 RealmFactory 从 INI 外部获取 Realm 实例 - 所有其他引用的对象都必须在 INI 中定义。您可能想打开 Shiro Jira 问题,以寻求更一般的 Factory 支持,而不仅仅是领域。

归根结底,因为 Guice 比 INI 更强大,所以建议尽可能在 Guice 中配置 Shiro 中的所有内容(SecurityManager、realms、ShiroFilter 等)

于 2011-01-31T21:07:50.303 回答