用户权限:
admin登录:
admin1登录:
admin2登录:
gitee源码地址:https://gitee.com/zhongbai111/springboot_shiro.git
第一步导入依赖:
<dependencies>
<!--
shiro三大对象
subject:用户
securityManager:管理所有用户
Realm:连接数据库
-->
<!--
springboot与shiro的依赖
-->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring-boot-web-starter</artifactId>
<version>1.7.1</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<!--
连接数据库依赖
-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.17</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.4</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.16</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!--
springboot与mybatis的依赖
-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.4</version>
</dependency>
<!--thymeleaf与shiro的依赖-->
<dependency>
<groupId>com.github.theborakompanioni</groupId>
<artifactId>thymeleaf-extras-shiro</artifactId>
<version>2.0.0</version>
</dependency>
</dependencies>
第二步搭建环境:properties以及yml文件
server:
port: 8081
spring:
datasource:
password: 123456
url: jdbc:mysql://localhost:3306/jsptest?useSSL=false&serverTimezone=UTC
driver-class-name: com.mysql.cj.jdbc.Driver
username: root
type: com.alibaba.druid.pool.DruidDataSource
#druid数据源专有配置
initialSize: 5
minIdle: 5
maxActive: 20
maxWait: 60000
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 300000
validationQuery: SELECT 1 FROM DUAL
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
poolPreparedStatements: true
#配置监控统计拦截的filters,stat:监控统计、log4j:日志记录、wall:防御sql注入
#如果允许报错,java.lang.ClassNotFoundException: org.apache.Log4j.Properity
#则导入log4j 依赖就行
filters: stat,wall,log4j
maxPoolPreparedStatementPerConnectionSize: 20
useGlobalDataSourceStat: true
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
server.port=8081
#mybatis的配置
#实体类路径
mybatis.type-aliases-package=com.sun.pojo
#XXXMapper.xml文件路径
mybatis.mapper-locations=classpath:mapper/*.xml
第三步实现业务:
(实体类,controller,service,mapper,mapper.xml)
User:
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private int id;
private String username;
private String password;
private String perms;
}
controller:
@Controller
public class MyController {
@RequestMapping({"/","/index"})
public String toIndex(Model model){
model.addAttribute("msg","hello,Shiro");
return "index";
}
@RequestMapping("/user/add")
public String add(){
return "/user/add";
}
@RequestMapping("/user/update")
public String update(){
return "/user/update";
}
@RequestMapping("/toLogin")
public String toLogin(){
return "login";
}
@RequestMapping("/login")
public String login(String username,String password,Model model){
//获取当前用户数据
Subject subject = SecurityUtils.getSubject();
//封装用户登录数据
UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(username, password);
try {
subject.login(usernamePasswordToken);//执行登录方法
return "index";
}catch (UnknownAccountException e){
//用户名不存在
model.addAttribute("msg","用户名不存在");
return "login";
}catch (IncorrectCredentialsException e){
model.addAttribute("msg","密码不存在");
return "login";
}
}
@RequestMapping("/noauth")
@ResponseBody
public String unauthorized(){
return "未经授权无法访问此页面";
}
@RequestMapping("/logout")
public String logout(){
Subject subject = SecurityUtils.getSubject();
subject.logout();
return "redirect:/login";
}
}
service:
@Service
public interface UserService {
public User queryUserByName(String username);
}
@Service
public class UserServiceImpl implements UserService {
@Autowired
UserMapper userMapper;
@Override
public User queryUserByName(String username) {
return userMapper.queryUserByName(username);
}
}
mapper:
@Repository
@Mapper
public interface UserMapper {
public User queryUserByName(String username);
}
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.sun.mapper.UserMapper">
<select id="queryUserByName" resultType="User" parameterType="String">
select * from user where username=#{username}
</select>
</mapper>
第四步编写shiro的配置
/* shiro三大对象
subject:用户
securityManager:管理所有用户
Realm:连接数据库
*/
@Configuration
public class ShiroConfig {
/*第三步创建shiroFilterFactoryBean*/
@Bean
public ShiroFilterFactoryBean shiroFilterFactoryBean(@Qualifier("defaultWebSecurityManager") DefaultWebSecurityManager defaultWebSecurityManager){
ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
bean.setSecurityManager(defaultWebSecurityManager);
//添加Shiro内置过滤器
/*anon:无需认证就可以访问
* authc:必须认证才能访问
* 必须拥有记住我功能才能用
* perms 拥有对某个资源的权限才能访问
* role:拥有某个角色权限才能访问*/
Map<String, String> filterChainDefinitionMap = new LinkedHashMap();
//添加权限,没有授权会跳转到为授权界面
filterChainDefinitionMap.put("/user/add","perms[user:add]");
filterChainDefinitionMap.put("/user/update","perms[user:update]");
bean.setFilterChainDefinitionMap(filterChainDefinitionMap);
/*设置登录的请求*/
bean.setLoginUrl("/toLogin");
//跳转未授权界面
bean.setUnauthorizedUrl("/noauth");
return bean;
}
/*第二步 创建securityManager*/
@Bean(name = "defaultWebSecurityManager")
public DefaultWebSecurityManager defaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm){
DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();
//关联userRealm
defaultWebSecurityManager.setRealm(userRealm);
return defaultWebSecurityManager;
}
/*第一步创建realm对象 需要自定义类*/
@Bean
public UserRealm userRealm(){
return new UserRealm();
}
//ShiroDialect用来整合shiro与thymeleaf
@Bean
public ShiroDialect shiroDialect(){
return new ShiroDialect();
}
}
shiro的授权认证:
//自定义的UserRealm 继承AuthorizingRealm
public class UserRealm extends AuthorizingRealm {
@Autowired
UserService userService;
//授权
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
System.out.println("执行了授权---doGetAuthorizationInfo");
//
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
//拿到当前这个对象
Subject subject = SecurityUtils.getSubject();
User user = (User) subject.getPrincipal();//拿到当前用户
//设置当前用户权限
info.addStringPermission(user.getPerms());
return info;
}
//认证
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
System.out.println("执行了认证---doGetAuthenticationInfo");
//缓存取用户名密码
UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) authenticationToken;
//用户名密码 数据库中取
User user = userService.queryUserByName(usernamePasswordToken.getUsername());
if (null==user) {
return null;//抛出异常UnknownAccountException
}
//密码认证shiro做
return new SimpleAuthenticationInfo(user, user.getPassword(), "");
}
}
前端thymeleaf整合shiro
index.html:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org"
xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>首页</h1>
<p th:text="${msg}"></p>
<shiro:authenticated>
<a th:href="@{/logout}">退出</a>
</shiro:authenticated>
<shiro:notAuthenticated>
<a th:href="@{/toLogin}">登录</a>
</shiro:notAuthenticated>
<hr>
<div shiro:hasPermission="user:add"><a th:href="@{/user/add}">add</a></div>
<div shiro:hasPermission="user:update"><a th:href="@{/user/update}">update</a></div>
</body>
</html>
login.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<p th:text="${msg}" style="color: red"></p>
<form action="/login">
<p>用户名: <input name="username" type="text"></p>
<p>密码: <input name="password" type="text"></p>
<button type="submit">登录</button>
</form>
</body>
</html>
user/add.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>add</h1>
</body>
</html>
user/update.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>update</h1>
</body>
</html>