Shiro
  1. Shiro
  2. SHIRO-23

Integrating Jsecurity with Guice

    Details

    • Type: New Feature New Feature
    • Status: Closed
    • Priority: Minor Minor
    • Resolution: Fixed
    • Affects Version/s: None
    • Fix Version/s: 1.2.0
    • Component/s: None
    • Labels:
      None

      Description

      /*

      • Licensed to the Apache Software Foundation (ASF) under one
      • or more contributor license agreements. See the NOTICE file
      • distributed with this work for additional information
      • regarding copyright ownership. The ASF licenses this file
      • to you under the Apache License, Version 2.0 (the
      • "License"); you may not use this file except in compliance
      • with the License. You may obtain a copy of the License at
        *
      • http://www.apache.org/licenses/LICENSE-2.0
        *
      • Unless required by applicable law or agreed to in writing,
      • software distributed under the License is distributed on an
      • "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
      • KIND, either express or implied. See the License for the
      • specific language governing permissions and limitations
      • under the License.
        */
        package com.akube.framework.jsecurity.filter;

      import com.google.inject.Injector;
      import org.apache.commons.logging.Log;
      import org.apache.commons.logging.LogFactory;
      import org.jsecurity.JSecurityException;
      import org.jsecurity.SecurityUtils;
      import org.jsecurity.mgt.SecurityManager;
      import org.jsecurity.web.config.IniWebConfiguration;

      import java.lang.reflect.InvocationTargetException;
      import java.lang.reflect.Method;
      import java.util.Map;

      /**

      • <p>JSecurity configuration that relies on Guice to define and initialize the JSecurity SecurityManager
      • instance (and all of its dependencies) and makes it avaialble to this filter by performing a Guice injection.
      • The URL/filter behavior is still loaded according to the behavior of the parent class
      • {@link org.jsecurity.web.config.IniWebConfiguration}
      • <p/>
      • <p>
      • The web.xml will need an entry like the following
      • <filter>
        <filter-name>JSecurityFilter</filter-name>
        <filter-class>org.jsecurity.guice.GuiceJSecurityFilter</filter-class>
        <init-param>
        <param-name>config</param-name>
        <param-value>
        </param-value>
        </init-param>
        <init-param>
        <param-name>InjectorFactoryClass</param-name>
        <param-value>app.bootstrap.guice.InjectorFactory</param-value>
        </init-param>
        <init-param>
        <param-name>InjectorFactoryMethod</param-name>
        <param-value>getInjector</param-value>
        </init-param>
        </filter>

      the injector factory class - > injector factory method is called to obtain a guice injector

      • </p>
        *
      • @author Animesh Jain
      • @see IniWebConfiguration
      • @since 0.9
        */
        public class GuiceWebConfiguration extends IniWebConfiguration {

      public static final String INJECTOR_FACTORY_CLASS = "InjectorFactoryClass";
      public static final String INJECTOR_FACTORY_METHOD = "InjectorFactoryMethod";

      private static final Log log = LogFactory.getLog(GuiceWebConfiguration.class);

      protected Injector injector;

      public Injector getInjector()

      { return injector; }

      public void setInjector(Injector injector)

      { this.injector = injector; }

      public GuiceWebConfiguration() {
      }

      @Override
      public void init() throws JSecurityException {
      String className = getFilterConfig().getInitParameter(INJECTOR_FACTORY_CLASS);
      String methodName = getFilterConfig().getInitParameter(INJECTOR_FACTORY_METHOD);
      System.out.println("*************** GuiceWebConfiguration init() ***************");
      System.out.println("injector class = "+className);
      System.out.println("injector method = "+methodName);
      /*
      Get injector from a class which holds an instance for this application. I had a static method in a class that returns the injector.
      I've put the class name and method name in filter init params.
      */
      try

      { Class clazz = Class.forName(className); Method method = clazz.getMethod(methodName); Injector injector = (Injector) method.invoke(null); System.out.println("Injector instantiated = "+injector); setInjector(injector); }

      catch (ClassNotFoundException e)

      { log.error("Injector factory class not found - "+className, e); throw new JSecurityException("Injector factory class not found - "+className, e); }

      catch (NoSuchMethodException e)

      { log.error("Injector factory method not found - "+methodName+" in class "+className, e); throw new JSecurityException("Injector factory method not found - "+methodName+" in class "+className, e); }

      catch (InvocationTargetException e)

      { log.error("InvocationTargetException when trying to invoke - "+methodName+" in class "+className, e); throw new JSecurityException("InvocationTargetException when trying to invoke - "+methodName+" in class "+className, e); }

      catch (IllegalAccessException e)

      { log.error("IllegalAccessException when trying to invoke - "+methodName+" in class "+className, e); throw new JSecurityException("IllegalAccessException when trying to invoke - "+methodName+" in class "+className, e); }

      super.init();
      }

      @Override
      protected SecurityManager createDefaultSecurityManager()

      { return createSecurityManager(null); }

      @Override
      protected SecurityManager createSecurityManager(Map<String, Map<String, String>> sections)

      { return getOrCreateSecurityManager(injector, sections); }

      protected SecurityManager getOrCreateSecurityManager(Injector injector, Map<String, Map<String, String>> sections) {
      System.out.println("Trying to create Security Manager");
      SecurityManager securityManager = null;
      if (injector != null)

      { /* The security manager is obtained using the Guice injector. Typically one will have to use a custom provider and bind it to the DefaultWebSecurityManager class This is the way Guice handles external configuration */ securityManager = injector.getInstance(DefaultWebSecurityManagerProvider.class).get(); SecurityUtils.setSecurityManager(securityManager); }

      else

      { throw new JSecurityException("Injector is null. Cannot instantiate security manager"); }

      return securityManager;
      }

      }

      ----------------------------------------------------------------------------------------------------------------------------

      The filter class can be -

      /**

      • <p>Extension of JSecurityFilter that uses {@link GuiceWebConfiguration}

        to configure the JSecurity instance.</p>
        *

      • @author Animesh Jain
        */
        public class GuiceJSecurityFilter extends JSecurityFilter {

      public GuiceJSecurityFilter()

      { this.configClassName = GuiceWebConfiguration.class.getName(); }

      }

      ----------------------------------------------------------------------------------------------------------------------------

      The Guice module can be

      public class JSecurityModule extends AbstractModule {

      protected void configure()

      { // the DefaultWebSecurityManagerProvider class provides a custom configured SecurityManager if needed bind(DefaultWebSecurityManagerProvider.class).asEagerSingleton(); bindInterceptor(any(), annotatedWith(RequiresRoles.class), new AopAllianceAnnotationsAuthorizingMethodInterceptor()); }

      }

      ----------------------------------------------------------------------------------------------------------------------------

      In my own project I've somewhat tried to abstract out a few classes to make things easily configurable with Guice + Jsecurity + Hibernate + Stripes.. so I can share that project scaffold if needed.

      1. GuiceBootstrapServletContextListener.java
        1 kB
        Brian Yarger
      2. GuiceIniConfiguration.java
        0.8 kB
        Brian Yarger
      3. JsecurityModule.java
        0.8 kB
        Brian Yarger
      4. ShiroGuiceSupport.patch
        41 kB
        Jared Bunting
      5. guice-final.patch
        118 kB
        Jared Bunting

        Activity

        Hide
        Les Hazlewood added a comment -

        Closing with the 1.2.0 release.

        Show
        Les Hazlewood added a comment - Closing with the 1.2.0 release.
        Hide
        Kalle Korhonen added a comment -

        Applied, thanks Jared it's a big chunk of code!

        Show
        Kalle Korhonen added a comment - Applied, thanks Jared it's a big chunk of code!
        Hide
        Jared Bunting added a comment -

        Here's what I consider a finalized patch - it contains all of the features that were mentioned previously with some refinement and a comprehensive test suite. Once this is included, I will add the information here (https://bitbucket.org/jaredbunting/shiro-guice/src/tip/README) to the shiro wiki. Please let me know if any further refinements are needed. Thanks!

        Show
        Jared Bunting added a comment - Here's what I consider a finalized patch - it contains all of the features that were mentioned previously with some refinement and a comprehensive test suite. Once this is included, I will add the information here ( https://bitbucket.org/jaredbunting/shiro-guice/src/tip/README ) to the shiro wiki. Please let me know if any further refinements are needed. Thanks!
        Hide
        Kalle Korhonen added a comment -

        Oh yes, that looks good. Should really learn to read one of these days - managed to first ignore REST in your original example and read the second parameter just as configuration for the first one.

        Show
        Kalle Korhonen added a comment - Oh yes, that looks good. Should really learn to read one of these days - managed to first ignore REST in your original example and read the second parameter just as configuration for the first one.
        Hide
        Jared Bunting added a comment -

        I'm not sure exactly what you mean. I'll try to be a bit more verbose.

        addFilterChain("/**", AUTHC_BASIC, config(REST, "get"))

        is equivalent to the ini syntax:

        /** = authcBasic, rest[get]

        So, you can do:

        addFilterChain("/**", FILTER1, FILTER2, ... , FILTERN)

        Using the config(FILTER, "string") lets you apply the path config.

        Is that what you were asking?

        Show
        Jared Bunting added a comment - I'm not sure exactly what you mean. I'll try to be a bit more verbose. addFilterChain("/**", AUTHC_BASIC, config(REST, "get")) is equivalent to the ini syntax: /** = authcBasic, rest [get] So, you can do: addFilterChain("/**", FILTER1, FILTER2, ... , FILTERN) Using the config(FILTER, "string") lets you apply the path config. Is that what you were asking?
        Hide
        Kalle Korhonen added a comment -

        I didn't look at the actual code yet, but how do you add multiple filters to the same chain with that syntax?

        Show
        Kalle Korhonen added a comment - I didn't look at the actual code yet, but how do you add multiple filters to the same chain with that syntax?
        Hide
        Jared Bunting added a comment -

        Hmm...that didn't format like I'd hoped.

        addFilterChain("/**", AUTHC_BASIC, config(REST, "get"))

        Show
        Jared Bunting added a comment - Hmm...that didn't format like I'd hoped. addFilterChain("/**", AUTHC_BASIC, config(REST, "get"))
        Hide
        Jared Bunting added a comment -

        I've been playing around with creating a full-featured shiro-guice integration module. I'm attaching a patch of what I have so far.

        This supports Guice 3.0, and I've done my best to make Shiro functionality available in a Guice-like style. Three modules are provided:

        ShiroModule - basic Shiro functionality, makes a SecurityManager available in Guice and provides a simple approach to bind realms to it.

        ShiroAopModule - basically adapts Shiro interceptors to Guice's AOP model. Also provides an extension point to easily bind other Shiro interceptors.

        ShiroWebModule - an extension of ShiroModule that supports integration with guice-servlets. Provides a simple, guice-like dsl for configuring filter chains (addFilterChain("/**", AUTHC_BASIC, config(REST, "get"))), binds a FilterChainResolver, binds a WebSecurityManager, and binds a GuiceShiroFilter (that is just a guice-injected extension of AbstractShiroFilter).

        I've done some testing of it, and it seems to be working for me. I have not yet tested it extensively, and still need to write the test suite for it, but I would love some feedback.

        Show
        Jared Bunting added a comment - I've been playing around with creating a full-featured shiro-guice integration module. I'm attaching a patch of what I have so far. This supports Guice 3.0, and I've done my best to make Shiro functionality available in a Guice-like style. Three modules are provided: ShiroModule - basic Shiro functionality, makes a SecurityManager available in Guice and provides a simple approach to bind realms to it. ShiroAopModule - basically adapts Shiro interceptors to Guice's AOP model. Also provides an extension point to easily bind other Shiro interceptors. ShiroWebModule - an extension of ShiroModule that supports integration with guice-servlets. Provides a simple, guice-like dsl for configuring filter chains ( addFilterChain("/**", AUTHC_BASIC, config(REST, "get")) ), binds a FilterChainResolver, binds a WebSecurityManager, and binds a GuiceShiroFilter (that is just a guice-injected extension of AbstractShiroFilter). I've done some testing of it, and it seems to be working for me. I have not yet tested it extensively, and still need to write the test suite for it, but I would love some feedback.
        Hide
        Brian Yarger added a comment -

        Module that configures Jsecurity guice bindings

        Show
        Brian Yarger added a comment - Module that configures Jsecurity guice bindings
        Hide
        Brian Yarger added a comment -

        IniConfiguration that uses guice to return a SecurityManager

        Show
        Brian Yarger added a comment - IniConfiguration that uses guice to return a SecurityManager
        Hide
        Brian Yarger added a comment -

        Example of bootstrapping guice, putting the realm in the Security Manager, and placing the injector in the ServletContext

        Show
        Brian Yarger added a comment - Example of bootstrapping guice, putting the realm in the Security Manager, and placing the injector in the ServletContext
        Hide
        Brian Yarger added a comment -

        Attached is another way I've integrated JSecurity and guice. In this scenario, I bootstrap guice in a ServletContextListener, and place the injector in the ServletContext as an attribute. This exposes it to my IniConfiguration so we can return an injected SecurityManager with my realm.

        I'm still learning guice, so there might be an even cleaner way to get my realm (which needs guice injection) put in the SecurityManager, but this is working for me, and is pretty clean. I suppose I could have subclasses it and added an @Inject tag, but I wanted to limit the number of classes I subclassed if possible.

        Show
        Brian Yarger added a comment - Attached is another way I've integrated JSecurity and guice. In this scenario, I bootstrap guice in a ServletContextListener, and place the injector in the ServletContext as an attribute. This exposes it to my IniConfiguration so we can return an injected SecurityManager with my realm. I'm still learning guice, so there might be an even cleaner way to get my realm (which needs guice injection) put in the SecurityManager, but this is working for me, and is pretty clean. I suppose I could have subclasses it and added an @Inject tag, but I wanted to limit the number of classes I subclassed if possible.

          People

          • Assignee:
            Kalle Korhonen
            Reporter:
            Animesh Jain
          • Votes:
            0 Vote for this issue
            Watchers:
            0 Start watching this issue

            Dates

            • Created:
              Updated:
              Resolved:

              Development