springboot 整合 Shiro
发布于: 2021 年 01 月 13 日
1.创建一个 springboot 项目
选中 web 和 thymeleaf
1.1 新建 index.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>首页</h1>
<p th:text="${msg}"></p>
</body>
</html>
复制代码
1.2 创建一个 controller
package com.yao.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class MyController {
@RequestMapping({"/","/index"})
public String toIndex(Model model){
model.addAttribute("msg","hello,Shiro");
return "index";
}
}
复制代码
一定要记住 shiro 的三大对象
1.subject:用户
2.SecurityManager:管理所有用户
3.Realm:连接数据
1.3 导入整合用的依赖包
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.4.1</version>
</dependency>
复制代码
1.4 创建一个 config(ShiroConfig),并编写他
package com.yao.config;
import org.springframework.context.annotation.Configuration;
@Configuration
public class ShiroConfig {
//ShiroFilterFactoryBean
//DefaultWebSecurityManager
//创建 realm 对象,这个realm对象需要自定义
}
复制代码
1.5 创建自己的一个 realmconfig,也就是在 config 中创建另外一个配置类 UserRealm
package com.yao.config;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
//自定义的 UserRealm
public class UserRealm extends AuthorizingRealm {
//授权
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
System.out.println("授权。。。");
return null;
}
//认证
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
System.out.println("认证。。。");
return null;
}
}
复制代码
1.6 将 UserRealm 注册到 ShiroConfig 里面去,是我们自己写的这个类被 spring 托管
1.7 新建两个测试页面并重新写一下 index 页面
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>
复制代码
index.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>首页</h1>
<p th:text="${msg}"></p>
<hr>
<a th:href="@{/user/add}">add</a> | <a th:href="@{/user/update}">update</a>
</body>
</html>
复制代码
1.8 编写 controller 层
package com.yao.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@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";
}
}
复制代码
1.9 添加过滤器
还是在 shiroconfig 中加入:
//添加Shiro的内置过滤器
/*
anon:无需认证就可以访问
authc:必须认证了才能通过
user:必须拥有记住我功能才能用
perms:拥有对某个资源的权限才可以访问
role:拥有某个角色权限才能访问
*/
Map<String,String> filterMap = new LinkedHashMap<>();
// filterMap.put("/user/add","authc");
// filterMap.put("/user/update","authc");
filterMap.put("/user/*","authc");
bean.setFilterChainDefinitionMap(filterMap);
//设置登录的请求
bean.setLoginUrl("/toLogin");
return bean;
复制代码
这里希望没有认证就从 add 和 update 跳到 login 页面因此还要写一个 login 页面和改写 controller
controller 层:
@RequestMapping("/toLogin")
public String toLogin(){
return "login";
}
复制代码
login 页面:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>登录</title>
</head>
<body>
<form>
<p>用户名: <input type="text" name="username"></p>
<p>密码:<input type="text" name="password"></p>
<p><input type="submit"></p>
</form>
</body>
</html>
复制代码
1.10 上面已经完成了页面拦截的功能接下来实现用户认证的工作
login.html:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>登录</title>
</head>
<body>
<p th:text="${msg}" style="color: red"></p>
<form th:action="@{/login}">
<p>用户名: <input type="text" name="username"></p>
<p>密码:<input type="text" name="password"></p>
<p><input type="submit"></p>
</form>
</body>
</html>
复制代码
controller:
@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);// 执行登陆的方法,如果没有异常就ok了
return "index";
} catch (UnknownAccountException e) {
model.addAttribute("msg","用户名错误");
return "login";
} catch (IncorrectCredentialsException e){
model.addAttribute("msg"," 密码错误");
return "login";
}
}
复制代码
UserRealm:
//认证
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
System.out.println("认证。。。");
//用户名,密码 数据库中取
String name = "root";
String password = "123456";
UsernamePasswordToken userToken = (UsernamePasswordToken) token;
if(!userToken.getUsername().equals(name)){
return null;//它这里会自动抛出前面的用户名错误的异常
}
//密码认证不让你做,它自己做,他不让你接触密码
return new SimpleAuthenticationInfo("",password,"");
}
}
复制代码
直接测试即可发现以上功能基本实现。
package com.yao.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class MyController {
@RequestMapping({"/","/index"})
public String toIndex(Model model){
model.addAttribute("msg","hello,Shiro");
return "index";
}
}
复制代码
2.springboot 整合 mybatis
2.1 导入依赖
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</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.1.12</version>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.0</version>
</dependency>
复制代码
2.2 编写配置文件 application.yml
spring:
datasource:
username: root
password: 892095368llq
#?serverTimezone=UTC解决时区的报错
url: jdbc:mysql://localhost:3306/yao?serverTimezone=UTC&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: 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.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
复制代码
2.3 编写配置文件 application.properties 并新建 mapper 文件夹
application.properties
mybatis.type-aliases-package=com.yao.pojo
mybatis.mapper-locations=classpath:mapper/*.xml
复制代码
2.4 创建 pojo 层,并配置 lombok
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.10</version>
</dependency>
复制代码
编写一个 User.java
package com.yao.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private int id;
private String name;
private String pwd;
}
复制代码
2.4 创建 mapper 层,并写出相对应的 mapper 接口和 resources 中的对应的 mapper 实现
UserMapper 接口
package com.yao.mapper;
import com.yao.pojo.User;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;
@Repository
@Mapper
public interface UserMapper {
public User queryUserByName(String name);
}
mapper。xml
<?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.yao.mapper.UserMapper">
<select id="queryUserByName" parameterType="String" resultType="User">
select * from user where name = #{name}
</select>
</mapper>
复制代码
UserService.interface
package com.yao.service;
import com.yao.pojo.User;
public interface UserService {
public User queryUserByName(String name);
}
UserServiceImpl.java
package com.yao.service;
import com.yao.mapper.UserMapper;
import com.yao.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class UserServiceImpl implements UserService{
@Autowired
UserMapper userMapper;
@Override
public User queryUserByName(String name) {
return userMapper.queryUserByName(name);
}
}
复制代码
2.6 在 test 中测试
package com.yao;
import com.yao.service.UserService;
import com.yao.service.UserServiceImpl;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class ShiroSpringbootApplicationTests {
@Autowired
UserServiceImpl userService;
@Test
void contextLoads() {
System.out.println(userService.queryUserByName("幺幺"));
}
}
复制代码
测试成功,继续写
2.7 更改 UserRealm
package com.yao.config;
import com.yao.pojo.User;
import com.yao.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
//自定义的 UserRealm
public class UserRealm extends AuthorizingRealm {
@Autowired
UserService userService;
//授权
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
System.out.println("授权。。。");
return null;
}
//认证
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
System.out.println("认证。。。");
UsernamePasswordToken userToken = (UsernamePasswordToken) token;
//连接真实数据库
User user = userService.queryUserByName(userToken.getUsername());
if (user==null){
return null;
}
//密码认证不让你做,它自己做,他不让你接触密码
return new SimpleAuthenticationInfo("",user.getPwd(),"");
}
}
复制代码
2.8 添加密码加密
//还有一个md5加密,集成了hashcode是不可逆的
//比如你的密码是123456
// md5(123456,32) = e10adc3949ba59abbe56e057f20f883e
// md5(123456,16) = 49ba59abbe56e057
//MD5盐值加密e10adc3949ba59abbe56e057f20f883eusername
//密码认证不让你做,它自己做,他不让你接触密码
return new SimpleAuthenticationInfo("",user.getPwd(),"");
复制代码
2.10 绑定 thymeleaf
package com.yao.mapper;
import com.yao.pojo.User;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;
@Repository
@Mapper
public interface UserMapper {
public User queryUserByName(String name);
}
复制代码
推荐阅读
看完三件事
如果你觉得这篇内容对你还蛮有帮助,我想邀请你帮我三个小忙:
点赞,转发,有你们的 『点赞和评论』,才是我创造的动力。
关注公众号 『 Java 斗帝 』,不定期分享原创知识。
同时可以期待后续文章 ing🚀
划线
评论
复制
发布于: 2021 年 01 月 13 日阅读数: 39
Java架构师迁哥
关注
还未添加个人签名 2020.09.07 加入
还未添加个人简介
评论