精彩文章免费看

SpringBoot 集成Shiro--官网

SpringBoot 集成Shiro

Web 应用

Spring Web 项目中,Shiro是通过过滤器来控制Web请求的

首先将Shiro的 web-starter 依赖添加到应用程序的类路径中,推荐采用 Maven Gradle

maven

<dependency>
    <groupId>org.apache.shiro</groupId>
    <artifactId>shiro-spring-boot-web-starter</artifactId>
    <version>1.7.1</version>
</dependency>

gradle

compile 'org.apache.shiro:shiro-spring-boot-web-starter:1.7.1'

然后提供一个Realm的实现

@Bean
public Realm realm() {

最后添加一个ShiroFilterChainDefinition到容器中,它指定了URL路径及其对应的过滤器链

@Bean
public ShiroFilterChainDefinition shiroFilterChainDefinition(){
    DefaultShiroFilterChainDefinition chainDefinition = new DefaultShiroFilterChainDefinition();
    chainDefinition.addPathDefinition("/admin/**", "authc, roles[admin]");
    chainDefinition.addPathDefinition("/docs/**", "authc, perms[document:read]");
    chainDefinition.addPathDefinition("/**", "authc");
    return chainDefinition;

完整示例参考github

开启Shiro的注解支持

如果包含了前面的shiro-spring-boot-web-starter,则就会自动开启Shiro的注解支持

@RequiresPermissions("document:read")
public void readDocument() {

注解与Web应用程序

Shiro的注解可以在@Controller类中使用,如下

@Controller
public class AccountInfoController {
    @RequiresRoles("admin")
    @RequestMapping("/admin/config")
    public String adminConfig(Model model) {
        return "view";

为了确保应用程序工作,至少需要一个ShiroFilterChainDefinition,并且其中至少包含了一个URL的过滤器链,要么配置所有的路径均可以匿名访问,要么就配置一个过滤器来过滤请求

@Bean
public ShiroFilterChainDefinition shiroFilterChainDefinition() {
    DefaultShiroFilterChainDefinition chainDefinition = new DefaultShiroFilterChainDefinition();
    chainDefinition.addPathDefinition("/**", "anno");
    return chainDefinition;

只需提供一个CacheManagerbean即可开启缓存

@Bean
protected CacheManager cacheManager() {
    return new MemoryConstrainedCacheManager();

最后为了使得SecurityUtils.*方法生效,只需要使得SecurityManager的bean设置到SecurityUtils即可

@Autowire
private SecurityManager securityManager;
@PostConstruct
private void initStaticSecurityManager() {
    SecurityUtils.setSecurityManager(securityManager);

接下来就可以像下面这样获取Subject

SecurityUtils.getSubject();

完整示例参考github