整合MyBatis
依赖
<!--shiro整合mybatis-->
<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.22</version>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.1</version>
</dependency>
连接数据库的配置文件
创建application.yml
spring:
datasource:
username: root
password: 123456
url: jdbc:mysql://localhost:3306/mybatis02?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8&useSSL=true
driver-class-name: com.mysql.cj.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource
initial-size: 5
min-idle: 5
max-active: 20
max-wait: 60000
time-between-eviction-runs-millis: 60000
min-evictable-idle-time-millis: 300000
validation-query: SELECT 1 FROM DUAL
test-while-idle: true
test-on-borrow: false
test-on-return: false
pool-prepared-statements: true
filters: stat,wall,log4j
maxPoolPreparedStatementPerConnectionSize: 20
useGlobalDataSourceStat: true
connection-properties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
紧接着,在application.properties
中进行配置
mybatis.type-aliases-package=com.czx.pojo
mybatis.mapper-locations=classpath:mapper/*.xml
整合Thymeleaf
依赖
<!--thymeleaf-shiro的依赖-->
<dependency>
<groupId>com.github.theborakompanioni</groupId>
<artifactId>thymeleaf-extras-shiro</artifactId>
<version>2.0.0</version>
</dependency>
给页面添加头文件
<html lang="en" xmlns:th="http://www.thymeleaf.org">
请求授权实现
创建类,补全项目
根据自己数据库中的信息创建实体,下面是我的项目列表
ShiroConfig
@Configuration
public class ShiroConfig {
//ShiroFilterFactoryBean
@Bean
public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("securityManager") DefaultWebSecurityManager getDefaultWebSecurityManager){
ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
//设置安全管理器
shiroFilterFactoryBean.setSecurityManager(getDefaultWebSecurityManager);
//添加shiro的内置过滤器
/**
* anon:无需认证就能访问
* authc:必须认证才能访问
* user:必须有 记住我 功能才能访问
* perms:拥有对某个资源的权限才能用
* role:拥有某个角色权限才能用
*/
Map<String, String> filterMap = new LinkedHashMap<>();
filterMap.put("/user/add","authc");
filterMap.put("/user/update","authc");
//授权 也就是登录以下的页面需要授权 怎么授权呢 在 Realm 中进行授权
filterMap.put("/user/add","perms[user:add]");
filterMap.put("/user/update","perms[user:update]");
shiroFilterFactoryBean.setFilterChainDefinitionMap(filterMap);
//设置登录的请求
shiroFilterFactoryBean.setLoginUrl("/toLogin");
//设置未经授权的请求
shiroFilterFactoryBean.setUnauthorizedUrl("/noauthc");
return shiroFilterFactoryBean;
}
//DefaultWebSecurity
@Bean(name="securityManager")
public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm){
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
//关联UserRealm
securityManager.setRealm(userRealm);
return securityManager;
}
//创建 Realm 对象
@Bean
public UserRealm userRealm(){
return new UserRealm();
}
//ShiroDialect:用来整合 shiro thymeleaf
@Bean
public ShiroDialect getShiroDialect(){
return new ShiroDialect();
}
}
UserRealm
public class UserRealm extends AuthorizingRealm {
@Autowired
private UserService 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(认证)方法");
//模拟数据库中的数据
// String name = "root";
// String password = "123456";
//连接数据库
UsernamePasswordToken userToken = (UsernamePasswordToken) authenticationToken;
User user = userService.selectByName(userToken.getUsername());
if (user == null){ //没有这个人
return null; //UnknownAccountException
}
//将user放入session中 供前端使用
Subject subject = SecurityUtils.getSubject();
Session session = subject.getSession();
session.setAttribute("loginUser",user);
//密码直接交给shiro来做
return new SimpleAuthenticationInfo(user,user.getPwd(),"");
}
}
MyController
@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 token = new UsernamePasswordToken(username, password);
try {
//执行登录代码
subject.login(token);
return "index";
}catch (UnknownAccountException e){ //用户名错误
model.addAttribute("msg","用户名错误");
return "login";
}catch (IncorrectCredentialsException e){ //密码错误
model.addAttribute("msg","密码错误");
return "login";
}
}
@RequestMapping("/noauthc")
@ResponseBody
public String unauthorized(){
return "未经授权无法访问";
}
}
UserMapper
@Repository
@Mapper
public interface UserMapper {
public User selectByName(String name);
}
User
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private int id;
private String name;
private String pwd;
private String perms;
}
UserService
public interface UserService {
public User selectByName(String name);
}
UserServiceImpl
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public User selectByName(String name) {
return userMapper.selectByName(name);
}
}
UserMapper.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.czx.mapper.UserMapper">
<select id="selectByName" resultType="com.czx.pojo.User">
select * from mybatis02.user where name = #{name};
</select>
</mapper>
index.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org"
xmlns:shiro="http://www.thymeleaf.org/thymeleaf-extras-shiro">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>首页</h1>
<p th:text="${msg}"></p>
<div th:if="${session.loginUser==null}">
<a th:href="@{/toLogin}">登录</a>
</div>
<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>
<h1>登录</h1>
<hr>
<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>
解释
shiro 整合 thymeleaf ,必须要在 ShiroConfig 中添加方法,交给 bean 管理
然后说说 UserRealm ,在 UserRealm 中先执行的是认证,接下来才是授权。在认证部分,我们根据用户传入的账号和密码去数据库中寻找有没有这个人,如果有,返回这个用户,如果没有,返回null。
找到后将这个用户传给授权部分
在授权部分,我们给这个用户权限
那这个 getPerms() 获得的权限是从哪里来的呢?是在 ShiroConfig 中设置的
我们可以看到,user下的 add 和 update 页面都需要被授权了才能访问,那怎么授权呢,这就是我们在数据库中的一个字段perms
,每个用户的这个字段下,有 add 就能访问 add 页面,update 页面同理。
接下来说说登录,没有登录,肯定是不能访问页面的,那该怎么设置呢?没登录的用户想访问页面时,直接跳转到登录页面,就是这么简单
下面是页面的显示问题,当一个用户没登录时,前端页面让它出现登录按钮,登录后按钮消失
登录后,只展示自己能访问的页面
Shiro 框架收官,下篇再见…