12. SpringBoot-shiro
12.1 快速入門
1、導入依賴
<dependencies>
<!-- shiro-core -->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>1.8.0</version>
</dependency>
<!-- configure logging -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>1.8.0-beta0</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.8.0-beta0</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
</dependencies>
2、創建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
3、創建shiro.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
4、創建Quickstart.java類
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.realm.text.IniRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
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();
DefaultSecurityManager securityManager = new DefaultSecurityManager();
IniRealm iniRealm = new IniRealm("classpath:shiro.ini");
securityManager.setRealm(iniRealm);
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
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("Subject=》session! [" + value + "]");
}
// let's login the current user so we can check against roles and permissions:
// 判斷當前的用戶是否被認證
if (!currentUser.isAuthenticated()) {
// token : 令牌
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);
}
}
5、啟動測試
12.2 shiro-Mybatis
1、導入依賴
<dependencies>
<!-- thymeleaf-extras-shiro -->
<dependency>
<groupId>com.github.theborakompanioni</groupId>
<artifactId>thymeleaf-extras-shiro</artifactId>
<version>2.1.0</version>
</dependency>
<!-- lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.22</version>
<scope>provided</scope>
</dependency>
<!-- 引入Mybatis mybatis-spring-boot-starter -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.0</version>
</dependency>
<!-- mysql 連接驅動 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.27</version>
</dependency>
<!-- log4j -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<!-- druid -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.8</version>
</dependency>
<!--
1. Subject 用戶
2. SecurityManager 管理所有用戶
3. Realm 連接數據
-->
<!--整合shiro-spring-boot-web-starter-->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring-boot-web-starter</artifactId>
<version>1.8.0</version>
</dependency>
<!-- spring-boot-starter-thymeleaf -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
<version>2.5.6</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
2、配置數據庫
application.yaml
spring:
datasource:
username: root
password: aadzj
# 如果報錯是時區問題 加上 serverTimezone=UTC 就OK
url: jdbc:mysql://localhost:3306/userdb?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
driver-class-name: com.mysql.cj.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource
#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.Properity
#則導入log4j 依賴就行
filters: stat,wall,log4j
maxPoolPreparedStatementPerConnectionSize: 20
useGlobalDataSourceStat: true
connectionoProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
3、編寫實體類
文件路徑:com--dzj--pojo--User.java
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
private String id;
private String username;
private String password;
private String perms;
}
4、編寫Mapper接口
文件路徑:com--dzj--mapper--UserMapper.java
@Repository
@Mapper
public interface UserMapper {
public User queryByUsername(String username);
}
5、配置全限定類別名,關聯配置文件
同樣在application.yaml中配置即可
# mybatis整合 全限定類別名,關聯配置文件
mybatis:
type-aliases-package: com.dzj.pojo
mapper-locations: classpath:mapper/*.xml
6、編寫Mapper映射文件
文件路徑: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.dzj.mapper.UserMapper">
<select id="queryByUsername" parameterType="String" resultType="User">
select * from userdb.user where username = #{username}
</select>
</mapper>
7、編寫業務層
接口UserService.java
文件路徑:com--dzj--service--UserService.java
package com.dzj.service;
import com.dzj.pojo.User;
public interface UserService {
public User queryByUsername(String username);
}
接口UserService.java實現類
文件路徑:com--dzj--service--UserServiceImpl.java
@Service
public class UserServiceImpl implements UserService {
@Autowired
UserMapper userMapper;
@Override
public User queryByUsername(String username) {
return userMapper.queryByUsername(username);
}
}
8、編寫controller層
文件路徑:com--dzj-controller--MyController.java
package com.dzj.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;
@Controller
public class MyController {
@RequestMapping({"/","/index","/index.html"})
public String toIndex(Model model){
model.addAttribute("msg","helle,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); //執行登錄方法,如果沒有異常就說明OK了
return "index";
} catch (UnknownAccountException e) {// 用戶名不存在
model.addAttribute("msg","用戶名錯誤");
return "login";
}catch (IncorrectCredentialsException e) {// 密碼不存在
model.addAttribute("msg","密碼錯誤");
return "login";
}
}
@RequestMapping("/noauth")
@ResponseBody
public String uauthorized(){
return "未經授權無法訪問此頁面!";
}
}
9、編寫shiro配置類
文件路徑:com--dzj--config--ShiroConfig.java
package com.dzj.config;
import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
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,步驟3
@Bean(name = "shiroFilterFactoryBean")
public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("defaultWebSecurityManager")DefaultWebSecurityManager securityManager){
ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
// 設置安全管理器
bean.setSecurityManager(securityManager);
//添加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/add","perms[user:add]");
filterMap.put("/user/update","perms[user:update]");//perms只有授權了才能訪問對象的頁面
filterMap.put("/user/*","authc"); //authc主要通過了登錄認證,就能進入根目錄user
//授權
bean.setFilterChainDefinitionMap(filterMap);
//設置登錄請求認證
bean.setLoginUrl("/toLogin");
//未授權頁面
bean.setUnauthorizedUrl("/noauth");
return bean;
}
// DefaultWebSecurityManager,步驟2
@Bean(name="defaultWebSecurityManager")
public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm){
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
securityManager.setSessionManager(sessionManager());
// 關聯UserRealm
securityManager.setRealm(userRealm);
return securityManager;
}
/*
在Shiro進行第一次重定向時,會在url后攜帶jsessionid,這會導致400錯誤(無法找到該網頁)。解決辦法:在Shiro的配置類中的sessionManager()方法中,將sessionIdUrlRewritingEnabled屬性設置為false。該方法返回一個DefaultWebSessionManager實例。
*/
@Bean
public DefaultWebSessionManager sessionManager() {
DefaultWebSessionManager sessionManager = new DefaultWebSessionManager();
sessionManager.setSessionIdUrlRewritingEnabled(false);
return sessionManager;
}
// 創建 Realm 對象,需要自定義類,步驟1
@Bean
public UserRealm userRealm(){
return new UserRealm();
}
//整合shiroDialect:用來整合shiro 和 thymeleaf
@Bean
public ShiroDialect getShiroDialect(){
return new ShiroDialect();
}
}
編寫UserRealm類
文件路徑:com--dzj--config--UserRealm.java
package com.dzj.config;
import com.dzj.pojo.User;
import com.dzj.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;
// 自定義的 UserRealm,繼承自AuthorizingRealm
public class UserRealm extends AuthorizingRealm {
@Autowired
UserService userService;
// 授權
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
System.out.println("執行了=>授權doGetAuthorizationInfo");
//SimpleAuthorizationInfo
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
// info.addStringPermission("user:add");
Subject subject = SecurityUtils.getSubject();
User currentUser = (User) subject.getPrincipal();//拿到user對象
//設置當前用戶的權限,從數據庫中獲取
info.addStringPermission(currentUser.getPerms());
return info;
}
// 認證
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
System.out.println("執行了=>認證doGetAuthenticationInfo");
UsernamePasswordToken userToken = (UsernamePasswordToken) token;
// 用戶名,密碼 可以數據庫中取
// String username = "root";
// String password = "aadzj";
//用戶名認證
// if(!userToken.getUsername().equals(username)){
// return null; //自動拋出異常,UnknownAccountException
// }
//連接真實的數據庫
User user = userService.queryByUsername(userToken.getUsername());
if(user==null){
return null;//返回null則自動拋出異常,UnknownAccountException
}
//可以加密:MD5 MD5鹽值加密
//密碼認證不需要我們做,shiro做~,加密了
return new SimpleAuthenticationInfo(user,user.getPassword(),"");
}
}
10、前端頁面
index.html
文件路徑:resources--templates--index.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org"
xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>首頁</h1>
<p th:text="${msg}"></p>
<shiro:guest><a th:href="@{/toLogin}">登錄</a></shiro:guest>
<!--<div shiro:notAuthenticated><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
文件路徑:resources--templates--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>
<form th:action="@{/login}" method="get">
<p>用戶名:<input type="text" name="username"></p>
<p>密碼:<input type="text" name="password"></p>
<p><input type="submit" value="登錄"></p>
</form>
<p th:text="${msg}" style="color:red"></p>
</body>
</html>
add.html
文件路徑:resources--templates--user--add.html
<body>
<h1>add</h1>
</body>
update.html
文件路徑:resources--templates--user--update.html
<body>
<h1>update</h1>
</body>
搞定,結束~