本文介绍了使用Google Guice Servlet配置Apache Shiro的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开始使用Guice/Shiro代替Spring/Spring Security.我从Shiro站点看过示例,所有配置示例都是INI文件示例.可以使用Guice Servlet配置纯Java中的Shiro吗?

I'm starting to use Guice/Shiro instead of Spring/Spring Security. I have looked examples from Shiro site, and all configuration examples are made as INI-file examples. Is it possible to configure Shiro in plain Java, as Guice Servlets are meant to be configured?

推荐答案

是可以的,但是如果您想让Guice创建领域,则需要一些粘合代码.

Yes it is possible, but requires some glue code if you want Guice to create your Realms.

  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. 子类化Shiro过滤器之一,因此您可以使用Guice提供的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);

这篇关于使用Google Guice Servlet配置Apache Shiro的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-24 14:01