使用Google Guice Servlet配置Apache Shiro

时间:2011-05-04 17:45:29

标签: guice shiro guice-servlet

我开始使用Guice / Shiro而不是Spring / Spring Security。我查看了Shiro站点的示例,所有配置示例都是作为INI文件示例制作的。是否可以在普通Java中配置Shiro,因为要配置Guice Servlet?

1 个答案:

答案 0 :(得分:14)

是的,但是如果你想让Guice创建你的领域,需要一些胶水代码。

  1. Bind Realm实施:
  2.     bind(Realm.class).to(MyRealm.class).in(Singleton.class);
    
    1. 绑定WebSecurityManager:
    2.     @Provides @Singleton WebSecurityManager securityManager(Realm realm) {
            DefaultWebSecurityManager sm = new DefaultWebSecurityManager();
            sm.setRealm(realm);
            return sm;
          }
      
      1. Shiro过滤器的一个子类,因此您可以使用Guice提供的WebSecurityManager:
      2.     public class SecurityFilter extends IniShiroFilter {
        
              static class SecurityManagerFactory extends WebIniSecurityManagerFactory {
        
                private final WebSecurityManager securityManager;
        
                public SecurityManagerFactory(WebSecurityManager securityManager) {
                  this.securityManager = securityManager;
                }
        
                public SecurityManagerFactory(WebSecurityManager securityManager, Ini ini) {
                  super(ini);
                  this.securityManager = securityManager;
                }
        
                @Override
                protected SecurityManager createDefaultInstance() {
                  return securityManager;
                }
              }
        
              private final Provider<WebSecurityManager> securityManager;
        
              @Inject
              SecurityFilter(Provider<WebSecurityManager> securityManager) {
                super();
                this.securityManager = securityManager;
              }
        
        
              protected Map<String, ?> applySecurityManager(Ini ini) {
                SecurityManagerFactory factory;
                if (ini == null || ini.isEmpty()) {
                  factory = new SecurityManagerFactory(securityManager.get());
                } else {
                  factory = new SecurityManagerFactory(securityManager.get(), ini);
                }
                setSecurityManager((WebSecurityManager) factory.getInstance());
                return factory.getBeans();
              }
            }
        
        1. 配置过滤器:
        2.     Joiner lines = Joiner.on("\n");
              Map<String, String> config = ImmutableMap.of("config", lines.join(
                  "; here you can provide additional ini",
                  "[roles]",
                  "admin = *",
                  "[urls]",
                  "/secure/** = authcBasic"
              ));
              filter("/*").through(SecurityFilter.class, config);