springboot集成shiro
springboot实现shiro
1、导入依赖
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.12</version>
</dependency>
<!-- shiro-->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.10.1</version>
</dependency>
<dependency>
<groupId>com.github.theborakompanioni</groupId>
<artifactId>thymeleaf-extras-shiro</artifactId>
<version>2.0.0</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>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.2</version>
</dependency>
2、配置Druid数据源和mybatis
spring:
datasource:
username: xiaofan
password: 123456
url: jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=utf-8
driver-class-name: com.mysql.cj.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource
#Spring Boot 默认是不注入这些属性值的,需要自己绑定
#druid 数据源专有配置
initialSize: 5
minIdle: 5
maxActive: 25
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.Priority
#则导入 log4j 依赖即可,Maven 地址:https://mvnrepository.com/artifact/log4j/log4j
filters: stat,wall,log4j
maxPoolPreparedStatementPerConnectionSize: 20
useGlobalDataSourceStat: true
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
mybatis:
type-aliases-package: com.fan.pojo
mapper-locations: classpath:mapper/*.xml
3、连接数据库,编写实体类pojo
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private int id;
private String name;
private String pwd;
private String perms;
}
4、编写mapper接口
@Repository
@Mapper
public interface UserMapper {
public User queryUserByName(String name);
}
4、编写mapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.fan.mapper.UserMapper">
<select id="queryUserByName" resultType="com.fan.pojo.User">
select * from user where name = #{name}
</select>
</mapper>
5、编写service层
public interface UserService {
public User queryUserByName(String name);
}
@Service
public class UserServiceImpl implements UserService{
@Autowired
private UserMapper userMapper;
@Override
public User queryUserByName(String name) {
return userMapper.queryUserByName(name);
}
}
6、编写controller层
@Controller
public class MyController {
@RequestMapping({"/","/index"})
public String toIndex(Model model){
model.addAttribute("info","hello,shiro");
return "index";
}
@RequestMapping("/add")
public String add(){
return "/user/add";
}
@RequestMapping("/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 token = new UsernamePasswordToken(username, password);
// 执行登录
try {
subject.login(token);
return "index";
}catch (UnknownAccountException e){//用户名不存在
model.addAttribute("info","用户名错误");
return "login";
}catch (IncorrectCredentialsException e){//密码不存在
model.addAttribute("info","密码错误");
return "login";
}
}
@RequestMapping("/unauthorized")
@ResponseBody
public String unauthorized(){
return "未经授权无法访问此页面";
}
}
7、编写shiro配置类,UserRealm负责处理数据库取出的数据
subject 用户
securityManager 管理所有用户
Realm 连接数据
public class UserRealm extends AuthorizingRealm {
@Autowired
UserServiceImpl userService;
// 授权
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
System.out.println("执行了=>授权doGetAuthorizationInfo");
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
// 拿到当前当前这个对象
Subject subject = SecurityUtils.getSubject();
User currentUser =(User) subject.getPrincipal();//拿到认证时传的user对象
info.addStringPermission(currentUser.getPerms());
return info;
}
// 认证
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
System.out.println("执行了=>认证doGetAuthenticationInfo");
UsernamePasswordToken token=(UsernamePasswordToken)authenticationToken;
// 连接数据库
User user = userService.queryUserByName(token.getUsername());
if(user==null){
return null;//抛出异常-->UnknownAccountException
}
// 密码认证,shiro做 shiro也能密码加密
return new SimpleAuthenticationInfo(user,user.getPwd(),"");
}
}
8、编写shiro配置类
@Configuration
public class ShiroConfig {
// shiroFilterBean 第三步
@Bean
public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("securityManager") DefaultWebSecurityManager defaultWebSecurityManager){
ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
// 设置安全管理器
bean.setSecurityManager(defaultWebSecurityManager);
// 添加shiro过滤器,拦截的必须是controller下的请求
/*
anon: 无需认证就可以访问
authc: 必须认证了才能访问
user: 必须拥有 记住我 才能用
perms: 拥有对某个资源的权限才能访问
role: 拥有的某个角色的权限才能访问
*/
HashMap<String, String> filterChainDefinitionMap = new LinkedHashMap<>();
// 拦截
// filterChainDefinitionMap.put("/add","anon");
// filterChainDefinitionMap.put("/update","authc");
// 授权 正常情况下跳的未授权的页面,401
filterChainDefinitionMap.put("/add","perms[user:add]");
filterChainDefinitionMap.put("/update","perms[user:update]");
bean.setFilterChainDefinitionMap(filterChainDefinitionMap);
// 设置登录的请求
bean.setLoginUrl("/toLogin");
// 设置未授权页面请求
bean.setUnauthorizedUrl("/unauthorized");
return bean;
}
// defaultWebSecurityManager 第二步
// 像是bean里面的ref引用注入
@Bean(value = "securityManager")
public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm){
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
//关联UserRealm
securityManager.setRealm(userRealm);
return securityManager;
}
// realm,需要自定义 第一步
@Bean(value = "userRealm")
public UserRealm userRealm(){
return new UserRealm();
}
// 整合shiroDialect 用来整合shiro thymeleaf
@Bean
public ShiroDialect getShiroDialect(){
return new ShiroDialect();
}
9、编写前端html页面,并整合shiro thymeleaf
add.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>add</h1>
</body>
</html>
update.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>update</h1>
</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>
<h1>登录</h1>
<hr>
<p th:text="${info}" style="color: red"></p>
<form th:action="@{/login}">
<label>用户名:</label>
<input type="text" name="username">
<label>密码:</label>
<input type="text" name="password">
<input type="submit" value="登录">
</form>
</body>
</html>
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="${info}"></p>
<hr>
<div shiro:notAuthenticated="">
<a th:href="@{/toLogin}">登录</a>
</div>
<div shiro:hasPermission="'user:add'">
<a th:href="@{/add}">add</a>
</div>
<div shiro:hasPermission="'user:update'">
<a th:href="@{/update}">update</a>
</div>
</body>
</html>
10、测试







浙公网安备 33010602011771号