2011-05-04 92 views
8

我開始使用Guice/Shiro代替Spring/Spring Security。我查看了Shiro站點的示例,並且所有配置示例都以INI文件示例形式提供。是否可以用簡單的Java配置Shiro,因爲Guice Servlet是要配置的?用Google Guice Servlet配置Apache Shiro

回答

14

是的,這是可能的,但如果你想讓Guice創建你的領域需要一些膠水代碼。

  1. 綁定境界的實現:
bind(Realm.class).to(MyRealm.class).in(Singleton.class); 
  1. 綁定WebSecurityManager:
@Provides @Singleton WebSecurityManager securityManager(Realm realm) { 
     DefaultWebSecurityManager sm = new DefaultWebSecurityManager(); 
     sm.setRealm(realm); 
     return sm; 
    } 
  1. 子類四郎過濾器之一,所以你可以使用吉斯提供WebSecurityManager:
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. 配置您的過濾器:
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); 
+0

thanx的答案全碼!所以最終配置必須以ini格式呢? – newbie 2011-05-06 06:02:25

+0

Ini是可選的,您可以手動配置提供者方法中的WebSecuirtyManager。 – sanjary 2011-05-06 07:00:00