我开始使用Guice / Shiro而不是Spring / Spring Security。我查看了Shiro站点的示例,所有配置示例都是作为INI文件示例制作的。是否可以在普通Java中配置Shiro,因为要配置Guice Servlet?
答案 0 :(得分:14)
是的,但是如果你想让Guice创建你的领域,需要一些胶水代码。
bind(Realm.class).to(MyRealm.class).in(Singleton.class);
@Provides @Singleton WebSecurityManager securityManager(Realm realm) {
DefaultWebSecurityManager sm = new DefaultWebSecurityManager();
sm.setRealm(realm);
return sm;
}
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();
}
}
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);