SpringBoo整合Shiro环境搭建

SpringBoo整合Shiro环境搭建_第1张图片

Shiro的三大对象

1.subject 当前用户
2.securityMonager 管理所有用户
3.Realm 建接数据I .

1.创建一个Spring Initializr一直下一步,选择Web环境

SpringBoo整合Shiro环境搭建_第2张图片

2.在Pom中导入Shiro整合Spring的jar包



    org.apache.shiro
    shiro-spring
    1.5.2

3.写配置类ShiroConfig.java

package com.example.demo.config;

import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ShiroConfig {
    /*三步走,倒着写,将它们交给Spring管理*/
    //ShiroFilterFactoryBean:3
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("securityManager")DefaultWebSecurityManager securityManager){
        ShiroFilterFactoryBean factoryBean = new ShiroFilterFactoryBean();
        //设置安全管理器
        factoryBean.setSecurityManager(securityManager);
        return factoryBean;
    }
    //DefaultWebSecurityManager:2  @Bean(name = "securityManager")给bean取别名
    @Bean(name = "securityManager")
    public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm")UserRealm userRealm){
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        //关联Realm
        securityManager.setRealm(userRealm);
        return securityManager;
    }
    //创建realm对象,需要自定义类:1,
    @Bean
    public UserRealm userRealm(){
        return new UserRealm();
    }
}

自定义UserRealm类

package com.example.demo.config;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
//自定义UserRealm 需要extends AuthorizingRealm
public class UserRealm extends AuthorizingRealm {
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行了=>授权 doGetAuthorizationInfo");
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("执行了=>认证 doGetAuthorizationInfo");
        return null;
    }
}

你可能感兴趣的:(SpringBoo整合Shiro环境搭建)