Spring 应用中集成 Apache Shiro

这一篇文章涵盖了将 Shiro 集成到基于 Spring 的应用程序的方法。

Shiro 的 Java Bean兼容性使它非常适合通过 Spring XML 或其他基于 Spring 的配置机制进行配置。Shiro 的应用程序需要一个应用程序单例安全管理器 ( SecuriyManager) 实例。注意,这并不一定是静态的单例,但是应用程序应该只使用一个实例,不管它是否是静态的单例。

1.独立的应用程序

以下是在 Spring 应用程序中启用应用程序单例安全管理器的最简单方法:



    ...



    
    






    
    

2.Web 应用程序

Shiro 对 Spring web 应用程序有很棒的支持。在一个 web 应用程序中,所有的可用的 web 请求都必须经过 Shiro Filter。这个过滤器非常强大,允许基于 URL 路径表达式执行的特殊自定义任何过滤器链。

在 Shiro 1.0之前,你必须在 Spring web 应用程序中使用一种混合的方法,定义 Shiro 的过滤器所有的配置属性都在 web.xml 中。但是在 spring.xml中定义 securityManager,这有点不友好。

现在,在 Shiro 1.0 以上的版本中,所有的 Shiro 配置都是在Spring XML 中完成的,它提供了更健壮的 Spring 配置机制。
以下是如何在基于 spring 的 web 应用程序中配置 Shiro:

web.xml

除了其他的 spring 的一些标签 ( ContextLoaderListener、Log4jConfigListener 等),还定义了以下过滤器和过滤器的映射:



    shiroFilter
    org.springframework.web.filter.DelegatingFilterProxy
    
        targetFilterLifecycle
        true
    


...



    shiroFilter
    /*

applicationContext.xml

在 applicationContext.xml 文件,定义 web 适用的SecurityManager 和 “shiroFilter” bean,这个bean 在 web.xml 中会被引用。


    
    
    
    
    
        
            # 定义需要过滤的 url :
            /admin/** = authc, roles[admin]
            /docs/** = authc, perms[document:read]
            /** = authc
            
    



 ... 
...


    
    
    
    





    ...

启用 Shiro 的注解

在应用程序中,可能需要使用 Shiro 的注释来进行安全检查(例如,@RequiresRole、@requiresPermission 等等。这需要 Shiro的 Spring AOP 集成,以扫描适当的带注释的类,并在必要时执行安全逻辑。下面是如何启用这些注释,将这两个 bean 定义添加到 applicationContext.xml 中:


    
    

你可能感兴趣的:(Spring 应用中集成 Apache Shiro)