一:操作流程:
1.首先创建Controller层编写跳转路径确保html能够正确跳转
2.建立数据库的表->编写pojo->service->serviceImpl->mapper->mapper.xml
3.创建Realm ShiroConfig两个配置文件类,
当用户获取登录到Session时可以在realm文件中进行获取.在Ccontroller层中通过SecurityUtils.getSubject来获取当前用户,
并利用UsernamePasswordToken实例来进行得到代表用户名和密码的token令牌
->当进行subject.login(token)操作登录时,后台会跳转到realm配置类中的AuthenticationInfo认证方法中->进行数据库中的用户名和密码的查询对比
->再次利用SecurityUtils.getSubject来进行session的设置将查询到的信息放入session便于前台获取信息,当认证成功后则进入授权方法中,
//获取当前登录的对象
Subject subject = SecurityUtils.getSubject();
User currentUser = (User) subject.getPrincipal();
info.addStringPermission(currentUser.getPerms());
此三行代码则代表获取当前shiro托管的当前用户的全部信息以此来判定是否得到add 或者update的权限,以此来判断前端显示的选择。
index.xml中
<!--过滤add或者update跳转URL,只存在拥有该权限的URL-->
<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>
<!--从后台获得用户的session-->
<p th:if="${session.loginUser==null}">
<a th:href="@{/toLogin}">登录</a>
</p>
<p th:if="${session.loginUser!=null}">
<a th:href="@{/logout}">登出</a>
</p>
login.html
h1>登录</h1>
<hr>
<p th:text="${msg}" style="color:red;"></p>
<form th:action="@{/login}">
<p>用户名:<label>
<input type="text" name="username">
</label></p>
<p>密码:<label>
<input type="text" name="password">
</label></p>
<p><input type="submit"></p>
</form>
二.导入maven jar包
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
<!--整合thymeleaf包-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!--用户格式化java8 LocalhostTime-->
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-java8time</artifactId>
<version>3.0.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring4</artifactId>
<version>3.0.9.RELEASE</version>
</dependency>
<!--shiro核心包-->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.5.1</version>
</dependency>
<!--mybatis-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.19</version>
</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.21</version>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.2</version>
</dependency>
<!--简化pojo包 可省略get set 构造参数等-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.12</version>
<scope>provided</scope>
</dependency>
<!--日志-->
<!--<dependency>
<groupId>org.bgee.log4jdbc-log4j2</groupId>
<artifactId>log4jdbc-log4j2-jdbc4.1</artifactId>
<version>1.16</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.13</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.13</version>
</dependency>-->
<!--shiro整合thymeleaf-->
<dependency>
<groupId>com.github.theborakompanioni</groupId>
<artifactId>thymeleaf-extras-shiro</artifactId>
<version>2.0.0</version>
</dependency>
</dependencies>
三、整合数据源将其放在application.yml中
spring:
datasource:
url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=GMT%2B8
username: root
password: 123456
driver-class-name: com.mysql.cj.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource
# 数据源其他配置
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,去掉后监控界面sql无法统计,'wall'用于防火墙
filters: stat,wall,log4j
maxPoolPreparedStatementPerConnectionSize: 20
useGlobalDataSourceStat: true
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
四.编写mybaits扫描配置(可放在application.properties中)
//扫描mapper.xml文件
mybatis.mapper-locations=classpath:mapper/*.xml
//自动扫描pojo将其导入mapper.xml文件中
mybatis.type-aliases-package=com.lwg.pojo
五.编写配置UserRealm呵ShiroConfig
1.编写UserRealm类并继承AuthorizationRealm 并重写其中的授权AuthorizationInfo方法以及认证方法AuthenticationInfo方法
2.首先需要编写三个bean ShiroFilterFactoryBean DefaultWebSecurityMannger 前者是来拦截需要安全控制的URL的入口
后者是一个安全控制管理器可以将UserRealm中的认证授权等功能注入其中
代码如下:
package com.lwg.config;
import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
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.LinkedHashMap;
import java.util.Map;
@Configuration
public class ShiroConfig {
//shiroFilterFactoryBean
@Bean
public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("securityManager") DefaultWebSecurityManager defaultWebSecurityManager){
ShiroFilterFactoryBean bean=new ShiroFilterFactoryBean();
//设置安全管理器
bean.setSecurityManager(defaultWebSecurityManager);
//添加shiro的内置过滤器
/*
anon :无需认证即可访问
authc:认证后才可访问
user: 必须拥有 记住我才可访问
perms: 拥有对某个资源的权限才可访问
role:拥有某个角色的权限才可访问
* */
Map<String, String> filterMap=new LinkedHashMap<>();
//授权
filterMap.put("/user/add","perms[user:add]");
filterMap.put("/user/update","perms[user:update]");
//过滤没有登录的页面‘
filterMap.put("/user/*","authc");
//设置登出
filterMap.put("/logout", "logout");
bean.setFilterChainDefinitionMap(filterMap);
//设置登录的请求
bean.setLoginUrl("/toLogin");
//设置跳转未授权限页面
bean.setUnauthorizedUrl("/noAuth");
return bean;
}
//DefaultWebSecurityManger
//@Qualifier注解防止在多个bean引用时出现混乱
@Bean(name = "securityManager")
public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm){
DefaultWebSecurityManager securityManager=new DefaultWebSecurityManager();
securityManager.setRealm(userRealm);
return securityManager;
}
//创建realm对象 自定义类
@Bean
public UserRealm userRealm(){
return new UserRealm();
}
@Bean
//整合thymeleaf
public ShiroDialect getShiroDialect(){
return new ShiroDialect();
}
}
UserRealm代码如下:
package com.lwg.config;
import com.lwg.pojo.User;
import com.lwg.service.UserServiceImpl;
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.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
public class UserRealm extends AuthorizingRealm {
@Autowired
private UserServiceImpl userService;
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
System.out.println("执行了->授权doGetAuthorizationInfo");
//简单的授权实例
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
//所有的都通过的user:add权限
//info.addStringPermission("user:add");
//获取当前登录的对象
Subject subject = SecurityUtils.getSubject();
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 (null==user){
return null;
}
//从当前的用户中获取登录用户的session,并将该session传递给前台
Subject currentSubject = SecurityUtils.getSubject();
Session session = currentSubject.getSession();
session.setAttribute("loginUser",user);
//密码认证 托管给shiro
return new SimpleAuthenticationInfo(user,user.getPwd(),"");
}
}
indexController代码:
package com.lwg.controller;
import org.apache.shiro.SecurityUtils;
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.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class indexController {
@RequestMapping({"/","/index"})
public String toindex(Model model){
model.addAttribute("msg","hello shiro");
return "index";
}
@RequestMapping("/toLogin")
public String toLogin(){
return "login";
}
@RequestMapping("/user/add")
public String add(){
return "user/add";
}
@RequestMapping("/user/update")
public String update(){
return "user/update";
}
@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("/noAuth")
@ResponseBody
public String Unauthorized(){
return "此页面无权限访问";
}
}
service:
package com.lwg.service;
import com.lwg.pojo.User;
public interface UserService {
public User queryUserByName(String name);
}
impl:
package com.lwg.service;
import com.lwg.mapper.UserMapper;
import com.lwg.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class UserServiceImpl implements UserService{
@Autowired
private UserMapper userMapper;
@Override
public User queryUserByName(String name) {
return userMapper.queryUserByName(name);
}
}
mapper:
package com.lwg.mapper;
import com.lwg.pojo.User;
import org.apache.ibatis.annotations.Mapper;
@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.lwg.mapper.UserMapper">
<select id="queryUserByName" parameterType="String" resultType="User">
SELECT * FROM mybatis.user where name = #{name}
</select>
</mapper>
六.shiro的内置过滤器
anon:无需认证即可访问
authc:认证后才可访问(比如登录后才可访问)
user: 必须拥有 记住我才可访问
perms: 拥有对某个资源的权限才可访问
role:拥有某个角色的权限才可访问
其中perms则是授权用户访问add页面或者update页面
//授权
filterMap.put("/user/add",“perms[user:add]”);
filterMap.put("/user/update",“perms[user:update]”);
//过滤没有登录的页面
filterMap.put("/user/*",“authc”);
//设置登出
filterMap.put("/logout", “logout”);
//注入ShiroFilterFactoryBean中得到过滤的用处
bean.setFilterChainDefinitionMap(filterMap);
SimpleAuthorizationInfo实例类简单介绍
SimpleAuthenticationInfo(user,user.getPwd(),"");
第一个参数user
第二个字段是user.getPassword(),注意这里是指从数据库中获取的password。
第三个字段是realm,即当前realm的名称。
这块对比逻辑是先对比username,但是username肯定是相等的,所以真正对比的是password。从这里传入的password(这里是从数据库获取的)和token(filter中登录时生成的)中的password做对比,如果相同就允许登录,不相同就抛出异常。
如果验证成功,最终这里返回的信息authenticationInfo 的值与传入的第一个字段的值相同(我这里传的是user对象)。
同时也可以用SimpleAuthorizationInfo进行权限的过滤
Ex:
//所有的都通过的user:add权限
//info.addStringPermission(“user:add”);
info.addStringPermission(currentUser.getPerms());