用户权限管理一般是对用户页面、按钮的访问权限管理。Shiro框架是一个强大且易用的Java安全框架,执行身份验证、授权、密码和会话管理,对于Shiro的介绍这里就不多说。本篇博客主要是了解Shiro的基础使用方法,在权限管理系统中集成Shiro实现登录、url和页面按钮的访问控制。
一、引入依赖
使用SpringBoot集成Shiro时,在pom.xml中可以引入shiro-spring-boot-web-starter。由于使用的是thymeleaf框架,thymeleaf与Shiro结合需要 引入thymeleaf-extras-shiro。
org.apache.shiro shiro-spring-boot-web-starter1.4.0 com.github.theborakompanioni thymeleaf-extras-shiro2.0.0
二、增加Shiro配置
有哪些url是需要拦截的,哪些是不需要拦截的,登录页面、登录成功页面的url、自定义的Realm等这些信息需要设置到Shiro中,所以创建Configuration文件ShiroConfig。
package com.example.config;import org.apache.shiro.mgt.SecurityManager;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;import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;import java.util.linkedHashMap;import java.util.Map;
@Configurationpublic class ShiroConfig {
@Bean("shiroFilterFactoryBean") public ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityManager securityManager) {
System.out.println("ShiroConfiguration.shirFilter()");
ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
shiroFilterFactoryBean.setSecurityManager(securityManager); //拦截器.
Map filterChainDefinitionMap = new linkedHashMap(); // 配置不会被拦截的链接 顺序判断
filterChainDefinitionMap.put("/static
@Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
System.out.println("MyShiroRealm.doGetAuthenticationInfo()"); //获取用户的输入的账号.
String username = (String)token.getPrincipal();
System.out.println(token.getCredentials()); //通过username从数据库中查找 User对象,如果找到,没找到. //实际项目中,这里可以根据实际情况做缓存,如果不做,Shiro自己也是有时间间隔机制,2分钟内不会重复执行该方法
User user = userService.getUserById(username);
System.out.println("----->>userInfo="+user); if(user == null){ return null;
}
SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
user, //用户名
"123456", //密码
getName() //realm name ); return authenticationInfo;
}
} View Code
四、登录认证
1.登录页面
这里做了一个非常丑的登录页面,主要是自己懒,不想在网上复制粘贴找登录页面了。


