将 Apache Shiro 集成到基于 Spring 的应用程序中

该页面介绍了将 Shiro 集成到基于Spring的应用程序中的方法。

Shiro 的 JavaBeans 兼容性使其非常适合通过 Spring XML 或其他基于 Spring 的配置机制进行配置。 Shiro 应用程序需要一个应用程序实例SecurityManager实例。请注意,这不必是* static *单例,而应仅由应用程序使用一个实例,无论它是否为静态单例。

Standalone Applications

这是在 Spring 应用程序中启用应用程序单例SecurityManager的最简单方法:

<!-- Define the realm you want to use to connect to your back-end security datasource: -->
<bean id="myRealm" class="...">
    ...
</bean>

<bean id="securityManager" class="org.apache.shiro.mgt.DefaultSecurityManager">
    <!-- Single realm app.  If you have multiple realms, use the 'realms' property instead. -->
    <property name="realm" ref="myRealm"/>
</bean>

<bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>

<!-- For simplest integration, so that all SecurityUtils.* methods work in all cases, -->
<!-- make the securityManager bean a static singleton.  DO NOT do this in web         -->
<!-- applications - see the 'Web Applications' section below instead.                 -->
<bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
    <property name="staticMethod" value="org.apache.shiro.SecurityUtils.setSecurityManager"/>
    <property name="arguments" ref="securityManager"/>
</bean>

Web Applications

Shiro 对 Spring Web 应用程序提供了一流的支持。在 Web 应用程序中,所有 Shiro 可访问的 Web 请求都必须通过主 Shiro 筛选器。该过滤器本身非常强大,可以
基于任何 URL 路径表达式执行的临时定制过滤器链。

在 Shiro 1.0 之前,您必须在 Spring Web 应用程序中使用混合方法,定义 Shiro 过滤器和
其所有配置属性都位于 web.xml 中,但在 Spring XML 中定义SecurityManager。这有点令人沮丧,因为您无法:1)将配置整合到一个位置,以及 2)利用更高级的 Spring 功能(例如PropertyPlaceholderConfigurer或抽象 bean)的配置功能来整合通用配置。

现在,在 Shiro 1.0 和更高版本中,所有 Shiro 配置都在 Spring XML 中完成,从而可以访问更强大的 Spring 配置机制。

这是在基于 Spring 的 Web 应用程序中配置 Shiro 的方法:

web.xml

除了您的其他 Spring web.xml 元素(ContextLoaderListenerLog4jConfigListener等)之外,还定义以下过滤器和过滤器 Map:

<!-- The filter-name matches name of a 'shiroFilter' bean inside applicationContext.xml -->
<filter>
    <filter-name>shiroFilter</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    <init-param>
        <param-name>targetFilterLifecycle</param-name>
        <param-value>true</param-value>
    </init-param>
</filter>

...

<!-- Make sure any request you want accessible to Shiro is filtered. /* catches all -->
<!-- requests.  Usually this filter mapping is defined first (before all others) to -->
<!-- ensure that Shiro works in subsequent filters in the filter chain:             -->
<filter-mapping>
    <filter-name>shiroFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

applicationContext.xml

在您的 applicationContext.xml 文件中,定义启用 Web 的SecurityManager和将从web.xml引用的'shiroFilter'bean。

<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
    <property name="securityManager" ref="securityManager"/>
    <!-- override these for application-specific URLs if you like:
    <property name="loginUrl" value="/login.jsp"/>
    <property name="successUrl" value="/home.jsp"/>
    <property name="unauthorizedUrl" value="/unauthorized.jsp"/> -->
    <!-- The 'filters' property is not necessary since any declared javax.servlet.Filter bean  -->
    <!-- defined will be automatically acquired and available via its beanName in chain        -->
    <!-- definitions, but you can perform instance overrides or name aliases here if you like: -->
    <!-- <property name="filters">
        <util:map>
            <entry key="anAlias" value-ref="someFilter"/>
        </util:map>
    </property> -->
    <property name="filterChainDefinitions">
        <value>
            # some example chain definitions:
            /admin/** = authc, roles[admin]
            /docs/** = authc, perms[document:read]
            /** = authc
            # more URL-to-FilterChain definitions here
        </value>
    </property>
</bean>

<!-- Define any javax.servlet.Filter beans you want anywhere in this application context.   -->
<!-- They will automatically be acquired by the 'shiroFilter' bean above and made available -->
<!-- to the 'filterChainDefinitions' property.  Or you can manually/explicitly add them     -->
<!-- to the shiroFilter's 'filters' Map if desired. See its JavaDoc for more details.       -->
<bean id="someFilter" class="..."/>
<bean id="anotherFilter" class="..."> ... </bean>
...

<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
    <!-- Single realm app.  If you have multiple realms, use the 'realms' property instead. -->
    <property name="realm" ref="myRealm"/>
    <!-- By default the servlet container sessions will be used.  Uncomment this line
         to use shiro's native sessions (see the JavaDoc for more): -->
    <!-- <property name="sessionMode" value="native"/> -->
</bean>
<bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>

<!-- Define the Shiro Realm implementation you want to use to connect to your back-end -->
<!-- security datasource: -->
<bean id="myRealm" class="...">
    ...
</bean>

启用 ShiroComments

在独立应用程序和 Web 应用程序中,您可能都希望使用 Shiro 的 Comments 进行安全检查(例如@RequiresRoles@RequiresPermissions等)。这需要 Shiro 的 Spring AOP 集成来扫描适当的 Comments 类并根据需要执行安全性逻辑。

这是启用这些 Comments 的方法。只需将这两个 bean 定义添加到applicationContext.xml

<!-- Enable Shiro Annotations for Spring-configured beans.  Only run after -->
<!-- the lifecycleBeanProcessor has run: -->
<bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator" depends-on="lifecycleBeanPostProcessor"/>
    <bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
    <property name="securityManager" ref="securityManager"/>
</bean>

安全 Spring 远程处理

Shiro 的 Spring 远程支持包括两个部分:进行远程调用的 Client 端配置和用于接收和处理远程调用的服务器的配置。

Server-side Configuration

当远程方法调用进入启用 Shiro 的服务器时,与该 RPC 调用关联的Subject必须绑定到接收线程以便在线程执行期间进行访问。这是通过在applicationContext.xml中定义 Shiro 的SecureRemoteInvocationExecutor bean 来完成的:

<!-- Secure Spring remoting:  Ensure any Spring Remoting method invocations -->
<!-- can be associated with a Subject for security checks. -->
<bean id="secureRemoteInvocationExecutor" class="org.apache.shiro.spring.remoting.SecureRemoteInvocationExecutor">
    <property name="securityManager" ref="securityManager"/>
</bean>

定义此 bean 之后,必须将其插入到用于导出/公开服务的远程处理Exporter上。 Exporter实现是根据使用的远程处理机制/协议定义的。有关定义Exporter bean 的信息,请参见 Spring 的Remoting chapter

例如,如果使用基于 HTTP 的远程处理(请注意对secureRemoteInvocationExecutor bean 的属性引用):

<bean name="/someService" class="org.springframework.remoting.httpinvoker.HttpInvokerServiceExporter">
    <property name="service" ref="someService"/>
    <property name="serviceInterface" value="com.pkg.service.SomeService"/>
    <property name="remoteInvocationExecutor" ref="secureRemoteInvocationExecutor"/>
</bean>

Client-side Configuration

执行远程呼叫时,必须将Subject标识信息附加到远程有效负载上,以使服务器知道是谁在进行呼叫。如果 Client 端是基于 Spring 的 Client 端,则通过 Shiro 的SecureRemoteInvocationFactory完成关联:

<bean id="secureRemoteInvocationFactory" class="org.apache.shiro.spring.remoting.SecureRemoteInvocationFactory"/>

然后,在定义了该 bean 之后,需要将其插入到您正在使用的特定于协议的 Spring 远程处理ProxyFactoryBean中。

例如,如果您使用的是基于 HTTP 的远程处理(请注意,对上面定义的secureRemoteInvocationFactory bean 的属性引用):

<bean id="someService" class="org.springframework.remoting.httpinvoker.HttpInvokerProxyFactoryBean">
    <property name="serviceUrl" value="http://host:port/remoting/someService"/>
    <property name="serviceInterface" value="com.pkg.service.SomeService"/>
    <property name="remoteInvocationFactory" ref="secureRemoteInvocationFactory"/>
</bean>

协助处理文档

尽管我们希望该文档对您使用 Apache Shiro 所做的工作有所帮助,但社区一直在不断改进和扩展文档。如果您想为 Shiro 项目提供帮助,请考虑在需要的地方更正,扩展或添加文档。您提供的每一点帮助都会扩大社区,进而改善 Shiro。

贡献文档的最简单方法是将其发送到User Forum用户邮件列表