SpringBoot 集成Shiro

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

  • 验证用户以验证其身份

  • 为用户执行访问控制,例如:

    • 确定是否为用户分配了某个安全角色
    • 确定是否允许用户执行某些操作
  • 在任何环境中使用Session API,即使没有Web容器或EJB容器也是如此。

  • 在身份验证,访问控制或会话生命周期内对事件做出反应。

  • 聚合用户安全数据的1个或多个数据源,并将其全部显示为单个复合用户“视图”。

  • 启用单点登录(SSO)功能

  • 无需登录即可为用户关联启用“记住我”服务
    Shiro针对Shiro开发团队所称的“应用程序安全的四大基石” - 身份验证,授权,会话管理和加密:

  • 身份验证:有时称为“登录”,这是证明用户是他们所说的人的行为。

  • 授权:访问控制的过程,即确定“谁”可以访问“什么”。

  • 会话管理:即使在非Web或EJB应用程序中,也可以管理特定于用户的会话。

  • 密码学:使用加密算法保持数据安全,同时仍然易于使用。
    具体参考: http://shiro.apache.org/reference.html

技术背景

  • 开发工具:STS(eclipse)
  • 技术选择: SpringBoot, SpringDataJpa, shiro
  • 数据库选择: MySQL, Redis

创建项目

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

    
    4.0.0
    
        study-springboot
        study-springboot
        0.0.1-SNAPSHOT
    
    study-springboot-backstage
    后台管理
    
        
        
            study-springboot
            study-springboot-domain
            0.0.1-SNAPSHOT
        
        
        
            org.apache.shiro
            shiro-spring
            1.4.0
        
        
            org.apache.shiro
            shiro-ehcache
            1.4.0
        
        
        
            org.crazycake
            shiro-redis
            2.4.2.1-RELEASE
        
        
        
            org.springframework.boot
            spring-boot-starter-aop
       
    

    
    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
        
    

配置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 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 filtersMap = new LinkedHashMap();
        //限制同一帐号同时在线的个数。
        filtersMap.put("kickout", kickoutSessionControlFilter());
        shiroFilterFactoryBean.setFilters(filtersMap);
        // 权限控制map.
        Map filterChainDefinitionMap = new LinkedHashMap();
        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文件中加入
     * 
            org.springframework.boot
            spring-boot-starter-aop
       
     * @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();
    }
}

限制规则:


SpringBoot 集成Shiro_第1张图片
引用图
  • anon:准许直接访问
  • authc:要求对请求用户进行身份验证,以便请求继续,如果没有验证,则强制用户通过将其定向到您配置的LoginUurl来登录。
  • logout:接收到请求后,将立即注销当前正在执行的子节点,然后将它们重定向到已配置的redirecturl。
  • perms: 如果当前用户具有映射值指定的权限,则允许访问;如果用户没有指定的所有权限,则拒绝访问
    具体参考:http://shiro.apache.org/static/1.4.0/apidocs/org/apache/shiro/web/filter/

测试控制器

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

测试类

/**
 * 

测试

* @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 requestEntity = new HttpEntity<>(setHttpHeaders()); ResponseEntity rest = restTemplate.exchange(this.base + url, HttpMethod.GET, requestEntity, String.class); return rest.getBody(); } private String requestPOST(String url, Object data){ HttpEntity requestEntity = new HttpEntity<>(data, setHttpHeaders()); ResponseEntity 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}]}]}}

你可能感兴趣的:(SpringBoot 集成Shiro)