预览地址:https://www.ixigua.com/7026306880414679588?logTag=f7052a9353889cecc2d9
gitee:https://gitee.com/caohanzong/springboot-shiro
- 1、环境搭建
- 2、Shiro实现登录拦截
- 3、Shiro实现用户认证
- 4、Shiro整合Mybatis
- 5、Shiro实现用户授权
- 6、Shiro整合Thymeleaf
- 所有代码
1、新建一个springboot项目,勾选Spring Web和Thymeleaf依赖
org.springframework.boot spring-boot-starter-thymeleaf org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-test test
2、测试环境是否正常
- 新建一个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";
}
}
- 新建一个index.html页面
首页
首页
add | update
- 新建一个add.html页面
Title
add
- 新建一个update.html页面
Title
update
-
项目结构
-
运行截图
3、导入shiro整合spring的包
org.apache.shiro
shiro-spring
1.5.3
4、编写导入配置类
- 编写一个自定义类UserRealm
//自定义的UserRealm
public class UserRealm extends AuthorizingRealm {
//授权
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
System.out.println("执行了=>授权doGetAuthorizationInfo");
return null;
}
//认证
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
System.out.println("执行了=>认证doGetAuthenticationInfo");
return null;
}
}
- 编写配置ShiroConfig
1、创建realm对象,需要自定义类
2、DefaultWebSecurityManager
3、ShiroFilterFactoryBean
@Configuration
public class ShiroConfig {
//ShiroFilterFactoryBean : 3
@Bean
public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("getDefaulWebSecurityManager") DefaultWebSecurityManager defaultWebSecurityManager){
ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
//设置安全管理器
bean.setSecurityManager(defaultWebSecurityManager);
return bean;
}
//DefaultWebSecurityManager : 2
@Bean
public DefaultWebSecurityManager getDefaulWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm){
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
//关联UserRealm
securityManager.setRealm(userRealm);
return securityManager;
}
//创建realm对象,需要自定义类 : 1
@Bean
public UserRealm userRealm(){
return new UserRealm();
}
2、Shiro实现登录拦截
- 在ShiroConfig中的getShiroFilterFactoryBean方法中添加如下配置:
//添加shiro的内置过滤器
Map filterMap = new linkedHashMap<>();
filterMap.put("/user/add","authc");
filterMap.put("/user/update","authc");
bean.setFilterChainDefinitionMap(filterMap);
- 再点击首页的add或者update之后,
这是拦截之后的系统默认页面,我们要把这个页面显示一些内容 - 添加拦截成功页面
- 登录页面login.html
登录页面
登录
- 在MyController中添加toLogin
@RequestMapping("/toLogin")
public String toLogin() {
return "login";
}
- 在ShiroConfig中的getShiroFilterFactoryBean方法中添加如下配置
//设置登录的请求,(如果没有登录,点击了有权限的访问)
bean.setLoginUrl("/toLogin");
- 拦截成功页面
- 在MyController中编写用户提交表单之后处理
@RequestMapping("/login")
public String login(String username,String password,Model model){
//获取当前的用户
Subject subject = SecurityUtils.getSubject();
//封装用户的登录数据
UsernamePasswordToken token = new UsernamePasswordToken(username, password);
//执行登录的方法,如果没有异常就ok
//subject.login(token);
try {
subject.login(token);
return "index";
} catch (UnknownAccountException e) { //用户名错误
model.addAttribute("msg","用户名错误");
return "login";
} catch (IncorrectCredentialsException e){ //密码错误
model.addAttribute("msg","密码错误");
return "login";
}
}
- login.html的修改
Title
登录
-
用户输入登录信息
页面:
控制台:
-
用户认证编写UserRealm中的认证(doGetAuthenticationInfo)
//认证
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
System.out.println("执行了=>认证doGetAuthorizationInfo");
// 用户名、密码, 数据中取
String name = "root";
String password = "123456";
UsernamePasswordToken userToken = (UsernamePasswordToken) token;
if (!userToken.getUsername().equals(name)) {
return null;//抛出异常 UnknownAccountException
}
// 密码认证,shiro做
return new SimpleAuthenticationInfo("",password,"");
}
4、Shiro整合Mybatis
1、导入依赖:
org.projectlombok lombok mysql mysql-connector-java log4j log4j 1.2.17 com.alibaba druid 1.1.23 org.mybatis.spring.boot mybatis-spring-boot-starter 2.1.3
2、配置文件application.yml的编写
spring:
datasource:
username: root
password: 123456
#?serverTimezone=UTC解决时区的报错
url: jdbc:mysql://localhost:3306/mybatis?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
mybatis:
type-aliases-package: com.chz.pojo
mapper-locations: classpath:mapper/*.xml
3、User类的编写
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private int id;
private String name;
private String pwd;
private String perms;
}
4、UserMapper.xml映射
select * from mybatis.user where name=#{name}
5、UserService接口实现
public interface UserService {
public User queryUserByName(String name);
}
6、UserServiceImpl业务逻辑
@Service
public class UserServiceImpl implements UserService{
@Autowired
UserMapper userMapper;
@Override
public User queryUserByName(String name) {
return userMapper.queryUserByName(name);
}
}
7、UserRealm连接真实数据库 (config-UserRealm)
//认证
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
System.out.println("执行了=>认证doGetAuthenticationInfo");
UsernamePasswordToken userToken= (UsernamePasswordToken) token;
//用户名,密码 ————数据库中取,连接真实的数据库
User user = userService.queryUserByName(userToken.getUsername());
//没有这个人
if(user==null){
//UnknownAccountException
return null;
}
//密码认证,shiro做
//可以加密:MD5,MD5演唱、盐值加密
return new SimpleAuthenticationInfo(user,user.getPwd(),"");
}
5、Shiro实现用户授权
1、ShiroConfig中的getShiroFilterFactoryBean方法添加认证代码
//授权,正常情况下,未授权会跳转到未授权页面
filterMap.put("/user/add","perms[user:add]");
filterMap.put("/user/update","perms[user:update]");
2、登录之后点击add按钮会弹出如下页面
3、添加为授权页面
- MyController
@RequestMapping("/noauth")
@ResponseBody
public String unauthorized(){
return "未经授权无法访问此页面";
}
- ShiroConfig中的getShiroFilterFactoryBean方法中添加
//未授权页面
bean.setUnauthorizedUrl("/noauth");
- 再次测试
所以需要在UserRealm中为用户进行真正授权
4、UserRealm类的修改
//自定义的UserRealm
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 currentUser = (User) subject.getPrincipal();
//设置当前用户的权限
info.addStringPermission(currentUser.getPerms());
return info;
}
//认证
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
System.out.println("执行了=>认证doGetAuthenticationInfo");
UsernamePasswordToken userToken= (UsernamePasswordToken) token;
//用户名,密码 ————数据库中取,连接真实的数据库
User user = userService.queryUserByName(userToken.getUsername());
//没有这个人
if(user==null){
//UnknownAccountException
return null;
}
//密码认证,shiro做
//可以加密:MD5,MD5演唱、盐值加密
return new SimpleAuthenticationInfo(user,user.getPwd(),"");
}
}
5、再次测试
1、shiro-thymeleaf整合包导入
com.github.theborakompanioni thymeleaf-extras-shiro 2.0.0
2、在ShiroConfig中整合ShiroDialect
// 整合ShiroDialect: 用来整合 Shiro thymeleaf
@Bean
public ShiroDialect getShiroDialect() {
return new ShiroDialect();
}
3、index.html页面
首页
首页
4、页面显示
没有add,只有update
ShiroConfig
package com.chz.config;
import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import org.apache.shiro.authc.UsernamePasswordToken;
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 java.util.HashMap;
import java.util.linkedHashMap;
import java.util.List;
import java.util.Map;
@Configuration
public class ShiroConfig {
//ShiroFilterFactoryBean : 3
@Bean
public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("getDefaulWebSecurityManager") DefaultWebSecurityManager defaultWebSecurityManager){
ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
//设置安全管理器
bean.setSecurityManager(defaultWebSecurityManager);
//添加shiro的内置过滤器
//拦截
Map filterMap = new linkedHashMap<>();
//user下的add、update,authc
//filterMap.put("/user/add","authc");
//filterMap.put("/user/update","authc");
//授权,正常情况下,未授权会跳转到未授权页面
filterMap.put("/user/add","perms[user:add]");
filterMap.put("/user/update","perms[user:update]");
filterMap.put("/user/*","authc");
bean.setFilterChainDefinitionMap(filterMap);
//设置登录的请求,(如果没有登录,点击了有权限的访问)
bean.setLoginUrl("/toLogin");
//未授权页面
bean.setUnauthorizedUrl("/noauth");
return bean;
}
//DefaultWebSecurityManager : 2
@Bean
public DefaultWebSecurityManager getDefaulWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm){
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
//关联UserRealm
securityManager.setRealm(userRealm);
return securityManager;
}
//创建realm对象,需要自定义类 : 1
@Bean
public UserRealm userRealm(){
return new UserRealm();
}
//整合ShiroDialect: 用来整合 shiro thymeleaf
@Bean
public ShiroDialect getShiroDialect(){
return new ShiroDialect();
}
UserRealm
package com.chz.config;
import com.chz.pojo.User;
import com.chz.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
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;
import java.net.Authenticator;
//自定义的UserRealm
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 currentUser = (User) subject.getPrincipal();
//设置当前用户的权限
info.addStringPermission(currentUser.getPerms());
return info;
}
//认证
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
System.out.println("执行了=>认证doGetAuthenticationInfo");
UsernamePasswordToken userToken= (UsernamePasswordToken) token;
//用户名,密码 ————数据库中取,连接真实的数据库
User user = userService.queryUserByName(userToken.getUsername());
//没有这个人
if(user==null){
//UnknownAccountException
return null;
}
//密码认证,shiro做
//可以加密:MD5,MD5演唱、盐值加密
return new SimpleAuthenticationInfo(user,user.getPwd(),"");
}
}
MyController
package com.chz.controller;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.lang.model.element.NestingKind;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@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);
//执行登录的方法,如果没有异常就ok
//subject.login(token);
try {
subject.login(token);
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(HttpServletResponse response) throws IOException {
Subject subject = SecurityUtils.getSubject();
subject.logout();
return "index";
}
}
index.html
首页
首页
login.html
Title
登录



