🌻🌻目录
一、Shiro 概述
1.1、什么是 Shiro
- Apache Shiro 是 Java 的一个安全(权限)框架;
- Shiro 可以非常容易的开发出足够好的应用,其不仅可以用在 JavaSE 环境,也可以用在 JavaEE 环境。
- Shiro可以完成:认证、授权、加密、会话管理、与Web集成、缓存等
Shiro 官网
1.2、有哪些功能
Authentication
:身份认证/登录,验证用户是不是拥有相应的身份Authorization
:授权,及权限验证,验证某个已认证的用户是否拥有某个权限;即判断用户是否能做事情,常见的如:验证某个用户是否拥有某个角色.或者细粒度的验证某个用户对某个资源是否具有某个权限Session Manager
:会话管理,即用户登陆后就是一次会话,在没有退出之前,它的所有信息都在会话中;会话可以是普通JavaSE环境的,也可以是如Web环境的Cryptography
:加密,保护数据的安全性,如密码加密存储到数据库,而不是明文存储Web Support
:Web支持,可以非常容易的集成到Web环境Caching
:缓存Concurrency
:shiro支持多线程应用的并发验证,即如在一个线程中开启另一个线程,能把权限自动传播过去Testing
:提供测试支持Run As
:允许一个用户假装为另一个用户(如果他们允许)的身份进行访问Remember Me
:记住我
Shiro不会去维护用户、维护权限;这些需要我们自己去设计/提供;然后通过相应的接口注入给Shiro
1.3 Shiro架构 (Shiro外部来看)
从外部有来看Shiro,即从应用程序角度的来观察如何使用Shiro完成工作:
- Subject: 应用代码直接交互的对象是Subject,也就是说Shiro的对外API核心就是Subject.Subject代表了当前"用户",这个用户不一定是一个具体的人,与当前应用交互的任何东西都是Subject,如网络爬虫、机器人等;与Subject的所有交互都会委托给SecurityManager;Subject其实是一个门面,SecurityManager才是实际的执行者
- SecurityManager:安全管理器;即所有与安全有关的操作都会与SecurityManager交互;且其管理着所有Subject;可以看出它是Shiro的核心,它负责与Shiro的其他组件进行交互,它相当于SpringMVC中DispatcherServlet的角色
- Realm:Shiro从Realm获取安全数据(如用户、角色、权限),就是说SecurityManager要验证用户身份,name它需要从Realm获取响应的用户进行比较以确定用户身份是否合法;也需要从Realm得到用户相应的角色/权限进行验证用户是否能进行操作;也可以把Realm看成DataSource
1.4 Shiro 架构(Shiro内部来看)
- Subject:任何可以与应用交互的"用户"
- SecurityManager:相当与SpringMVC中的DispatcherServlet;是Shiro的心脏;所有具体的交互都通过SecurityManager进行控制;它管理着所有Subject、且负责进行认证、授权、会话及缓存的管理
- Authenticator: 负责Subject认证,是一个扩展点,可以自定义实现;可以使用认证策略(Authentication Strategy),即什么情况下算用户认证通过了
- Authorizer: 授权器、即访问控制器,用来决定主题是否有权限进行相应的操作;即控制着用户能访问应用中的哪些功能
- Realm:可以有一个或多个Realm,可以认为是安全实体数据源,即用户获取安全实体的;可以是JDBC实现,也可以是内存实现等等;由用户提供;所以一般在应用中都需要实现自己的Realm
- SessionManager: 管理Session生命周期的组件;而Shiro并不仅仅可以用在Web环境,也可以用在如普通的JavaSE环境
- CacheManager: 缓存控制器,来管理如用户、角色、权限等的缓存的;因为这些数据基本上很少改变,放在缓存中可以提供访问的性能
- Cryptography: 密码模块,Shiro提高了一些常见的加密组件用于如密码加密/解密
二、HelloWorld
- 查看官网文档: Shiro官网
- 官方的 quickstart:
这个是我 shiro-main 官网下载的也可以直接用
- 创建一个maven父工程
springboot-08-shiro
,用于学习Shiro,删掉不必要的东西src
- 创建一个普通的Maven子工程:
hello-shiro
- 根据官方文档,我们来导入Shiro的依赖
copy 所有的依赖到 shiro-hello / pom.xml中
都没有版本但是就添加个下面的版本就可以
<!-- https://mvnrepository.com/artifact/org.apache.shiro/shiro-core -->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>1.9.1</version>
</dependency>
完整依赖:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>springboot-08-shiro</artifactId>
<groupId>com.zql</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>shiro-hello</artifactId>
<dependencies>
<!-- https://mvnrepository.com/artifact/org.apache.shiro/shiro-core -->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>1.9.1</version>
</dependency>
<!-- configure logging -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>1.7.21</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.21</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
</dependencies>
</project>
- 在 resources下面创建
log4j2.xml
或log4j.properties
并 copy下面日志文件
log4j.properties
log4j.rootLogger=INFO, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m %n
# General Apache libraries
log4j.logger.org.apache=WARN
# Spring
log4j.logger.org.springframework=WARN
# Default Shiro logging
log4j.logger.org.apache.shiro=INFO
# Disable verbose logging
log4j.logger.org.apache.shiro.util.ThreadContext=WARN
log4j.logger.org.apache.shiro.cache.ehcache.EhCache=WARN
- 在 resources下面创建
shiro.ini
并 copy下面文件,注:记得idea中需要安装 ini插件哦,才会高亮显示;
[users]
# user 'root' with password 'secret' and the 'admin' role
root = secret, admin
# user 'guest' with the password 'guest' and the 'guest' role
guest = guest, guest
# user 'presidentskroob' with password '12345' ("That's the same combination on
# my luggage!!!" ;)), and role 'president'
presidentskroob = 12345, president
# user 'darkhelmet' with password 'ludicrousspeed' and roles 'darklord' and 'schwartz'
darkhelmet = ludicrousspeed, darklord, schwartz
# user 'lonestarr' with password 'vespa' and roles 'goodguy' and 'schwartz'
lonestarr = vespa, goodguy, schwartz
# -----------------------------------------------------------------------------
# Roles with assigned permissions
#
# Each line conforms to the format defined in the
# org.apache.shiro.realm.text.TextConfigurationRealm#setRoleDefinitions JavaDoc
# -----------------------------------------------------------------------------
[roles]
# 'admin' role has all permissions, indicated by the wildcard '*'
admin = *
# The 'schwartz' role can do anything (*) with any lightsaber:
schwartz = lightsaber:*
# The 'goodguy' role is allowed to 'drive' (action) the winnebago (type) with
# license plate 'eagle5' (instance specific id)
goodguy = winnebago:drive:eagle5
- 直接 copy到 java下面运行即可
/**
* @Author:Daniel
* @Version 1.0
*/
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.Factory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Simple Quickstart application showing how to use Shiro's API.
*
* @since 0.9 RC2
*/
public class Quickstart {
private static final transient Logger log = LoggerFactory.getLogger(Quickstart.class);
public static void main(String[] args) {
Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
SecurityManager securityManager = factory.getInstance();
SecurityUtils.setSecurityManager(securityManager);
// Now that a simple Shiro environment is set up, let's see what you can do:
// get the currently executing user:
//获取当前的用户对象
Subject currentUser = SecurityUtils.getSubject();
// Do some stuff with a Session (no need for a web or EJB container!!!)
//通过当前用户拿到session
Session session = currentUser.getSession();
session.setAttribute("someKey", "aValue");
String value = (String) session.getAttribute("someKey");
if (value.equals("aValue")) {
log.info("Retrieved the correct value! [" + value + "]");
}
//判断当前用户是否被认证
//Token:没有获取,直接设置令牌
if (!currentUser.isAuthenticated()) {
UsernamePasswordToken token = new UsernamePasswordToken("lonestarr", "vespa");
token.setRememberMe(true);//设置记住我
try {
currentUser.login(token);//执行登录操作
} catch (UnknownAccountException uae) {
log.info("There is no user with username of " + token.getPrincipal());
} catch (IncorrectCredentialsException ice) {
log.info("Password for account " + token.getPrincipal() + " was incorrect!");
} catch (LockedAccountException lae) {
log.info("The account for username " + token.getPrincipal() + " is locked. " +
"Please contact your administrator to unlock it.");
}
// ... catch more exceptions here (maybe custom ones specific to your application?
catch (AuthenticationException ae) {
//unexpected condition? error?
}
}
//say who they are:
//print their identifying principal (in this case, a username):
log.info("User [" + currentUser.getPrincipal() + "] logged in successfully.");
//test a role:
if (currentUser.hasRole("schwartz")) {
log.info("May the Schwartz be with you!");
} else {
log.info("Hello, mere mortal.");
}
//粗粒度
//test a typed permission (not instance-level)
if (currentUser.isPermitted("lightsaber:wield")) {
log.info("You may use a lightsaber ring. Use it wisely.");
} else {
log.info("Sorry, lightsaber rings are for schwartz masters only.");
}
//细粒度
//a (very powerful) Instance Level permission:
if (currentUser.isPermitted("winnebago:drive:eagle5")) {
log.info("You are permitted to 'drive' the winnebago with license plate (id) 'eagle5'. " +
"Here are the keys - have fun!");
} else {
log.info("Sorry, you aren't allowed to drive the 'eagle5' winnebago!");
}
//注销
//all done - log out!
currentUser.logout();
//结束
System.exit(0);
}
}
看到能打印出这行信息,说明快如入门成功
测试运行结果显示:
三、springboot 整合 shiro
3.1 环境搭建
文章最终结构(可以到最后参考):
- 在父工程 springboot-08-shiro 下面新建一个 moudle叫
shiro-springboot
- 勾选spring web依赖即可
- 在 pom.xml 中导入 thymeleaf 依赖
<!-- thymeleaf模板-->
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring5</artifactId>
</dependency>
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-java8time</artifactId>
</dependency>
新建一个包 controller
编写一个 MyController.java
测试,代码如下:
package com.zql.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* @Author:Daniel
* @Version 1.0
*/
@Controller
public class MyController {
@RequestMapping({"/","/index"})
public String toIndex(Model model){
model.addAttribute("msg","hello-shiro-springboot");
return "index";
}
}
- 在 templates下新建一个
index.html
,导入thymeleaf约束,这样可以编写thymeleaf提示
xmlns:th="http://www.themeleaf.org"
index.html完整代码如下:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.themeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>首页</h1>
<p th:text="${msg}"></p>
</body>
</html>
- 运行项目检查
http://localhost:8080/index
或http://localhost:8080
可以看到可以跑通!
shiro的三大对象:
- Subject:用户
- SecurityManager:管理所有用户
- Realm:连接数据
3.2 springboot 整合 shiro
- pom.xml导入依赖:
<!--shiro整合包-->
<!-- https://mvnrepository.com/artifact/org.apache.shiro/shiro-spring -->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.9.1</version>
</dependency>
- 创建一个
config
包,因为配置涉及到userRealm,这个需要自己自定义,所以在config包下先写一个UserRealm
类
代码如下:
package com.zql.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;
/**
* @Author:Daniel
* @Version 1.0
*/
//自定义的 UserReal
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;
}
}
- 再在config包下编写
ShiroConfig.java
配置类
代码如下:
package com.zql.config;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.PathVariable;
/**
* @Author:Daniel
* @Version 1.0
*/
@Configuration
public class ShiroConfig {
//ShiroFilterFactoryBean
@Bean
public ShiroFilterFactoryBean shiroFilterFactoryBean(@PathVariable("userRealm") DefaultWebSecurityManager defaultWebSecurityManager){
ShiroFilterFactoryBean filterFactoryBean = new ShiroFilterFactoryBean();
//设置安全管理器
filterFactoryBean.setSecurityManager(defaultWebSecurityManager);
return filterFactoryBean;
}
//DefaultWebSecurityManager 2
@Bean("securityManager")
public DefaultWebSecurityManager getDefaultWebSecurityManager(@PathVariable("userRealm") UserRealm userRealm){
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
//关联 userRealm
securityManager.setRealm(userRealm);
return securityManager;
}
// Realm:创建realm对象,需要自定义:第一步,从后往前配置 1
@Bean
public UserRealm userRealm(){
return new UserRealm();
}
}
- 在templates建一个
user
夹放关于用户的页面:add.html
;update:html
5. 回到 MyController.java
添加两个页面跳转的方法
@RequestMapping("/user/add")
public String add(Model model){
model.addAttribute("msg","add");
return "user/add";
}
@RequestMapping("/user/update")
public String update(Model model){
model.addAttribute("msg","update");
return "user/update";
}
- 回到主页index.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.themeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>首页</h1>
<p th:text="${msg}"></p>
<p>
<a th:href="@{user/add}">add</a>
| <a th:href="@{user/update}">update</a>
</p>
</body>
</html>
-
再次重启项目检查
-
可以实现跳转add和update页面
到此环境搭建完成!
四、shiro 实现登陆拦截
- 在 ShiroConfig 添加 shiro 的内置过滤器
// 添加shiro的内置过滤器
/*
* anon:无需认证都可访问
* authc: 必须认证了才能访问
* user:必须拥有 记住我 才能用
* perms:拥有对某个资源的权限才能访问
* role:拥有某个角色权限才能访问*/
Map<String, String> filterChainDefinitionMap = new LinkedHashMap<>();
filterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap); //点击源码进去
/* filterChainDefinitionMap.put("/user/add","authc");
filterChainDefinitionMap.put("/user/update","authc");*/
//filterMap.put("/user/*","authc");拦截所有user下的请求
- 再次运行项目点击add,发现失败,此时拦截已经成功了
3. 因为它跳转的url是login页面,所以还得在templates下面重写login
页面
代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
登录:
<form action="/toLogin" method="post">
<p>用户名<input type="text" name="username"></p>
<p>密码<input type="text" name="password"></p>
<p><input type="submit"></p>
</form>
</body>
</html>
- MyController 添加方法
@RequestMapping("/toLogin")
public String toLogin(){
return "login";
}
- 配置登录页面
filterFactoryBean.setLoginUrl("/toLogin");
6. 点击add或者update已经跳转到了登录页面,说明已经拦截成功!
五、shiro 实现用户认证
- 在MyController添加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); //执行登录方法,如果没有异常就说明ok
return "index";
}catch (UnknownAccountException e){
model.addAttribute("msg","用户名不存在"); //用户名不存在
return "login";
}catch (IncorrectCredentialsException e){
model.addAttribute("msg","密码错误");//密码不存在
return "login";
}
}
- 在login.html写入信息msg
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.themeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
登录:
<p th:text="${msg}" style="color: red"></p>
<form th:action="@{/login}" method="post">
<p>用户名<input type="text" name="username"></p>
<p>密码<input type="text" name="password"></p>
<p><input type="submit"></p>
</form>
</body>
</html>
- 启动项目随便登录测试一下
- 在UserRealm代码下修改认证代码:
//认证
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
//System.out.println("执行了=>授权doGetAuthenticationInfo");
// 用户名,密码到数据库中取
String username = "root";
String password = "123";
UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) authenticationToken;
if(!usernamePasswordToken.getUsername().equals(username)){
return null; //抛出异常:UnknownAccountException
}
// 密码认证:shiro做
return new SimpleAuthenticationInfo("",password,"");
}
-
重启项目查看,登录写的数据
-
可以看到登陆成功
六、shiro 整合 mybatis
- 在 pom.xml 导入对应的依赖
<!--整合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.2.6</version>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.4</version>
</dependency>
- 在resource目录下新建
application.yaml
配置文件
spring:
datasource:
username: root
password: root
url: jdbc:mysql://localhost:3306/springboot?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai
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:日志记录(需要导入log4j依赖)
# wall:防御sql注入
filters: stat,wall,log4j
maxPoolPreparedStatementPerConnectionSize: 20
useGlobalDataSourceStat: true
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
- 新建数据库连接绑定 springboot 的数据库
- application.properties文件里配置mybatis的相关设置
mybatis.type-aliases-package=com.zql.pojo
mybatis.mapper-locations=classpath:mapper/*.xml
- 由于配置文件里多了别名的扫描和mapper的文件,所以要完整架构,新建一个pojo实体类和mapper的包,如下
pojo实体类为了方便代码简洁,我使用了lombok,在pom导入对应依赖即可
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
实体类如下: User.java
package com.zql.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* @Author:Daniel
* @Version 1.0
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private int id;
private String name;
private String pwd;
}
- 编写mapper 接口
UserMapper.java
package com.zql.mapper;
import com.zql.pojo.User;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;
/**
* @Author:Daniel
* @Version 1.0
*/
@Repository
@Mapper
public interface UserMapper {
public User queryByName(String name);
}
- 再 resources下面创建文件夹
mapper
接着编写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.zql.mapper.UserMapper">
<select id="queryByName" parameterType="String" resultType="user" >
select * from user where name=#{name }
</select>
</mapper>
- 在新建
service
包接着写一个UserService接口和它的实现类
UserService.java
package com.zql.service;
import com.zql.pojo.User;
/**
* @Author:Daniel
* @Version 1.0
*/
public interface UserService {
public User queryByName(String name);
}
- UserMapperImpl实现类代码:
package com.zql.service.impl;
import com.zql.mapper.UserMapper;
import com.zql.pojo.User;
import com.zql.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* @Author:Daniel
* @Version 1.0
*/
@Service
public class UserServiceImpl implements UserService {
@Autowired
UserMapper userMapper;
@Override
public User queryByName(String name) {
return userMapper.queryByName(name);
}
}
- 在测试类测试代码
package com.zql;
import com.zql.service.impl.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.queryByName("Daniel"));
}
}
- 可以看到查询成功
- 这样就可以去改 Realm的代码,开始的用户名和密码都是手写伪造的
UserRealm代码修改如下:
package com.zql.config;
import com.zql.pojo.User;
import com.zql.service.UserService;
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.springframework.beans.factory.annotation.Autowired;
/**
* @Author:Daniel
* @Version 1.0
*/
//自定义的 UserReal
public class UserRealm extends AuthorizingRealm {
@Autowired
UserService userService;
//授权
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
System.out.println("执行了=>认证doGetAuthorizationInfo");
return null;
}
//认证
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
//System.out.println("执行了=>授权doGetAuthenticationInfo");
// 用户名,密码到数据库中取
/* String username = "root";
String password = "123";*/
UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) authenticationToken;
User user = userService.queryByName(usernamePasswordToken.getUsername());
if(user == null){ //UnknownAccountException
return null;
}
//密码认证:shiro做
//密码可以加密:md5,md5盐值加密
return new SimpleAuthenticationInfo("",user.getPwd(),"");
}
}
- 现在的话登录用户就是数据库中的,启动项目测试,可以看到登录成功
七、shiro 实现请求授权
- 在ShiroConfig添加部分代码,如图:
- 登录用户点击添加的请求,显示未授权401的错误
- 正常情况下,授权会跳转到未授权的页面,所以才MyController写一个跳转到未授权的页面方法
@ResponseBody
@RequestMapping("/noauth")
public String unauthorized(){
return "无法访问此页面";
}
- ShiroConfig类修改一下:
- 重启项目测试,发现已经可以跳转到我们设置的未授权的页面了
- 怎样添加add页面的授权呢,在UserRealm修改下代码,因为ShiroConfig设定了add页面需要权限,所以要在UserRealm添加权限
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
System.out.println("执行了=>认证doGetAuthorizationInfo");
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
info.addStringPermission("user:add");
return info;
}
- 但是所有登录的用户都有此权限,所以我打算把数据库的表新增一个权限的字段,添加下权限
- 记得改下User实体类
- UserRealm类
- ShiroConfig里添加对update的过滤
- 开启项目测试:
登录有add权限的账号 Daniel
点击add,成功跳转
登录有update权限的账号 hollow
点击add & update,成功跳转
八、shiro 整合 thymeleaf
- 导入对应的依赖
<!--shiro整合thymeleaf-->
<dependency>
<groupId>com.github.theborakompanioni</groupId>
<artifactId>thymeleaf-extras-shiro</artifactId>
<version>2.0.0</version>
</dependency>
- ShiroConfig 类添加方法
//整合ShiroDialect:用来整合shiro thymeleaf
@Bean
public ShiroDialect getShiroDialect(){
return new ShiroDialect();
}
- 在index.html添加约束并且修改add和update
xmlns:shiro="http://www.thymeleaf.org/thymeleaf-extras-shiro"
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.themeleaf.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 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>
- 运行项目测试
(1)没有权限(没有权限不会显示add和update的页面,就会被拦截了)
(2) 只有add 权限
(2) 超级 权限
- 为了让登录后不在显示登录按钮,需要在UserRealm里添加代码
Subject subject = SecurityUtils.getSubject();
Session session = subject.getSession();
session.setAttribute("loginUser",user);
然后在前端判断它从而决定显不显示登录按钮,
index.html:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.themeleaf.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 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>
<br>
<div th:if="${session.loginUser==null}"><a th:href="@{/toLogin}">登录</a></div>
<div><a th:href="@{/logout}">注销</a></div>
</body>
</html>
- 在后端 MyController.java 中添加
@RequestMapping("/logout")
public String logout(){
return "login";
}
- 运行项目检查,登录后登录按钮消失
文章源码 springboot-08-shiro