4

Jersey で REST API を開発しており、依存性注入に Google Guice を使用し、セキュリティ フレームワークとして Apache Shiro を使用したいと考えています。

認証のために、EntityManagerに接続されているカスタムAuthenticatorを注入する必要があるカスタムRealmを作成しました。

ただし、依存関係はレルムに注入されません。shiro.ini (使用される領域を定義する必要があります) は、guice によって管理されていないと思います。

依存関係を Apache Shiro、特に使用されている Realm に注入するにはどうすればよいですか?

私の 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);
        }
    });
}
}

白鬼は領域のみを定義する

[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 フレームワークを最大限に活用できる場合は、通常、すべての Shiro を IoC メカニズム内で直接構成することをお勧めします。Shiro の Spring 統合は、この良い例です: http://shiro.apache.org/spring.html Guice 環境でもほぼ同じことを行うことをお勧めします。

これを行いたくなく、むしろ INI を使用したい場合、Shiro には RealmFactory の概念があります。

Guice 環境と通信し、Guice で構成された Realm を「プル」する RealmFactory 実装を作成できます。次に、Shiro INI で RealmFactory 実装を定義します。

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

ただし、Shiro の INI は、RealmFactory を介して INI の外部から Realm インスタンスを取得することしかサポートしていないことに注意してください。他のすべての参照オブジェクトは、INI で定義する必要があります。Shiro Jira の問題を開いて、レルムだけでなく、より一般的な Factory サポートを依頼することもできます。

最終的に、Guice は INI よりも強力であるため、可能であれば Shiro のすべてを Guice で構成することをお勧めします (SecurityManager、レルム、ShiroFilter など)。

于 2011-01-31T21:07:50.303 に答える