Apache Shiro 1.8.0是当前的稳定版本(Java 1.8+ JVM).
本系列文章目录如下:
- 为什么要使用Apache Shiro(一)
- Apache Shiro的三个重要概念(二)
- Apache Shiro核心功能之Authentication(三)
- Apache Shiro核心功能之Authorization(四)
- Apache Shiro核心功能之Session Management(五)
- Apache Shiro核心功能之Cryptography(六)
- Apache Shiro集成
- 将Apache Shiro集成到Spring-Boot应用程序中
Shiro的Spring-Boot集成是将Shiro集成到基于spring的应用程序中最简单的方法。
WEB应用程序
Shiro对Spring web应用程序提供一流的支持。在一个web应用程序中,所有可以访问Shiro的web请求必须通过一个主Shiro Filter。这个过滤器本身非常强大,允许基于任何URL路径表达式执行特定的自定义过滤器链。
首先,在你的应用程序类路径中包含Shiro Spring web starter依赖项
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring-boot-web-starter</artifactId>
<version>1.8.0</version>
</dependency>
提供一个Realm实现:
@Bean
public Realm realm() {
...
}
最后是一个ShiroFilterChainDefinition,它将映射任何应用程序特定的路径到一个给定的过滤器,以便允许不同的路径不同级别的访问。
@Bean
public ShiroFilterChainDefinition shiroFilterChainDefinition() {
DefaultShiroFilterChainDefinition chainDefinition = new DefaultShiroFilterChainDefinition();
// logged in users with the 'admin' role
chainDefinition.addPathDefinition("/admin/**", "authc, roles[admin]");
// logged in users with the 'document:read' permission
chainDefinition.addPathDefinition("/docs/**", "authc, perms[document:read]");
// all other paths require a logged in user
chainDefinition.addPathDefinition("/**", "authc");
return chainDefinition;
}
使用Shiro注解
在独立应用程序和web应用程序中,您可能希望使用Shiro的注解进行安全检查(例如,@RequiresRoles, @RequiresPermissions等)。这些注解在上面列出的两个启动器中都是自动启用的。
@RequiresPermissions("document:read")
public void readDocument() {
...
}
注解和Web程序
@Controller
public class AccountInfoController {
@RequiresRoles("admin")
@RequestMapping("/admin/config")
public String adminConfig(Model model) {
return "view";
}
}
一个至少有一个定义的ShiroFilterChainDefinition bean仍然需要工作,要么配置所有路径可以通过anon过滤器访问,要么配置一个' permissive '模式的过滤器,例如:authcBasic[permissive]。
@Bean
public ShiroFilterChainDefinition shiroFilterChainDefinition() {
DefaultShiroFilterChainDefinition chainDefinition = new DefaultShiroFilterChainDefinition();
chainDefinition.addPathDefinition("/**", "anon"); // all paths are managed via annotations
// or allow basic authentication, but NOT require it.
// chainDefinition.addPathDefinition("/**", "authcBasic[permissive]");
return chainDefinition;
}
缓存
启用缓存就像提供一个 CacheManager bean一样简单:
@Bean
protected CacheManager cacheManager() {
return new MemoryConstrainedCacheManager();
}