SpringBoot 集成Shiro

2019-04-15  本文已影响0人  Bertram_Wang

Apache Shiro是一个功能强大且灵活的开源安全框架,可以清晰地处理身份验证,授权,企业会话管理和加密。

技术背景

创建项目

创建maven子项目 study-springboot-backstage 引入一下依赖pom.xml

    <project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>study-springboot</groupId>
        <artifactId>study-springboot</artifactId>
        <version>0.0.1-SNAPSHOT</version>
    </parent>
    <artifactId>study-springboot-backstage</artifactId>
    <description>后台管理</description>
    <dependencies>
        <!-- 实体项目 -->
        <dependency>
            <groupId>study-springboot</groupId>
            <artifactId>study-springboot-domain</artifactId>
            <version>0.0.1-SNAPSHOT</version>
        </dependency>
        <!-- shiro -->
        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-spring</artifactId>
            <version>1.4.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-ehcache</artifactId>
            <version>1.4.0</version>
        </dependency>
        <!-- shiro+redis缓存插件 -->
        <dependency>
            <groupId>org.crazycake</groupId>
            <artifactId>shiro-redis</artifactId>
            <version>2.4.2.1-RELEASE</version>
        </dependency>
        <!-- 开启注解 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
       </dependency>
    </dependencies>

    <!-- 打包 -->
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

配置AuthorizingRealm,创建SysUserRealm.java

/**
 * @describe shiro认证
 * @author Bertram.Wang
 */
@Component
public class SysUserRealm extends AuthorizingRealm {

    @Autowired
    private SysUserRepository sysUserRepository;
    @Autowired
    private SysUserService sysUserService;

    
    /**
     * 授权(验证权限时调用)
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        SysUser user = (SysUser) principals.getPrimaryPrincipal();
        Integer userId = user.getId();

        // 用户权限列表
        Set<String> permsSet = sysUserService.getAuthorityByUserId(userId);

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setStringPermissions(permsSet);
        return info;
    }

    /**
     * 认证(登录时调用)
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String username = (String) token.getPrincipal();
        String password = new String((char[]) token.getCredentials());
        // 查询用户信息
        SysUser user = sysUserRepository.findOneByNameAndPassword(username, password);

        // 账号不存在
        if (user == null) {
            throw new UnknownAccountException("账号或密码不正确");
        }
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(userInfo, password, getName());
        return info;
    }

}

shiro配置类,主要是设置shiroFilter,securityManager, sessionManage等信息
自定义SessionManager

/**
 * @Date 2019年4月10日
 * @Sgin MySessionManager
 * @Author Bertram.Wang
 */
public class MySessionManager extends DefaultWebSessionManager {
 
    private static final String AUTHORIZATION = "Authorization";
 
    private static final String REFERENCED_SESSION_ID_SOURCE = "Stateless request";
 
    public MySessionManager() {
        super();
    }
 
    @Override
    protected Serializable getSessionId(ServletRequest request, ServletResponse response) {
        String id = WebUtils.toHttp(request).getHeader(AUTHORIZATION);
        //如果请求头中有 Authorization 则其值为sessionId
        if (!StringUtils.isEmpty(id)) {
            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_SOURCE, REFERENCED_SESSION_ID_SOURCE);
            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID, id);
            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_IS_VALID, Boolean.TRUE);
            return id;
        } else {
            //否则按默认规则从cookie取sessionId
            return super.getSessionId(request, response);
        }
    }
}

shiroConfig.java

/**
 * @Date 2019年4月10日
 * @Sgin ShiroConfig
 * @Author Bertram.Wang
 */
@Configuration
public class ShiroConfig {

    @Bean
    public ShiroFilterFactoryBean shiroFilter(SecurityManager securityManager) {
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        shiroFilterFactoryBean.setSecurityManager(securityManager);
        // 没有登陆的用户只能访问登陆页面
        shiroFilterFactoryBean.setLoginUrl("/initlogin");
        // 登录成功后要跳转的链接
        //shiroFilterFactoryBean.setSuccessUrl("/auth/index");
        // 未授权界面; ----这个配置了没卵用,具体原因想深入了解的可以自行百度
        shiroFilterFactoryBean.setUnauthorizedUrl("/initlogin");
        //自定义拦截器
        Map<String, Filter> filtersMap = new LinkedHashMap<String, Filter>();
        //限制同一帐号同时在线的个数。
        filtersMap.put("kickout", kickoutSessionControlFilter());
        shiroFilterFactoryBean.setFilters(filtersMap);
        // 权限控制map.
        Map<String, String> filterChainDefinitionMap = new LinkedHashMap<String, String>();
        filterChainDefinitionMap.put("/css/**", "anon");
        filterChainDefinitionMap.put("/js/**", "anon");
        filterChainDefinitionMap.put("/img/**", "anon");
        filterChainDefinitionMap.put("/login", "anon");
        filterChainDefinitionMap.put("/logout", "logout");
        filterChainDefinitionMap.put("/**/kickout", "anon");
        filterChainDefinitionMap.put("/**", "authc,kickout");
        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
        return shiroFilterFactoryBean;
    }

    @Bean
    public SecurityManager securityManager(SysUserRealm sysUserRealm) {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setRealm(sysUserRealm);
        // 自定义缓存实现 使用redis
        securityManager.setCacheManager(cacheManager());
        // 自定义session管理 使用redis
        securityManager.setSessionManager(sessionManager());
        return securityManager;
    }


    /**
     * cacheManager 缓存 redis实现 使用的是shiro-redis开源插件
     * @return
     */
    public RedisCacheManager cacheManager() {
        RedisCacheManager redisCacheManager = new RedisCacheManager();
        redisCacheManager.setRedisManager(redisManager());
        return redisCacheManager;
    }

    /**
     * shiro redisManager 使用的是shiro-redis开源插件
     * @return
     */
    public RedisManager redisManager() {
        RedisManager redisManager = new RedisManager();
        redisManager.setHost("localhost");
        redisManager.setPort(6379);
        redisManager.setExpire(1800);// 配置缓存过期时间
        redisManager.setTimeout(0);
        redisManager.setPassword("Redis1234!");
        return redisManager;
    }

    /**
     * Session Manager 
     */
    @Bean
    public DefaultWebSessionManager sessionManager() {
        MySessionManager mySessionManager = new MySessionManager();
        mySessionManager.setSessionDAO(redisSessionDAO());
        return mySessionManager;
    } 

    /**
     * RedisSessionDAO shiro 
     */
    @Bean
    public RedisSessionDAO redisSessionDAO() {
        RedisSessionDAO redisSessionDAO = new RedisSessionDAO();
        redisSessionDAO.setRedisManager(redisManager());
        return redisSessionDAO;
    }

    /**
     * *限制同一账号登录同时登录人数控制
     * @return
     */
    @Bean
    public KickoutSessionControlFilter kickoutSessionControlFilter() {
        KickoutSessionControlFilter kickoutSessionControlFilter = new KickoutSessionControlFilter();
        kickoutSessionControlFilter.setCacheManager(cacheManager());
        kickoutSessionControlFilter.setSessionManager(sessionManager());
        kickoutSessionControlFilter.setKickoutAfter(false);
        kickoutSessionControlFilter.setMaxSession(1);
        kickoutSessionControlFilter.setKickoutUrl("/auth/kickout");
        return kickoutSessionControlFilter;
    }


    /***
     * *授权所用配置
     * @return
     */
    @Bean
    public DefaultAdvisorAutoProxyCreator getDefaultAdvisorAutoProxyCreator() {
        DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator = new DefaultAdvisorAutoProxyCreator();
        defaultAdvisorAutoProxyCreator.setProxyTargetClass(true);
        return defaultAdvisorAutoProxyCreator;
    }

    /***
     * *使授权注解起作用不如不想配置可以在pom文件中加入
     * <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
       </dependency>
     * @param securityManager
     * @return
     */
//    @Bean
//    public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager){
//      AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
//        authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
//        return authorizationAttributeSourceAdvisor;
//    }

    /**
     * Shiro生命周期处理器
     */
    @Bean
    public LifecycleBeanPostProcessor getLifecycleBeanPostProcessor() {
        return new LifecycleBeanPostProcessor();
    }
}

限制规则:


引用图

测试控制器

@RestController
public class TestController {
    @Autowired
    private SysUserService sysUserService;
    @GetMapping("/hello")
    public Response<?> hello() {
        SysUser sysUser = sysUserRepository.findOneById(2);
        return success(authorityByUserId);
    }
}

测试类

/**
 * <p> 测试<p>
 * @Author Bertram.Wang 
 */
@RunWith(SpringRunner.class)   
@SpringBootTest(classes=Application.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class ApplicationTest {
    private static final Logger log = LoggerFactory.getLogger(ApplicationTest.class);
    @LocalServerPort
    private int port;
    private String base;
    @Autowired
    private TestRestTemplate restTemplate;
    @Before
    public void setUp() throws Exception {
        this.base = String.format("http://localhost:%d/%s", port, "/backstage");
    } 
    /**
     * *设置请求消息头
     */
    private static HttpHeaders setHttpHeaders() {
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-type", "application/json;charset=utf-8;Accept:application/json;");// 设置编码 这个一定不能去
        headers.add("Authorization", AUTHORIZATION);
        return headers;
    }
    // sessionID
    private static final String AUTHORIZATION = "sessionId";
    
    private String requestGET(String url){
        HttpEntity<Object> requestEntity = new HttpEntity<>(setHttpHeaders());
        ResponseEntity<String> rest = restTemplate.exchange(this.base + url, HttpMethod.GET, requestEntity, String.class);
        return rest.getBody();
    }
    private String requestPOST(String url, Object data){
        HttpEntity<Object> requestEntity = new HttpEntity<>(data, setHttpHeaders());
        ResponseEntity<String> rest = restTemplate.postForEntity(this.base + url, requestEntity, String.class);
        return rest.getBody();
    }
    // ---------------------LoginController--------------------------
    @Test
    public void logoutTest() throws Exception {
        String requestGET = requestGET("/logout");
        log.info("===================rest:{}", requestGET);
    }
    @Test
    public void loginTest() throws Exception {
        SysUserAO sysUserAO = new SysUserAO();
        sysUserAO.setUsername("admin");
        sysUserAO.setPassword("admin");
        String requestPOST = requestPOST("/login", sysUserAO);
        log.info("===================rest:{}", requestPOST);
    }
    
    @Test
    public void helloTest() throws Exception {
        String requestGET = requestGET("/hello");
        log.info("===================rest:{}", requestGET);
    }
}

执行helloTest方法,

rest:{"code":20303,"message":"请先登录","time":1555320155};

先执行loginTest方法:

rest:{"code":0,"message":"成功","time":1555320426,"data":{"id":"a521dbf5-6a63-45d2-85de-95c121aeb0e9","host":"127.0.0.1","lastAccessTime":"2019-04-15T09:27:05.985+0000","timeout":1800000,"attributeKeys":["org.apache.shiro.subject.support.DefaultSubjectContext_AUTHENTICATED_SESSION_KEY","org.apache.shiro.subject.support.DefaultSubjectContext_PRINCIPALS_SESSION_KEY"],"startTimestamp":"2019-04-15T09:27:05.985+0000"}}

把rest.data.id替换sessionId,再执行helloTest方法:

rest:{"code":0,"message":"成功","time":1555328243,"data":{"id":2,"createDate":"2019-04-10T09:31:51.000+0000","modifyDate":"2019-04-10T09:31:53.000+0000","name":"admin","password":"8c6976e5b5410415bde908bd4dee15dfb167a9c873fc4bb8a81f6f2ab448a918","roles":[{"id":1,"createDate":"2019-04-03T06:53:22.000+0000","modifyDate":"2019-04-03T06:53:25.000+0000","name":"ADMIN","parentId":0,"menus":[{"id":1,"createDate":"2018-08-30T09:27:32.000+0000","modifyDate":"2018-10-10T08:44:03.000+0000","name":"系统管理","parentId":0,"permission":null,"type":0,"url":null,"icon":"fa fa-cog","orderNum":1}]}]}}
上一篇下一篇

猜你喜欢

热点阅读